[
  {
    "path": ".editorconfig",
    "content": "# editorconfig.org\nroot = true\n\n[*]\nindent_style = space\nindent_size = 2\ninsert_final_newline = true\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\n.vscode\n"
  },
  {
    "path": ".travis.yml",
    "content": "language: c\nenv:\n  - ARDUINO_VERSION=1.6.13\nbefore_install:\n  - \"/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16\"\n  - sleep 3\n  - export DISPLAY=:1.0\n  - wget http://downloads.arduino.cc/arduino-$ARDUINO_VERSION-linux64.tar.xz\n  - tar xf arduino-$ARDUINO_VERSION-linux64.tar.xz\n  - sudo mv arduino-$ARDUINO_VERSION /usr/local/share/arduino\n  - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino\ninstall:\n  - ln -s $PWD /usr/local/share/arduino/libraries/TheThingsNetwork\n  - arduino --install-library \"DHT sensor library:1.3.0,Adafruit Unified Sensor:1.0.2\"\nbefore_script:\n  # Replace placeholders with actual frequency plan (on Mac OS folow -i by '')\n  - find $PWD/examples -type f -name \"*.ino\" -exec sed -i 's/REPLACE_ME/TTN_FP_EU868/g' {} +\nscript:\n  - test/verify arduino:avr:leonardo examples/SendABP/SendABP.ino\n  - test/verify arduino:avr:leonardo examples/DeviceInfo/DeviceInfo.ino\n  - test/verify arduino:avr:leonardo examples/TheThingsMessage/Receive/Receive.ino\n  - test/verify arduino:avr:leonardo examples/TheThingsMessage/Send/Send.ino\n  - test/verify arduino:avr:leonardo examples/PassThrough/PassThrough.ino\n  - test/verify arduino:avr:leonardo examples/QuickStart/QuickStart.ino\n  - test/verify arduino:avr:leonardo examples/Receive/Receive.ino\n  - test/verify arduino:avr:leonardo examples/ReceiveClassC/ReceiveClassC.ino\n  - test/verify arduino:avr:leonardo examples/SendOTAA/SendOTAA.ino\n  - test/verify arduino:avr:leonardo examples/Sensors/DHT/DHT.ino\n  - test/verify arduino:avr:leonardo examples/Sensors/LightSensor/LightSensor.ino\n  - test/verify arduino:avr:leonardo examples/Workshop/Workshop.ino\n  - test/verify arduino:avr:leonardo test/TheThingsMessage/TheThingsMessage.ino\n  - test/verify arduino:avr:leonardo test/TheThingsNetwork/TheThingsNetwork.ino\nnotifications:\n  email:\n    on_success: change\n    on_failure: change\n"
  },
  {
    "path": "AUTHORS",
    "content": "Johan Stokking <johan@thethingsnetwork.org>\nFokke Zandbergen <mail@fokkezb.nl>\nAlessandro Blason <mrblason@gmail.com>\nJP Meijers <git@jpmeijers.com>\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "## Contributing\n\nWe'd ❤️ to welcome your contribution. Please make sure your changes include:\n\n1.  Examples: [examples](examples)\n2.  Syntax highlighting: [keywords.txt](keywords.txt)\n3.  Documentation: [docs](docs)\n4.  Tests: [test](test)\n5.  Verification of the examples and tests: [.travis.yml](.travis.yml)\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2016 The Things Network\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "Makefile",
    "content": "PROTOC = $(NANOPB)/generator-bin/protoc --proto_path=src/api --nanopb_out=\"-v:src\"\n\n.PHONY: proto\n\nproto:\n\t$(PROTOC) src/api/*.proto\n"
  },
  {
    "path": "README.md",
    "content": "# The Things Network Arduino Library\n[![Build Status](https://travis-ci.org/TheThingsNetwork/arduino-device-lib.svg?branch=master)](https://travis-ci.org/TheThingsNetwork/arduino-device-lib)\n\nThis is an [Arduino Library](https://www.arduino.cc/en/Guide/Libraries) for Arduino devices like [The Things Uno](https://www.thethingsnetwork.org/docs/devices/uno/) and [Node](https://www.thethingsnetwork.org/docs/devices/node/) to communicate via [The Things Network](https://www.thethingsnetwork.org).\n\n> At the moment this library requires devices to feature a [Microchip RN2xx3 module](http://www.microchip.com/design-centers/wireless-connectivity/embedded-wireless/lora-technology).\n\n## Installation\n\n* Install the library by [Using the Library Manager](https://www.arduino.cc/en/Guide/Libraries#toc3)\n* **OR** by [Importing the .zip library](https://www.arduino.cc/en/Guide/Libraries#toc4) using either the [master](https://github.com/TheThingsNetwork/arduino-device-lib/archive/master.zip) or one of the [releases](https://github.com/TheThingsNetwork/arduino-device-lib/releases) ZIP files.\n\n## Documentation\n\n* [The Things Network Documentation](https://www.thethingsnetwork.org/docs/devices/arduino/)\n* API References:\n    * [TheThingsNetwork](docs/TheThingsNetwork.md)\n    * [TheThingsMessage](docs/TheThingsMessage.md)\n\n## Examples\n\nThe library comes with [examples](examples). After installing the library you need to restart the Arduino IDE before they can be found under **File > Examples > TheThingsNetwork**.\n"
  },
  {
    "path": "docs/CayenneLPP.md",
    "content": "# API Reference\n\nThe `CayenneLPP` class enables Arduino devices to encode data with the Cayenne Low Power Payload (LPP). [Read more about Cayenne LPP](https://mydevices.com/cayenne/docs/lora/#lora-cayenne-low-power-payload)\n\n## Class: `CayenneLPP`\n\nInclude and instantiate the CayenneLPP class. The constructor takes the size of the allocated buffer. Depending on the LoRa frequency plan and data rate used, the maximum payload varies. It's safe to send up to 51 bytes of payload.\n\n```c\n#include <CayenneLPP.h>\n\nCayenneLPP lpp(uint8_t size);\n```\n\n- `uint8_t size`: The maximum payload size to send, e.g. `51`.\n\n## Example\n\n```c\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\nCayenneLPP lpp(51);\n\nlpp.reset();\nlpp.addTemperature(1, 22.5);\nlpp.addBarometricPressure(2, 1073.21);\nlpp.addGPS(3, 52.37365, 4.88650, 2);\n\nttn.sendBytes(lpp.getBuffer(), lpp.getSize());\n```\n\nSee the [CayenneLPP](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/CayenneLPP/CayenneLPP.ino) example. \n\n## Method: `reset`\n\nResets the buffer.\n\n```c\nvoid reset(void);\n```\n\n## Method: `getSize`\n\nReturns the size of the buffer.\n\n```c\nuint8_t getSize(void);\n```\n\n## Method: `getBuffer`\n\nReturns a pointer to the buffer.\n\n```c\nuint8_t *getBuffer(void);\n```\n\n## Method: `copy`\n\nCopies the internal buffer to a specified buffer and returns the copied size.\n\n```c\nuint8_t copy(uint8_t *buffer);\n```\n\n## Methods: `add...`\n\nAdd data to the buffer. The `channel` parameter acts as a key for the data field. The data fields you send are dynamic; you can selectively send data as long as the channel matches.\n\n```c\nuint8_t addDigitalInput(uint8_t channel, uint8_t value);\nuint8_t addDigitalOutput(uint8_t channel, uint8_t value);\n\nuint8_t addAnalogInput(uint8_t channel, float value);\nuint8_t addAnalogOutput(uint8_t channel, float value);\n\nuint8_t addLuminosity(uint8_t channel, uint16_t lux);\nuint8_t addPresence(uint8_t channel, uint8_t value);\nuint8_t addTemperature(uint8_t channel, float celsius);\nuint8_t addRelativeHumidity(uint8_t channel, float rh);\nuint8_t addAccelerometer(uint8_t channel, float x, float y, float z);\nuint8_t addBarometricPressure(uint8_t channel, float hpa);\nuint8_t addGyrometer(uint8_t channel, float x, float y, float z);\nuint8_t addGPS(uint8_t channel, float latitude, float longitude, float meters);\n```\n"
  },
  {
    "path": "docs/TheThingsMessage.md",
    "content": "# API Reference\n\n## Class: `TheThingsMessage`\nThe `TheThingsMessage` class provides structs for sensor and application data you can encode and decode as bytes.\n\n```c\n#include <TheThingsMessage.h>\n```\n\n## Type: `devicedata_t`\n\nCreate a struct of this type using `api_DeviceData_init_default` as defaults.\n\n```c\ndevicedata_t data = api_DeviceData_init_default;\n```\n\nThen in your `setup()` function select what fields of the struct should be included when encoding it as bytes:\n\n```c\ndata.has_motion = true;\ndata.has_water = false;\ndata.has_temperature_celcius = true;\ndata.has_temperature_fahrenheit = true;\ndata.has_humidity = true;\n```\n\nIn your `loop()` function read your sensors and set the fields of the struct:\n\n```c\ndata.motion = true;\ndata.water = 682;\ndata.temperature_celcius = 30\ndata.temperature_fahrenheit = 86;\ndata.humidity = 97;\n```\n\n### Additional analog readings\n\nYou can also add other analog readings.\n\n> **TODO:** Document how this works and include in example.\n\n## Method: `encodeDeviceData`\n\nEncode the message you want to send.\n\n```c\nstatic void encodeDeviceData(devicedata_t *data, byte **buffer, size_t *size);\n```\n\n- `devicedata_t *data`: Structure containing typical fields that devices send.\n- `byte **buffer`: Bytes to send.\n- `size_t *size`: The number of bytes to send.\n\nUsage:\n\n```c\nbyte *buffer;\nsize_t size;\nTheThingsMessage::encodeDeviceData(&data, &buffer, &size);\n```\n\n## Method: `decodeAppData`\n\nDecode the message you received.\n\n```c\nstatic bool decodeAppData(appdata_t *receiveData, const byte *payload, size_t length);\n```\n\n- `appdata_t *receiveData`: Structure containing all the message we can interpret.\n- `const byte *payload`: Bytes received.\n- `size_t *length`: The number of bytes.\n\nUsage:\n\n```c\nconst byte *payload;\nsize_t length;\nTheThingsMessage::decodeAppData(&receiveData, payload, length);\n```\n"
  },
  {
    "path": "docs/TheThingsNetwork.md",
    "content": "# API Reference\n\nThe `TheThingsNetwork` class enables Arduino devices with supported LoRaWAN modules to communicate via The Things Network. Currently supported LoRaWAN modules are the Microchip RN2483 and the RN2903.\n\n## Class: `TheThingsNetwork`\n\nInclude and instantiate the TheThingsNetwork class. The constructor initializes the library with the Streams it should communicate with. It also sets the value of the spreading factor, the frequency plan, and the frequency sub-band.\n\n```c\n#include <TheThingsNetwork.h>\n\nTheThingsNetwork ttn(Stream& modemStream, Stream& debugStream, fp_ttn_t fp, uint8_t sf = 7, uint8_t fsb = 2);\n```\n\n- `Stream& modemStream`: Stream for the LoRa modem ([see notes](https://www.thethingsnetwork.org/docs/devices/arduino/usage.html)).\n- `Stream& debugStream`: Stream to write debug logs to ([see notes](https://www.thethingsnetwork.org/docs/devices/arduino/usage.html)).\n- `fp_ttn_fp fp`: The frequency plan: `TTN_FP_EU868`, `TTN_FP_US915`, `TTN_FP_AS920_923`, `TTN_FP_AS923_925` or `TTN_FP_KR920_923` depending on the region you deploy in. See [the wiki](https://www.thethingsnetwork.org/wiki/LoRaWAN/Frequencies/Frequency-Plans).\n- `uint8_t sf = 7`: Optional custom spreading factor. Can be `7` to `10` for `TTN_FP_US915` and `7` to `12` for other frequency plans. Defaults to `7`.\n- `uint8_t fsb = 2`: Optional custom frequency subband. Can be `1` to `8`. Defaults to `2` (for US915).\n\n## Method: `reset`\n\nPerforms a software reset of the RN module. This does not clear saved state, e.g. provisioned keys.\n\n```c\nvoid reset(bool adr);\n```\n\n- `bool adr`: Enable/disable Adaptive Data Rate.\n\n## Method: `hardReset`\n\nPerforms a hardware reset of the RN module. Input parameter is the pin to which the reset pin from the module is connected. This does clear saved state, e.g., provisioned keys.\n\n```c\nvoid hardReset(uint8_t resetPin);\n```\n\n- `uint8_t resetPin`: The output pin that is connected to the module's reset pin. The output pin should be configured as output and set to high by the user.\n\n## Method: `getHardwareEui`\n\nGets the unique hardware EUI, often used as the DevEUI.\n\n```c\nsize_t getHardwareEui(char *buffer, size_t size);\n```\n\n## Method: `getAppEui`\n\nGets the provisioned AppEUI. The AppEUI is set using `provision()` or `join()`.\n\n```c\nsize_t getAppEui(char *buffer, size_t size);\n```\n\n## Method: `getVersion`\n\nGets the response from a `sys get ver` command (i.e. the hardware model, the the software version, etc.).\n\n```c\nsize_t getVersion(char *buffer, size_t size);\n```\n\n## Method: `showStatus`\n\nWrites information about the device and LoRa module to `debugStream`.\n\n```c\nvoid showStatus();\n```\n\nWill write something like:\n\n```bash\nEUI: 0004A30B001B7AD2\nBattery: 3223\nAppEUI: 70B3D57EF000001C\nDevEUI: 0004A30B001B7AD2\nData Rate: 5\nRX Delay 1: 1000\nRX Delay 2: 2000\n```\n\nSee the [DeviceInfo](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/DeviceInfo/DeviceInfo.ino) example.\n\n## Method: `onMessage`\n\nSets a function that will be called to process incoming messages. You'll want to do this in your `setup()` function and then define a `void (*cb)(const byte* payload, size_t length, port_t port)` function somewhere else in your sketch.\n\n```c\nvoid onMessage(void (*cb)(const byte* payload, size_t length, port_t port));\n```\n\n- `const byte* payload`: Bytes received.\n- `size_t length`: Number of bytes.\n- `port_t port`: The port addressed.\n\nSee the [Receive](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/Receive/Receive.ino) example.\n\n## Method: `join`\n\nActivate the device via OTAA (default).\n\n```c\nbool join(const char *appEui, const char *appKey, int8_t retries = -1, uint32_t retryDelay = 10000, lorawan_class = CLASS_A);\nbool join(int8_t retries = -1, uint32_t retryDelay = 10000);\n```\n\n- `const char *appEui`: Application EUI the device is registered to.\n- `const char *appKey`: Application Key assigned to the device.\n- `int8_t retries = -1`: Number of times to retry after failed or unconfirmed join. Defaults to `-1`, which means infinite.\n- `uint32_t retryDelay = 10000`: Delay in ms between attempts. Defaults to 10 seconds.\n- `lorawan_class = CLASS_A`: The LoRaWAN class to use for downlink message reception.\n\nReturns `true` or `false` depending on whether it received confirmation that the activation was successful before the maximum number of attempts.\n\nCall the method without the first two arguments if the device's LoRa module comes with pre-flashed values.\n\n## Method: `personalize`\n\nActivate the device via ABP.\n\n```c\nbool personalize(const char *devAddr, const char *nwkSKey, const char *appSKey, bool reset_first);\nbool personalize();\n```\n\n- `const char *devAddr`: Device Address assigned to the device.\n- `const char *nwkSKey`: Network Session Key assigned to the device for identification.\n- `const char *appSKey`: Application Session Key assigned to the device for encryption.\n- `bool reset_first`: Soft reset the module before performing any other action. Default is `true`.\n\nReturns `true` or `false` depending on whether the activation was successful.\n\nCall the method with no arguments if the device's LoRa module comes with pre-flashed values.\n\nSee the [SendABP](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/SendABP/SendABP.ino) example.\n\n## Method: `setClass`\n\nChange the downlink receive LoRaWAN Class. Class C is only supported in firmware version 1.0.5 and up. For other firmware versions, this method will have no effect.\n\n```c\nbool setClass(lorawan_class p_lw_class);\n```\n\n- `lorawan_class p_lw_class`: The LoRaWAN class. Either `CLASS_A` or `CLASS_C`.\n\nReturns `true` if the change was successful, or `false` if not successful.\n\nThe receive window only opens after a transmit. Therefore Class C receive will only start after calling `sendBytes()`.\n\nSee the [ReceiveClassC](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/ReceiveClassC/ReceiveClassC.ino) example.\n\n## Method: `sendBytes`\n\nSend a message to the application using raw bytes.\n\n```c\nttn_response_t sendBytes(const byte* payload, size_t length, port_t port = 1, bool confirm = false, uint8_t sf = 0);\n```\n\n- `const byte* payload `: Bytes to send.\n- `size_t length`: The number of bytes. Use `sizeof(payload)` to get it.\n- `port_t port = 1`: The port to address. Defaults to `1`.\n- `bool confirm = false`: Whether to ask for confirmation—defaults to `false`. If confirmation fails, the method will return the error code `TTN_ERROR_UNEXPECTED_RESPONSE`.\n- `uint8_t sf = 0`: Override the spreading factor (SF). If the default value `0` is passed, the SF is not changed from the constructor or previous value.\n\nReturns a success or error code and logs the related error message:\n\n* `TTN_ERROR_SEND_COMMAND_FAILED`: Send command failed.\n* `TTN_SUCCESSFUL_TRANSMISSION`: Successful transmission.\n* `TTN_SUCCESSFUL_RECEIVE`: Successful transmission. Received \\<N> bytes\n* `TTN_UNSUCCESSFUL_RECEIVE`: if we sent a confirmed message but did not get an acknowledgment\n* `TTN_ERROR_UNEXPECTED_RESPONSE`: Unexpected response: \\<Response>\n\nSee the [SendOTAA](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/SendOTAA/SendOTAA.ino) example.\n\n## Method: `poll`\n\nCalls `sendBytes()` with `{ 0x00 }` as payload to poll for incoming messages.\n\n```c\nint8_t poll(port_t port = 1, bool confirm = false);\n```\n\n- `port_t port = 1`: The port to address. Defaults to `1`.\n- `bool confirm = false`: Whether to ask for confirmation.\n- `bool modem_only = false`: (only class A) Whether to avoid sending an empty frame and only listen to the modem's incoming message.\n\nReturns the result of `sendBytes()`, with one difference:\n* `TTN_UNSUCCESSFUL_RECEIVE`: In class C or class A `modem_only` poll, we only listened, and there was no incoming message.\n\nThe `modem_only` option for poll may be useful if the sending procedure did not terminate yet, e.g., we sent a confirmed message and did not get a response. In such a case, the modem will independently retry. With `modem_only` we thus just listen to the modem output to verify the status of the further attempts.\n\nSee the [Receive](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/Receive/Receive.ino) example.\n\n## Method: `provision`\n\nSets the information needed to activate the device via OTAA, without actually activating. Call join() without the first 2 arguments to activate.\n\n```c\nbool provision(const char *appEui, const char *appKey, bool reset_first);\n```\n\n- `const char *appEui`: Application Identifier for the device.\n- `const char *appKey`: Application Key assigned to the device.\n- `bool reset_first`: Soft reset the module before performing any other action. Default is `true`.\n\n## Method: `sleep`\n\nSleep the LoRa module for a specified number of milliseconds.\n\n```c\nvoid sleep(unsigned long mseconds);\n```\n\n- `unsigned long mseconds`: number of milliseconds to sleep.\n\n## Method: `wake`\n\nWake up the LoRa module from sleep before the expiration of the defined time.\n\n```c\nvoid wake();\n```\n\n## Method: `linkCheck`\n\nSets the time interval for the link check process to be triggered. The next uplink will include a Link Check Request MAC command when the interval expires. This method should be called after joining has been completed.\n\n```c\nvoid linkCheck(uint16_t seconds);\n```\n\n- `uint16_t seconds`: the time interval in seconds. A value of 0 will disable the link check process.\n\n## Method: `getLinkCheckGateways`\n\nGets the number of gateways that successfully received the last Link Check Request frame.\n\n```c\nuint8_t getLinkCheckGateways();\n```\n\n## Method: `getLinkCheckMargin`\n\nGets the demodulation margin as received in the last Link Check Answer frame.\n\n```c\nuint8_t getLinkCheckMargin();\n```\n\n# Additional for operation\n\n## Method: `getVDD`\n\nReturns the voltage in millivolt (mV) measured by the RN2xxx LoRa module. It's for information only since we don't know how it's calculated but looks accurate.\n\n```c\nuint16_t getVDD();\n```\n\n## Method: `getStatus`\n\nReturns the status of the RN2xxx modem's state machine in one of the nine possible states of `ttn_modem_status_t`. Unfortunately, due to a firmware bug, this does not work for RN2493 modems with firmware < 1.05. If unsuccessful, the method returns `TTN_MODEM_READ_ERROR`.\n\n```c\nenum ttn_modem_status_t getStatus()\n```\n\nPossible return codes are:\n\n- `TTN_MODEM_READ_ERR` could not read out the status\n- `TTN_MODEM_IDLE` modem idle, ready for next tx\n- `TTN_MODEM_TX` modem transmitting\n- `TTN_MODEM_BEFORE_RX` waiting time between tx and rx1 windows\n- `TTN_MODEM_RX1` RX1 window open\n- `TTN_MODEM_BEFORE_RX2` waiting time between the two rx windows\n- `TTN_MODEM_RETRY_DELAY` waiting before retry again\n- `TTN_MODEM_APB_DELAY` APB join delay\n- `TTN_MODEM_C_RX1` RX1 window open in class C\n- `TTN_MODEM_C_RX2` RX2 window open in class C\n\n\n## Method: `getLastError`\n\nReturns the last error code encountered by the RN2xxx modem. The error code may be one of the twelve possible errors of `ttn_response_code_t`. Call this method after an unsuccessful execution.\n\n```c\nttn_response_code_t getLastError();\n```\n\nFor example, suppose you perform a send via `sendbytes` and get a `TTN_ERROR_SEND_COMMAND_FAILED`. In that case, you can call this method and get a `TTN_ERR_BUSY`, which means the modem already has a message to send in the buffer.\n\nPossible error codes are:\n\n - `TTN_OK` nothing actually went wrong.\n - `TTN_ERROR_BUSY` busy sending a message\n - `TTN_ERROR_FRAME_COUNTER_ERROR` if the frame counter rolled over\n - `TTN_ERROR_INVALID_CLASS` selected LoRaWan class is invalid\n - `TTN_ERROR_INVALID_LENGTH` data length is not available for the current configuration\n - `TTN_ERROR_INVALID_PARAMETER` invalid parameter specified\n - `TTN_ERROR_NO_KEY_INTITIALIZED` network keys not initialized\n - `TTN_ERROR_MAC_PAUSE` mac level has been paused\n - `TTN_ERROR_NO_KEY_MULTICAST` multicast keys not set\n - `TTN_ERROR_NO_FREE_CHANNEL` all channels exhausted their duty cycle, so we can not send\n - `TTN_ERROR_NOT_JOINED` modem did not join a network\n - `TTN_ERROR_SILENT` if the module is in a Silent Immediately state\n - `TTN_ERROR_ERR` other unspecified error \n\n## Method: `getFCU`\n\nReturns the next used uplink frame counter. In LoRaWan, this counter must match on both sides, server, and end-node, for a transmission to be successful. Please note that although the counter is 32bit, the frame itself contains only the lowest 16bits of the message. Nonetheless, the message is encrypted using all 32bits of the FCU in the key. Therefore, it _must_ be up to date and in sync. If the readout is unsuccessful, the method returns 0. However, the first frame after a reset is also set to 0.\n\n```c\nuint32_t getFCU();\n```\n\n## Method: `setFCU`\n\nSets the FCU as of above. The method returns true if successful.\n\n```c\nbool setFCU(uint32_t fcu);\n```\n\n## Method: `getFCD`\n\nReturns the next expected downlink frame counter. In LoRaWan, this counter must match on both sides, server, and end-node, for a transmission to be successful. Please note that although the counter is 32bit, the frame itself contains only the lowest 16bits of the message. Nonetheless, the message is encrypted using all 32bits of the FCD in the key. Therefore, it _must_ be up to date and in sync. If the readout is unsuccessful, the method returns 0. However, the first frame after a reset is also sent with frame number 0.\n\n```c\nuint32_t getFCD();\n```\n\n## Method: `setFCD`\n\nSets the FCD as of above. The method returns true if successful.\n\n```c\nbool setFCD(uint32_t fcd);\n```\n\n## Method: `getDR`\n\nReturns the data rate that the modem will use for the next uplink frame. If the readout is unsuccessful, the method returns -1.\n\n```c\nint8_t getDR();\n```\n\n## Method: `setDR`\n\nSets the data rate to use for the next uplink frame; see `getDR`. This is mainly useful for operating with adaptive data rate (ADR) in `off`; see `setADR`. If ADR is on, it will set the DR for the next uplink, but the value for the successive transmissions may change according to the ADR protocol. The range of valid DR values depends on the frequency plan. The method returns true if successful.\n\n```c\nbool setDR(uint8_t dr);\n```\n\n## Method: `getPowerIndex`\n\nReturns the power index that the LoRa modem will use for the next uplink frame. If the readout is unsuccessful, the method returns -1.\n\n```c\nint8_t getPowerIndex();\n```\n\n## Method: `setPowerIndex`\n\nSets the power index to use for the next uplink frame; see `getPowerIndex`. This is mainly useful for operating with adaptive data rate (ADR) in `off`; see `setADR`. If ADR is on, it will set the power index for the next uplink. Still, the value for the following transmissions may change according to the ADR protocol. The range of valid values depends on modem hardware and the frequency plan. The method returns true if successful.\n\n```c\nbool setPowerIndex(uint8_t index);\n```\n\n## Method: `setChannel`\n\nThe TTN module can store multiple channel configurations. With this method, you can configure a logical channel of the modem by defining frequency in `Hz`, minimum and maximum usable data rates for the channel. Data rates depend on the used frequency plan and must be between 0 and 15. The method returns true if a configuration is successful.\n\n```c\nbool setChannel(uint8_t channel, uint32_t frequency = 0l, uint8_t dr_min = 255, uint8_t dr_max = 255);\n```\n\nAlternatively, you can only re-set the data rates for the channel by leaving (omitting) frequency to 0.\n \n```c\nsetChannel(2, dr_min = 0, dr_max = 4);\n```\n  \nOr, you can only re-set the frequency for the channel by leaving (omitting) dr_* to 255.\n\n```c\nsetChannel(2, 863500000);\n```\n\nHowever, the whole configuration must have been set at least once to be successful in both cases.\n\n## Method: `setRX2Channel`\n\nIn some plans, the TTN module stores a common RX2 downlink channel, which is used for RX2 window communication. With this method, you can configure this channel by defining frequency in `Hz` and its data rates. The valid data rates depend on the used frequency plan. The method returns true if a configuration is successful.\n\n```c\nbool setRx2Channel(uint32_t frequency, uint8_t dr);\n```\n\n## Method: `getChannelStatus`\n\nThe TTN module can store multiple channel configurations. This method returns true if the channel is enabled for transmission and/or receiving.\n\n```c\nbool getChannelStatus (uint8_t channel);\n```\n\n## Method: `setChannelStatus`\n\nSets the channel status of the selected channel number; see `getChannelStatus`. If set to true and the channel is configured, the modem may use the channel for transmission. The method returns true if successful.\n\n```c\nbool setChannelStatus (uint8_t channel, bool status);\n```\n\n## Method: `setChannelDCycle`\n\nSets the channel maximum allowed duty cycle of a selected channel number in `%`. Depending on regional regulations, the duty cycle may limit the maximum frequency use to a percentage in time. With this method, we set the ratio of transmission time for the selected channel, e.g., `1%` with 1 second transmission time means the radio has to pause for 99 seconds on this channel before retransmitting. The method returns true if successful.\n\n```c\nbool setChannelDCycle (uint8_t channel, float duty_cycle);\n```\n\n## Method: `setADR`\n\nWe can manually disable or enable the adaptive data rate (ADR) algorithm on the device with this method. It independently adapts the transmission data rate (and power) in runtime if active. If disabled, we must select power index and data rate manually, see `setDR` and `setPowerIndex`. The method returns true if successful.\n\n```c\nbool setADR(bool adr);\n```\n\n## Method: `setRX1Delay`\n\nWhen transmitting in LoRaWan, we usually operate on a TX window and two RX windows. This setting defines how long the modem has to wait before opening the channel for listening for RX window 1. RX window two is hardcoded to be one second after RX1. This parameter is configurable between 1 and 15 seconds in `ms`. By default, we have a delay of 1000 ms, and you should not change this if you do not change the network server accordingly. Longer window delays may be helpful with slow, unresponsive Internet connectivity. The method returns true if successful.\n\n```c\nbool setRX1Delay(uint16_t delay);\n```\n\n## Method: `checkValidModuleConnected`\n\nChecks if a valid module is connected to the configured serial port. Useful to check for connectivity with a supported module before performing any other actions.\n\n```c\nbool checkValidModuleConnected(bool autobaud_first);\n```\n\n- `bool autobaud_first`: Perform a call to `autoBaud()` before checking connection. Default is `false`.\n\nReturns:\n\n* `false` if no response was received (i.e. `needsHardReset` is `true`)\n* `false` if the module is invalid (unsupported), i.e. **not** one of the following:\n    * `RN2483`\n    * `RN2483A`\n    * `RN2903`\n    * `RN2903AS`\n* `true` if the module responded (i.e. `needsHardReset` is `false`) and is valid (supported).\n\nSee the [CheckModule](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/CheckModule/CheckModule.ino) example.\n\n# Additional for statistics \n\n## Method: `getRSSI`\n\nReturns the relative signal strength of the last received frame in `dBm`. Typical values are between -70dBm (very strong) and -136dBm (weak/sensitivity threshold). If the readout is unsuccessful, the method returns -255.\n\n```c\nint16_t getRSSI();\n```\n\n## Method: `getSNR`\n\nReturns the signal to noise ratio of the last received frame in `dB`. Note that LoRa also allows negative values for SNR. Typical values are between +20dB (very clear) and -20dB (weak/sensitivity threshold). If the readout is unsuccessful, the method returns -128.\n\n```c\nint8_t getSNR();\n```\n\n## Method: `getFrequency`\n\nReturns the channel frequency of the last received frame in `Hz`. If the readout is unsuccessful, the method returns 0.\n\n```c\nuint32_t getFrequency();\n```\n\n## Method: `getWatchDogTimer`\n\nReturns the LoRa modem's internal watch-dog timer in `ms`. If this time is exceeded, the modem resets. If instead, the readout is unsuccessful, the method returns 0.\n\n```c\nuint32_t getWatchDogTimer();\n```\n\n## Method: `getBW`\n\nReturns the used channel bandwidth of the last received frame in `kHz`. If the readout is unsuccessful, the method returns 0.\n\n```c\nuint8_t getBW();\n```\n\n## Method: `getCR`\n\nReturns the used code rate of the last received frame in `4/x`. If the readout is unsuccessful, the method returns 0.\n\n```c\nuint8_t getCR();\n```\n\n## Method: `getPower`\n\nReturns the power of the last incoming transmission in `dBm`. If the readout is unsuccessful, the method returns -128.\n\n```c\nint8_t getPower();\n```\n"
  },
  {
    "path": "examples/CayenneLPP/CayenneLPP.ino",
    "content": "#include <TheThingsNetwork.h>\n#include <CayenneLPP.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\nCayenneLPP lpp(51);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  lpp.reset();\n  lpp.addTemperature(1, 22.5);\n  lpp.addBarometricPressure(2, 1073.21);\n  lpp.addGPS(3, 52.37365, 4.88650, 2);\n\n  // Send it off\n  ttn.sendBytes(lpp.getBuffer(), lpp.getSize());\n\n  delay(10000);\n}\n"
  },
  {
    "path": "examples/CheckModule/CheckModule.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your DevAddr, NwkSKey, AppSKey and the frequency plan\nconst char *devAddr = \"00000000\";\nconst char *nwkSKey = \"00000000000000000000000000000000\";\nconst char *appSKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  // RN2XX3 reset pin connected to Arduino pin 12\n  pinMode(12, OUTPUT);\n  digitalWrite(12, HIGH);\n  // hard reset module and wait for startup\n  debugSerial.println(\"-- CHECK COMM\");\n  ttn.resetHard(12);\n  delay(100);\n  // check if a valid module responded\n  // (if no module is connected or wiring is bad, checkValidModuleConnected() will\n  //  take about ~30s to return (another ~30s if autobaud_first is true))\n  if(!ttn.checkValidModuleConnected(true))\n  {\n    if(ttn.needsHardReset)\n    {\n      debugSerial.println(\"Module unresponsive, please power cycle or hard reset board!\");\n    }\n    else\n    {\n      debugSerial.println(\"Module unsupported!\");       // module must be RN2483, RN2483A, RN2903, RN2903AS\n    }\n    while(true)                                         // stop code execution\n    {\n      ;\n    }\n  }\n\n  // do an ABP join\n  debugSerial.println(\"-- PERSONALIZE\");\n  // false is added as fourth argument to the personalize() call so that it\n  // does not perform a soft reset, because the module was already hard reset before via pin 12.\n  ttn.personalize(devAddr, nwkSKey, appSKey, false);\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Prepare payload of 1 byte to indicate LED status\n  byte payload[1];\n  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;\n\n  // Send it off\n  ttn.sendBytes(payload, sizeof(payload));\n\n  delay(10000);\n}\n"
  },
  {
    "path": "examples/DeviceInfo/DeviceInfo.ino",
    "content": "#include <TheThingsNetwork.h>\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n}\n\nvoid loop()\n{\n  debugSerial.println(\"Device Information\");\n  debugSerial.println();\n  ttn.showStatus();\n  debugSerial.println();\n  debugSerial.println(\"Use the EUI to register the device for OTAA\");\n  debugSerial.println(\"-------------------------------------------\");\n  debugSerial.println();\n\n  delay(10000);\n}\n"
  },
  {
    "path": "examples/PassThrough/PassThrough.ino",
    "content": "/**\n * Use this sketch to talk directly to the LoRa module.\n * \n * In Serial Monitor, select \"Both NL & CR\" and \"115200 baud\" in\n * the bottom right dropdowns and send command a command like:\n *\n * mac get deveui\n * sys reset\n */\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\nvoid setup()\n{\n  while (!debugSerial || !loraSerial)\n    ;\n\n  debugSerial.begin(115200);\n  delay(1000);\n\n  loraSerial.begin(57600);\n}\n\nvoid loop()\n{\n  while (debugSerial.available())\n  {\n    loraSerial.write(debugSerial.read());\n  }\n  while (loraSerial.available())\n  {\n    debugSerial.write(loraSerial.read());\n  }\n}\n"
  },
  {
    "path": "examples/QuickStart/Converter.js",
    "content": "function Converter(decoded, port) {\n  // Merge, split or otherwise\n  // mutate decoded fields.\n  var converted = decoded;\n    \n  if (port === 1 && (converted.led === 0 || converted.led === 1)) {\n    converted.led = Boolean(converted.led);\n  }\n    \n  return converted;\n}\n"
  },
  {
    "path": "examples/QuickStart/Decoder.js",
    "content": "function Decoder(bytes, port) {\n  // Decode an uplink message from a buffer\n  // (array) of bytes to an object of fields.\n  var decoded = {};\n    \n  if (port === 1) {\n    decoded.led = bytes[0];\n  }\n    \n  return decoded;\n}\n"
  },
  {
    "path": "examples/QuickStart/Encoder.js",
    "content": "function Encoder(object, port) {\n  // Encode downlink messages sent as\n  // object to an array or buffer of bytes.\n  var bytes = [];\n    \n  if (port === 1) {\n    bytes[0] = object.led ? 1 : 0;\n  }\n    \n  return bytes;\n}\n"
  },
  {
    "path": "examples/QuickStart/QuickStart.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  // Set callback for incoming messages\n  ttn.onMessage(message);\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Prepare payload of 1 byte to indicate LED status\n  byte payload[1];\n  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;\n\n  // Send it off\n  ttn.sendBytes(payload, sizeof(payload));\n\n  delay(10000);\n}\n\nvoid message(const byte *payload, size_t length, port_t port)\n{\n  debugSerial.println(\"-- MESSAGE\");\n\n  // Only handle messages of a single byte\n  if (length != 1)\n  {\n    return;\n  }\n\n  if (payload[0] == 0)\n  {\n    debugSerial.println(\"LED: off\");\n    digitalWrite(LED_BUILTIN, LOW);\n  }\n  else if (payload[0] == 1)\n  {\n    debugSerial.println(\"LED: on\");\n    digitalWrite(LED_BUILTIN, HIGH);\n  }\n}\n"
  },
  {
    "path": "examples/QuickStart/Validator.js",
    "content": "function Validator(converted, port) {\n  // Return false if the decoded, converted\n  // message is invalid and should be dropped.\n    \n  if (port === 1 && typeof converted.led !== 'boolean') {\n    return false;\n  }\n    \n  return true;\n}\n"
  },
  {
    "path": "examples/Receive/Receive.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  // Set callback for incoming messages\n  ttn.onMessage(message);\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Send single byte to poll for incoming messages\n  ttn.poll();\n\n  delay(10000);\n}\n\nvoid message(const uint8_t *payload, size_t size, port_t port)\n{\n  debugSerial.println(\"-- MESSAGE\");\n  debugSerial.print(\"Received \" + String(size) + \" bytes on port \" + String(port) + \":\");\n\n  for (int i = 0; i < size; i++)\n  {\n    debugSerial.print(\" \" + String(payload[i]));\n  }\n\n  debugSerial.println();\n}\n"
  },
  {
    "path": "examples/ReceiveClassC/ReceiveClassC.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  // Set callback for incoming messages\n  ttn.onMessage(message);\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey, -1, 10000, CLASS_C);\n\n  // Class C RX only takes affect after a TX\n  uint8_t payload[] = {0x00};\n  ttn.sendBytes(payload, 1);\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Check for received data.\n  ttn.poll();\n\n  // When using Class C we can poll as quickly as we can, as we only check the serial buffer.\n  //delay(1000);\n}\n\nvoid message(const uint8_t *payload, size_t size, port_t port)\n{\n  debugSerial.println(\"-- MESSAGE\");\n  debugSerial.print(\"Received \" + String(size) + \" bytes on port \" + String(port) + \":\");\n\n  for (int i = 0; i < size; i++)\n  {\n    debugSerial.print(\" \" + String(payload[i]));\n  }\n\n  debugSerial.println();\n}\n"
  },
  {
    "path": "examples/SendABP/SendABP.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your DevAddr, NwkSKey, AppSKey and the frequency plan\nconst char *devAddr = \"00000000\";\nconst char *nwkSKey = \"00000000000000000000000000000000\";\nconst char *appSKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  debugSerial.println(\"-- PERSONALIZE\");\n  ttn.personalize(devAddr, nwkSKey, appSKey);\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Prepare payload of 1 byte to indicate LED status\n  byte payload[1];\n  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;\n\n  // Send it off\n  ttn.sendBytes(payload, sizeof(payload));\n\n  delay(10000);\n}\n"
  },
  {
    "path": "examples/SendOTAA/SendOTAA.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Prepare payload of 1 byte to indicate LED status\n  byte payload[1];\n  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;\n\n  // Send it off\n  ttn.sendBytes(payload, sizeof(payload));\n\n  delay(10000);\n}\n"
  },
  {
    "path": "examples/Sensors/DHT/DHT.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// First install \"DHT sensor library\" via the Library Manager\n#include <DHT.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\n#define DHTPIN 2\n\n//Choose your DHT sensor moddel\n//#define DHTTYPE DHT11\n//#define DHTTYPE DHT21\n#define DHTTYPE DHT22\n\nDHT dht(DHTPIN, DHTTYPE);\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n\n  dht.begin();\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Read sensor values and multiply by 100 to effictively have 2 decimals\n  uint16_t humidity = dht.readHumidity(false) * 100;\n\n  // false: Celsius (default)\n  // true: Farenheit\n  uint16_t temperature = dht.readTemperature(false) * 100;\n\n  // Split both words (16 bits) into 2 bytes of 8\n  byte payload[4];\n  payload[0] = highByte(temperature);\n  payload[1] = lowByte(temperature);\n  payload[2] = highByte(humidity);\n  payload[3] = lowByte(humidity);\n\n  debugSerial.print(\"Temperature: \");\n  debugSerial.println(temperature);\n  debugSerial.print(\"Humidity: \");\n  debugSerial.println(humidity);\n\n  ttn.sendBytes(payload, sizeof(payload));\n\n  delay(20000);\n}\n"
  },
  {
    "path": "examples/Sensors/LightSensor/LightSensor.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n//define AnalogPin for sensor\n#define LightPin A0\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  pinMode(LightPin, INPUT);\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n\n  ttn.showStatus();\n  debugSerial.println(\"Setup for The Things Network complete\");\n}\n\nvoid loop()\n{\n\n  uint16_t light = analogRead(LightPin);\n\n  // Split word (16 bits) into 2 bytes of 8\n  byte payload[2];\n  payload[0] = highByte(light);\n  payload[1] = lowByte(light);\n\n  debugSerial.print(\"Transmitting Light level: \");\n  debugSerial.println(light);\n\n  ttn.sendBytes(payload, sizeof(payload));\n\n  delay(20000);\n}\n"
  },
  {
    "path": "examples/TheThingsMessage/Receive/Receive.ino",
    "content": "#include <TheThingsNetwork.h>\n#include <TheThingsMessage.h>\n\n// Set your AppEUI and  AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\ndevicedata_t data = api_DeviceData_init_default;\n\nvoid setup()\n{\n  pinMode(LED_BUILTIN, INPUT);\n\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n\n  ttn.onMessage(message);\n\n  data.has_motion = true;\n  data.has_water = true;\n}\n\nvoid loop()\n{\n  // Read sensors\n  data.motion = digitalRead(LED_BUILTIN) == HIGH;\n  data.water = 682;\n\n  // Encode data\n  byte *buffer;\n  size_t size;\n\n  // Send standard message on port 100\n  TheThingsMessage::encodeDeviceData(&data, &buffer, &size);\n  ttn.sendBytes(buffer, size, 100);\n\n  delay(10000);\n}\n\nvoid message(const uint8_t *payload, size_t length, port_t port)\n{\n  //standard message always received on port 100 or more\n  if (port >= 100)\n  {\n    appdata_t appData = api_AppData_init_default;\n    TheThingsMessage::decodeAppData(&appData, payload, length);\n  }\n}\n"
  },
  {
    "path": "examples/TheThingsMessage/Send/Send.ino",
    "content": "#include <TheThingsNetwork.h>\n#include <TheThingsMessage.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915\n#define freqPlan REPLACE_ME\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\ndevicedata_t data = api_DeviceData_init_default;\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  debugSerial.println(\"-- STATUS\");\n  ttn.showStatus();\n\n  debugSerial.println(\"-- JOIN\");\n  ttn.join(appEui, appKey);\n\n  // Select what fields to include in the encoded message\n  data.has_motion = true;\n  data.has_water = false;\n  data.has_temperature_celcius = true;\n  data.has_temperature_fahrenheit = true;\n  data.has_humidity = true;\n}\n\nvoid loop()\n{\n  debugSerial.println(\"-- LOOP\");\n\n  // Read the sensors\n  data.motion = true;\n  data.water = 682;\n  data.temperature_celcius = 30;\n  data.temperature_fahrenheit = 86;\n  data.humidity = 97;\n\n  // Encode the selected fields of the struct as bytes\n  byte *buffer;\n  size_t size;\n  TheThingsMessage::encodeDeviceData(&data, &buffer, &size);\n\n  ttn.sendBytes(buffer, size);\n\n  delay(10000);\n}\n"
  },
  {
    "path": "examples/Workshop/Workshop.ino",
    "content": "#include <TheThingsNetwork.h>\n\n// Before your start, make sure that in the Tools menu, your Board and your\n// Port is set to Arduino Leonardo\n\n// After you registered your ABP device, go to The Things Network Dashboard\n// and copy the Device Addr, Network Session Key and App Session Key\n\n// Set your Device Address, for example: \"1C55B133\";\nconst char *devAddr = \"00000000\";\n\n// Set your Network Session Key, for example: \"0C11F84C5E4315CCDE50AB31C430BBE5\";\n// This is used by the network to identify your device\nconst char *nwkSKey = \"00000000000000000000000000000000\";\n\n// Set your Application Session Key, for example: \"6C250A6B559B1BA0A51696ED20E3CF56\";\n// This is used by the network for encryption\nconst char *appSKey = \"00000000000000000000000000000000\";\n\n//Set your frequency plan by replacing REPLACE_ME by TTN_FP_EU868 for Europe or TTN_FP_US915 for the United States\n#define freqPlan REPLACE_ME\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\nTheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);\n\nvoid setup()\n{\n  // Set up the serial interfaces for the debugging serial monitor and LoRa module\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  // Wait a maximum of 10s for Serial Monitor\n  while (!debugSerial && millis() < 10000)\n    ;\n\n  // Here we activate the device with your address and keys\n  ttn.personalize(devAddr, nwkSKey, appSKey);\n\n  // Show the status on the debugging serial monitor\n  ttn.showStatus();\n}\n\nvoid loop()\n{\n  // Create a buffer with three bytes\n  byte payload[3] = {0x01, 0x02, 0x03};\n\n  // Send it to the network\n  ttn.sendBytes(payload, sizeof(payload));\n\n  // Wait 10 seconds\n  delay(10000);\n}\n"
  },
  {
    "path": "keywords.txt",
    "content": "#######################################\n# Syntax Coloring Map\n#######################################\n\n#######################################\n# Class (KEYWORD1)\n#######################################\n\nTheThingsNetwork\tKEYWORD1\nTheThingsMessage\tKEYWORD1\nTheThingsNode\tKEYWORD1\n\nttn_port_t\tKEYWORD1\nttn_response_t\tKEYWORD1\nttn_fp_t\tKEYWORD1\nlorawan_class_t\tKEYWORD1\n\n#######################################\n# Methods and Functions (KEYWORD2)\n#######################################\n\nshowStatus\tKEYWORD2\nonMessage\tKEYWORD2\nprovision\tKEYWORD2\njoin\tKEYWORD2\npersonalize\tKEYWORD2\nsetClass\tKEYWORD2\nsendBytes\tKEYWORD2\npoll\tKEYWORD2\n\nencodeSensorData\tKEYWORD2\ndecodeAppData\tKEYWORD2\n\ngetLight\tKEYWORD2\nconfigLight\tKEYWORD2\ngetTemperatureAsInt\tKEYWORD2\ngetTemperatureAsFloat\tKEYWORD2\nconfigTemperature\tKEYWORD2\nonTemperatureAlert\tKEYWORD2\nconfigTemperatureAlert\tKEYWORD2\nonMotionStart\tKEYWORD2\nonMotionStop\tKEYWORD2\nisMoving\tKEYWORD2\nconfigMotion\tKEYWORD2\nonButtonPress\tKEYWORD2\nonButtonRelease\tKEYWORD2\nisButtonPressed\tKEYWORD2\ngetRed\tKEYWORD2\ngetGreen\tKEYWORD2\ngetBlue\tKEYWORD2\ngetColor\tKEYWORD2\ncolorToString\tKEYWORD2\nsetRGB\tKEYWORD2\nsetRed\tKEYWORD2\nsetGreen\tKEYWORD2\nsetBlue\tKEYWORD2\nsetColor\tKEYWORD2\ngetUSB\tKEYWORD2\ngetBattery\tKEYWORD2\ngetVDD\tKEYWORD2\n\nencodeDeviceData\tKEYWORD2\ndecodeAppData\tKEYWORD2\n\n#######################################\n# Constants (LITERAL1)\n#######################################\n\nTTN_DEFAULT_SF\tLITERAL1\nTTN_DEFAULT_FSB\tLITERAL1\nTTN_RETX\tLITERAL1\nTTN_PWRIDX_868\tLITERAL1\nTTN_PWRIDX_915\tLITERAL1\nTTN_BUFFER_SIZE\tLITERAL1\nTTN_ERROR_SEND_COMMAND_FAILED\tLITERAL1\nTTN_ERROR_UNEXPECTED_RESPONSE\tLITERAL1\nTTN_SUCCESSFUL_TRANSMISSION\tLITERAL1\nTTN_SUCCESSFUL_RECEIVE\tLITERAL1\nTTN_FP_EU868\tLITERAL1\nTTN_FP_US915\tLITERAL1\nTTN_FP_AS920_923\tLITERAL1\nTTN_FP_AS923_925\tLITERAL1\nTTN_FP_KR920_923\tLITERAL1\n\nTTN_PIN_LED\tLITERAL1\n\nTTN_COLOR\tLITERAL1\nTTN_RED\tLITERAL1\nTTN_GREEN\tLITERAL1\nTTN_BLUE\tLITERAL1\nTTN_YELLOW\tLITERAL1\nTTN_CYAN\tLITERAL1\nTTN_MAGENTA\tLITERAL1\nTTN_WHITE\tLITERAL1\nTTN_BLACK\tLITERAL1\n\nCLASS_A\tLITERAL1\nCLASS_B\tLITERAL1\nCLASS_C\tLITERAL1\n"
  },
  {
    "path": "library.properties",
    "content": "name=TheThingsNetwork\nversion=2.7.2\nauthor=The Things Network\nmaintainer=Johan Stokking <johan@thethingsnetwork.org>\nsentence=The Things Network Arduino Library.\nparagraph=Compatible with any Microchip RN2483 and RN2903 device.\ncategory=Communication\nurl=https://github.com/TheThingsNetwork/arduino-device-lib\narchitectures=*\nincludes=TheThingsNetwork.h\n"
  },
  {
    "path": "src/CayenneLPP.cpp",
    "content": "// Adapted from https://developer.mbed.org/teams/myDevicesIoT/code/Cayenne-LPP/\n\n// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"CayenneLPP.h\"\n\nCayenneLPP::CayenneLPP(uint8_t size) : maxsize(size)\n{\n  buffer = (uint8_t *)malloc(size);\n  cursor = 0;\n}\n\nCayenneLPP::~CayenneLPP(void)\n{\n  free(buffer);\n}\n\nvoid CayenneLPP::reset(void)\n{\n  cursor = 0;\n}\n\nuint8_t CayenneLPP::getSize(void)\n{\n  return cursor;\n}\n\nuint8_t *CayenneLPP::getBuffer(void)\n{\n  //    uint8_t[cursor] result;\n  //    memcpy(result, buffer, cursor);\n  //    return result;\n  return buffer;\n}\n\nuint8_t CayenneLPP::copy(uint8_t *dst)\n{\n  memcpy(dst, buffer, cursor);\n  return cursor;\n}\n\nuint8_t CayenneLPP::addDigitalInput(uint8_t channel, uint8_t value)\n{\n  if ((cursor + LPP_DIGITAL_INPUT_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_DIGITAL_INPUT;\n  buffer[cursor++] = value;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addDigitalOutput(uint8_t channel, uint8_t value)\n{\n  if ((cursor + LPP_DIGITAL_OUTPUT_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_DIGITAL_OUTPUT;\n  buffer[cursor++] = value;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addAnalogInput(uint8_t channel, float value)\n{\n  if ((cursor + LPP_ANALOG_INPUT_SIZE) > maxsize)\n  {\n    return 0;\n  }\n\n  int16_t val = value * 100;\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_ANALOG_INPUT;\n  buffer[cursor++] = val >> 8;\n  buffer[cursor++] = val;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addAnalogOutput(uint8_t channel, float value)\n{\n  if ((cursor + LPP_ANALOG_OUTPUT_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  int16_t val = value * 100;\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_ANALOG_OUTPUT;\n  buffer[cursor++] = val >> 8;\n  buffer[cursor++] = val;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addLuminosity(uint8_t channel, uint16_t lux)\n{\n  if ((cursor + LPP_LUMINOSITY_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_LUMINOSITY;\n  buffer[cursor++] = lux >> 8;\n  buffer[cursor++] = lux;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addPresence(uint8_t channel, uint8_t value)\n{\n  if ((cursor + LPP_PRESENCE_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_PRESENCE;\n  buffer[cursor++] = value;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addTemperature(uint8_t channel, float celsius)\n{\n  if ((cursor + LPP_TEMPERATURE_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  int16_t val = celsius * 10;\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_TEMPERATURE;\n  buffer[cursor++] = val >> 8;\n  buffer[cursor++] = val;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addRelativeHumidity(uint8_t channel, float rh)\n{\n  if ((cursor + LPP_RELATIVE_HUMIDITY_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_RELATIVE_HUMIDITY;\n  buffer[cursor++] = rh * 2;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addAccelerometer(uint8_t channel, float x, float y, float z)\n{\n  if ((cursor + LPP_ACCELEROMETER_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  int16_t vx = x * 1000;\n  int16_t vy = y * 1000;\n  int16_t vz = z * 1000;\n\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_ACCELEROMETER;\n  buffer[cursor++] = vx >> 8;\n  buffer[cursor++] = vx;\n  buffer[cursor++] = vy >> 8;\n  buffer[cursor++] = vy;\n  buffer[cursor++] = vz >> 8;\n  buffer[cursor++] = vz;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addBarometricPressure(uint8_t channel, float hpa)\n{\n  if ((cursor + LPP_BAROMETRIC_PRESSURE_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  int16_t val = hpa * 10;\n\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_BAROMETRIC_PRESSURE;\n  buffer[cursor++] = val >> 8;\n  buffer[cursor++] = val;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addGyrometer(uint8_t channel, float x, float y, float z)\n{\n  if ((cursor + LPP_GYROMETER_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  int16_t vx = x * 100;\n  int16_t vy = y * 100;\n  int16_t vz = z * 100;\n\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_GYROMETER;\n  buffer[cursor++] = vx >> 8;\n  buffer[cursor++] = vx;\n  buffer[cursor++] = vy >> 8;\n  buffer[cursor++] = vy;\n  buffer[cursor++] = vz >> 8;\n  buffer[cursor++] = vz;\n\n  return cursor;\n}\n\nuint8_t CayenneLPP::addGPS(uint8_t channel, float latitude, float longitude, float meters)\n{\n  if ((cursor + LPP_GPS_SIZE) > maxsize)\n  {\n    return 0;\n  }\n  int32_t lat = latitude * 10000;\n  int32_t lon = longitude * 10000;\n  int32_t alt = meters * 100;\n\n  buffer[cursor++] = channel;\n  buffer[cursor++] = LPP_GPS;\n\n  buffer[cursor++] = lat >> 16;\n  buffer[cursor++] = lat >> 8;\n  buffer[cursor++] = lat;\n  buffer[cursor++] = lon >> 16;\n  buffer[cursor++] = lon >> 8;\n  buffer[cursor++] = lon;\n  buffer[cursor++] = alt >> 16;\n  buffer[cursor++] = alt >> 8;\n  buffer[cursor++] = alt;\n\n  return cursor;\n}\n"
  },
  {
    "path": "src/CayenneLPP.h",
    "content": "// Adapted from https://developer.mbed.org/teams/myDevicesIoT/code/Cayenne-LPP/\n\n// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef _CAYENNE_LPP_H_\n#define _CAYENNE_LPP_H_\n\n#include <Arduino.h>\n\n//LPP_BATTERY = // TODO Unsupported in IPSO Smart Object\n//LPP_PROXIMITY = // TODO Unsupported in IPSO Smart Object\n\n#define LPP_DIGITAL_INPUT 0         // 1 byte\n#define LPP_DIGITAL_OUTPUT 1        // 1 byte\n#define LPP_ANALOG_INPUT 2          // 2 bytes, 0.01 signed\n#define LPP_ANALOG_OUTPUT 3         // 2 bytes, 0.01 signed\n#define LPP_LUMINOSITY 101          // 2 bytes, 1 lux unsigned\n#define LPP_PRESENCE 102            // 1 byte, 1\n#define LPP_TEMPERATURE 103         // 2 bytes, 0.1°C signed\n#define LPP_RELATIVE_HUMIDITY 104   // 1 byte, 0.5% unsigned\n#define LPP_ACCELEROMETER 113       // 2 bytes per axis, 0.001G\n#define LPP_BAROMETRIC_PRESSURE 115 // 2 bytes 0.1 hPa Unsigned\n#define LPP_GYROMETER 134           // 2 bytes per axis, 0.01 °/s\n#define LPP_GPS 136                 // 3 byte lon/lat 0.0001 °, 3 bytes alt 0.01 meter\n\n// Data ID + Data Type + Data Size\n#define LPP_DIGITAL_INPUT_SIZE 3       // 1 byte\n#define LPP_DIGITAL_OUTPUT_SIZE 3      // 1 byte\n#define LPP_ANALOG_INPUT_SIZE 4        // 2 bytes, 0.01 signed\n#define LPP_ANALOG_OUTPUT_SIZE 4       // 2 bytes, 0.01 signed\n#define LPP_LUMINOSITY_SIZE 4          // 2 bytes, 1 lux unsigned\n#define LPP_PRESENCE_SIZE 3            // 1 byte, 1\n#define LPP_TEMPERATURE_SIZE 4         // 2 bytes, 0.1°C signed\n#define LPP_RELATIVE_HUMIDITY_SIZE 3   // 1 byte, 0.5% unsigned\n#define LPP_ACCELEROMETER_SIZE 8       // 2 bytes per axis, 0.001G\n#define LPP_BAROMETRIC_PRESSURE_SIZE 4 // 2 bytes 0.1 hPa Unsigned\n#define LPP_GYROMETER_SIZE 8           // 2 bytes per axis, 0.01 °/s\n#define LPP_GPS_SIZE 11                // 3 byte lon/lat 0.0001 °, 3 bytes alt 0.01 meter\n\nclass CayenneLPP\n{\npublic:\n  CayenneLPP(uint8_t size);\n  ~CayenneLPP();\n\n  void reset(void);\n  uint8_t getSize(void);\n  uint8_t *getBuffer(void);\n  uint8_t copy(uint8_t *buffer);\n\n  uint8_t addDigitalInput(uint8_t channel, uint8_t value);\n  uint8_t addDigitalOutput(uint8_t channel, uint8_t value);\n\n  uint8_t addAnalogInput(uint8_t channel, float value);\n  uint8_t addAnalogOutput(uint8_t channel, float value);\n\n  uint8_t addLuminosity(uint8_t channel, uint16_t lux);\n  uint8_t addPresence(uint8_t channel, uint8_t value);\n  uint8_t addTemperature(uint8_t channel, float celsius);\n  uint8_t addRelativeHumidity(uint8_t channel, float rh);\n  uint8_t addAccelerometer(uint8_t channel, float x, float y, float z);\n  uint8_t addBarometricPressure(uint8_t channel, float hpa);\n  uint8_t addGyrometer(uint8_t channel, float x, float y, float z);\n  uint8_t addGPS(uint8_t channel, float latitude, float longitude, float meters);\n\nprivate:\n  uint8_t *buffer;\n  uint8_t maxsize;\n  uint8_t cursor;\n};\n\n#endif\n"
  },
  {
    "path": "src/TheThingsMessage.cpp",
    "content": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"TheThingsMessage.h\"\n\nbool TheThingsMessage::decodeAppData(appdata_t *receiveData, const byte *payload, size_t length)\n{\n  pb_istream_t stream = pb_istream_from_buffer(payload, length);\n  if (!pb_decode(&stream, api_AppData_fields, receiveData))\n  {\n    return false;\n  }\n#ifdef LED_BUILTIN\n  receiveData->light ? digitalWrite(LED_BUILTIN, HIGH) : digitalWrite(LED_BUILTIN, LOW);\n#endif\n  return true;\n}\n\nvoid TheThingsMessage::encodeDeviceData(devicedata_t *data, byte **buffer, size_t *size)\n{\n  byte message[TTN_BUFFER_SIZE];\n\n  pb_ostream_t sendStream = pb_ostream_from_buffer(message, sizeof(message));\n  pb_encode(&sendStream, api_DeviceData_fields, data);\n  *buffer = message;\n  *size = sendStream.bytes_written;\n}\n"
  },
  {
    "path": "src/TheThingsMessage.h",
    "content": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef _THETHINGSMESSAGE_H_\n#define _THETHINGSMESSAGE_H_\n\n#include \"TheThingsNetwork.h\"\n#include \"pb.h\"\n#include \"pb_encode.h\"\n#include \"pb_decode.h\"\n#include \"deviceData.pb.h\"\n#include \"appData.pb.h\"\n\ntypedef api_DeviceData devicedata_t;\ntypedef api_AppData appdata_t;\n\nclass TheThingsMessage\n{\npublic:\n  static void encodeDeviceData(devicedata_t *data, uint8_t **buffer, size_t *size);\n  static bool decodeAppData(appdata_t *receiveData, const uint8_t *payload, size_t size);\n};\n\n#endif\n"
  },
  {
    "path": "src/TheThingsNetwork.cpp",
    "content": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#include \"TheThingsNetwork.h\"\n\n#define debugPrintLn(...)                \\\n  {                                      \\\n    if (debugStream)                     \\\n      debugStream->println(__VA_ARGS__); \\\n  }\n#define debugPrint(...)                \\\n  {                                    \\\n    if (debugStream)                   \\\n      debugStream->print(__VA_ARGS__); \\\n  }\n\n#define TTN_HEX_CHAR_TO_NIBBLE(c) ((c >= 'A') ? (c - 'A' + 0x0A) : (c - '0'))\n#define TTN_HEX_PAIR_TO_BYTE(h, l) ((TTN_HEX_CHAR_TO_NIBBLE(h) << 4) + TTN_HEX_CHAR_TO_NIBBLE(l))\n\nconst char ok[] PROGMEM = \"ok\";\nconst char on[] PROGMEM = \"on\";\nconst char off[] PROGMEM = \"off\";\nconst char accepted[] PROGMEM = \"accepted\";\nconst char mac_tx_ok[] PROGMEM = \"mac_tx_ok\";\nconst char mac_rx[] PROGMEM = \"mac_rx\";\nconst char mac_err[] PROGMEM = \"mac_err\";\nconst char rn2483[] PROGMEM = \"RN2483\";\nconst char rn2483a[] PROGMEM = \"RN2483A\";\nconst char rn2903[] PROGMEM = \"RN2903\";\nconst char rn2903as[] PROGMEM = \"RN2903AS\";\n\nconst char *const compare_table[] PROGMEM = {ok, on, off, accepted, mac_tx_ok, mac_rx, mac_err, rn2483, rn2483a, rn2903, rn2903as};\n\n#define CMP_OK 0\n#define CMP_ON 1\n#define CMP_OFF 2\n#define CMP_ACCEPTED 3\n#define CMP_MAC_TX_OK 4\n#define CMP_MAC_RX 5\n#define CMP_MAC_ERR 6\n#define CMP_RN2483 7\n#define CMP_RN2483A 8\n#define CMP_RN2903 9\n#define CMP_RN2903AS 10\n\n// CMP OK\nconst char busy[] PROGMEM = \"busy\";\nconst char fram_counter_err_rejoin_needed[] PROGMEM = \"fram_counter_err_rejoin_needed\";\nconst char invalid_class[] PROGMEM = \"invalid_class\";\nconst char invalid_data_len[] PROGMEM = \"invalid_data_len\";\nconst char invalid_param[] PROGMEM = \"invalid_param\";\nconst char keys_not_init[] PROGMEM = \"keys_not_init\";\nconst char mac_paused[] PROGMEM = \"mac_paused\";\nconst char multicast_keys_not_set[] PROGMEM = \"multicast_keys_not_set\";\nconst char no_free_ch[] PROGMEM = \"no_free_ch\";\nconst char not_joined[] PROGMEM = \"not_joined\";\nconst char silent[] PROGMEM = \"silent\";\nconst char err[] PROGMEM = \"err\";\n\nconst char *const compareerr_table[] PROGMEM = {ok, busy, fram_counter_err_rejoin_needed, invalid_class, invalid_data_len, invalid_param, keys_not_init, mac_paused, multicast_keys_not_set, no_free_ch, not_joined, silent, err};\n\n#define CMP_ERR_OK 0\n#define CMP_ERR_BUSY 1\n#define CMP_ERR_FRMCNT 2\n#define CMP_ERR_INVCLS 3\n#define CMP_ERR_INVDLEN 4\n#define CMP_ERR_INVPAR 5\n#define CMP_ERR_NKEYINT 6\n#define CMP_ERR_MACPAUSE 7\n#define CMP_ERR_NKYMLTCST 8\n#define CMP_ERR_NFRCHN 9\n#define CMP_ERR_NJOIN 10\n#define CMP_ERR_SILENT 11\n#define CMP_ERR_ERR 12\n\n#define CMP_ERR_LAST CMP_ERR_ERR\n\n#define SENDING \"Sending: \"\n#define SEND_MSG \"\\r\\n\"\n\nconst char eui[] PROGMEM = \"EUI: \";\nconst char battery[] PROGMEM = \"Battery: \";\nconst char appEui[] PROGMEM = \"AppEUI: \";\nconst char devEui[] PROGMEM = \"DevEUI: \";\nconst char band[] PROGMEM = \"Band: \";\nconst char data_rate[] PROGMEM = \"Data Rate: \";\nconst char rx_delay_1[] PROGMEM = \"RX Delay 1: \";\nconst char rx_delay_2[] PROGMEM = \"RX Delay 2: \";\nconst char version[] PROGMEM = \"Version: \";\nconst char model[] PROGMEM = \"Model: \";\nconst char devaddr[] PROGMEM = \"DevAddr: \";\n\nconst char *const show_table[] PROGMEM = {eui, battery, appEui, devEui, band, data_rate, rx_delay_1, rx_delay_2, version, model, devaddr};\n\n#define SHOW_EUI 0\n#define SHOW_BATTERY 1\n#define SHOW_APPEUI 2\n#define SHOW_DEVEUI 3\n#define SHOW_BAND 4\n#define SHOW_DATA_RATE 5\n#define SHOW_RX_DELAY_1 6\n#define SHOW_RX_DELAY_2 7\n#define SHOW_VERSION 8\n#define SHOW_MODEL 9\n#define SHOW_DEVADDR 10\n\nconst char invalid_sf[] PROGMEM = \"Invalid SF\";\nconst char invalid_fp[] PROGMEM = \"Invalid frequency plan\";\nconst char unexpected_response[] PROGMEM = \"Unexpected response: \";\nconst char send_command_failed[] PROGMEM = \"Send command failed\";\nconst char join_failed[] PROGMEM = \"Send join command failed\";\nconst char join_not_accepted[] PROGMEM = \"Join not accepted: \";\nconst char personalize_not_accepted[] PROGMEM = \"Personalize not accepted\";\nconst char response_is_not_ok[] PROGMEM = \"Response is not OK: \";\nconst char error_key_length[] PROGMEM = \"One or more keys are of invalid length.\";\nconst char check_configuration[] PROGMEM = \"Check your coverage, keys and backend status.\";\nconst char no_response[] PROGMEM =  \"No response from RN module.\";\nconst char invalid_module[] PROGMEM = \"Invalid module (must be RN2xx3[xx]).\";\n\nconst char *const error_msg[] PROGMEM = {invalid_sf, invalid_fp, unexpected_response, send_command_failed, join_failed, join_not_accepted, personalize_not_accepted, response_is_not_ok, error_key_length, check_configuration, no_response, invalid_module};\n\n#define ERR_INVALID_SF 0\n#define ERR_INVALID_FP 1\n#define ERR_UNEXPECTED_RESPONSE 2\n#define ERR_SEND_COMMAND_FAILED 3\n#define ERR_JOIN_FAILED 4\n#define ERR_JOIN_NOT_ACCEPTED 5\n#define ERR_PERSONALIZE_NOT_ACCEPTED 6\n#define ERR_RESPONSE_IS_NOT_OK 7\n#define ERR_KEY_LENGTH 8\n#define ERR_CHECK_CONFIGURATION 9\n#define ERR_NO_RESPONSE 10\n#define ERR_INVALID_MODULE 11\n\nconst char personalize_accepted[] PROGMEM = \"Personalize accepted. Status: \";\nconst char join_accepted[] PROGMEM = \"Join accepted. Status: \";\nconst char successful_transmission[] PROGMEM = \"Successful transmission\";\nconst char successful_transmission_received[] PROGMEM = \"Successful transmission. Received \";\nconst char valid_module[] PROGMEM = \"Valid module connected.\";\n\nconst char *const success_msg[] PROGMEM = {personalize_accepted, join_accepted, successful_transmission, successful_transmission_received, valid_module};\n\n#define SCS_PERSONALIZE_ACCEPTED 0\n#define SCS_JOIN_ACCEPTED 1\n#define SCS_SUCCESSFUL_TRANSMISSION 2\n#define SCS_SUCCESSFUL_TRANSMISSION_RECEIVED 3\n#define SCS_VALID_MODULE 4\n\nconst char radio_prefix[] PROGMEM = \"radio\";\nconst char radio_set[] PROGMEM = \"set\";\nconst char radio_get[] PROGMEM = \"get\";\nconst char radio_get_bw[] PROGMEM = \"bw\";\nconst char radio_get_prlen[] PROGMEM = \"prlen\";\nconst char radio_get_crc[] PROGMEM = \"crc\";\nconst char radio_get_cr[] PROGMEM = \"cr\";\nconst char radio_get_sf[] PROGMEM = \"sf\";\nconst char radio_get_freq[] PROGMEM = \"freq\";\nconst char radio_get_rxbw[] PROGMEM = \"rxbw\";\nconst char radio_get_wdt[] PROGMEM = \"wdt\";\nconst char radio_get_pwr[] PROGMEM = \"pwr\";\nconst char radio_get_rssi[] PROGMEM = \"rssi\";\nconst char radio_get_snr[] PROGMEM = \"snr\";\n\nconst char *const radio_table[] PROGMEM = {radio_prefix, radio_set, radio_get, radio_get_bw, radio_get_prlen, radio_get_crc, radio_get_cr, radio_get_sf, radio_get_freq, radio_get_rxbw, radio_get_wdt, radio_get_pwr, radio_get_rssi, radio_get_snr};\n\n#define RADIO_PREFIX 0\n#define RADIO_SET 1\n#define RADIO_GET 2\n#define RADIO_GET_BW 3\n#define RADIO_GET_PRLEN 4\n#define RADIO_GET_CRC 5\n#define RADIO_GET_CR 6\n#define RADIO_GET_SF 7\n#define RADIO_GET_FREQ 8\n#define RADIO_GET_RXBW 9\n#define RADIO_GET_WDT 10\n#define RADIO_GET_PWR 11\n#define RADIO_GET_RSSI 12\n#define RADIO_GET_SNR 13\n\nconst char sys_prefix[] PROGMEM = \"sys\";\nconst char sys_sleep[] PROGMEM = \"sleep\";\nconst char sys_reset[] PROGMEM = \"reset\";\nconst char sys_erase_fw[] PROGMEM = \"eraseFW\";\nconst char sys_factory_rst[] PROGMEM = \"factoryRESET\";\nconst char sys_set[] PROGMEM = \"set\";\nconst char sys_get[] PROGMEM = \"get\";\nconst char sys_get_ver[] PROGMEM = \"ver\";\nconst char sys_get_vdd[] PROGMEM = \"vdd\";\nconst char sys_get_hweui[] PROGMEM = \"hweui\";\nconst char sys_set_get_nvm[] PROGMEM = \"nvm\";\nconst char sys_set_pindig[] PROGMEM = \"pindig\";\n\nconst char *const sys_table[] PROGMEM = {sys_prefix, sys_sleep, sys_reset, sys_erase_fw, sys_factory_rst, sys_set, sys_get, sys_get_ver, sys_get_vdd, sys_get_hweui, sys_set_get_nvm, sys_set_pindig};\n\n#define SYS_PREFIX 0\n#define SYS_SLEEP 1\n#define SYS_RESET 2\n#define SYS_ERASE_FW 3\n#define SYS_FACTORY_RST 4\n#define SYS_SET 5\n#define SYS_GET 6\n#define SYS_GET_VER 7\n#define SYS_GET_VDD 8\n#define SYS_GET_HWEUI 9\n#define SYS_SET_GET_NVM 10\n#define SYS_SET_PINDIG 11\n\nconst char mac_prefix[] PROGMEM = \"mac\";\nconst char mac_reset[] PROGMEM = \"reset\";\nconst char mac_tx[] PROGMEM = \"tx\";\nconst char mac_join[] PROGMEM = \"join\";\nconst char mac_save[] PROGMEM = \"save\";\nconst char mac_force_enable[] PROGMEM = \"forceENABLE\";\nconst char mac_pause[] PROGMEM = \"pause\";\nconst char mac_resume[] PROGMEM = \"resume\";\nconst char mac_set[] PROGMEM = \"set\";\nconst char mac_get[] PROGMEM = \"get\";\n\nconst char *const mac_table[] PROGMEM = {mac_prefix, mac_reset, mac_tx, mac_join, mac_save, mac_force_enable, mac_pause, mac_resume, mac_set, mac_get};\n\n#define MAC_PREFIX 0\n#define MAC_RESET 1\n#define MAC_TX 2\n#define MAC_JOIN 3\n#define MAC_SAVE 4\n#define MAC_FORCE_ENABLE 5\n#define MAC_PAUSE 6\n#define MAC_RESUME 7\n#define MAC_SET 8\n#define MAC_GET 9\n\nconst char mac_devaddr[] PROGMEM = \"devaddr\";\nconst char mac_deveui[] PROGMEM = \"deveui\";\nconst char mac_appeui[] PROGMEM = \"appeui\";\nconst char mac_nwkskey[] PROGMEM = \"nwkskey\";\nconst char mac_appskey[] PROGMEM = \"appskey\";\nconst char mac_appkey[] PROGMEM = \"appkey\";\nconst char mac_pwridx[] PROGMEM = \"pwridx\";\nconst char mac_dr[] PROGMEM = \"dr\";\nconst char mac_adr[] PROGMEM = \"adr\";\nconst char mac_bat[] PROGMEM = \"bat\";\nconst char mac_retx[] PROGMEM = \"retx\";\nconst char mac_linkchk[] PROGMEM = \"linkchk\";\nconst char mac_rxdelay1[] PROGMEM = \"rxdelay1\";\nconst char mac_rxdelay2[] PROGMEM = \"rxdelay2\";\nconst char mac_band[] PROGMEM = \"band\";\nconst char mac_ar[] PROGMEM = \"ar\";\nconst char mac_rx2[] PROGMEM = \"rx2\";\nconst char mac_ch[] PROGMEM = \"ch\";\nconst char mac_gwnb[] PROGMEM = \"gwnb\";\nconst char mac_mrgn[] PROGMEM = \"mrgn\";\nconst char mac_class[] PROGMEM = \"class\";\nconst char mac_status[] PROGMEM = \"status\";\nconst char mac_upctr[] PROGMEM = \"upctr\";\nconst char mac_dnctr[] PROGMEM = \"dnctr\";\n\nconst char *const mac_options[] PROGMEM = {mac_devaddr, mac_deveui, mac_appeui, mac_nwkskey, mac_appskey, mac_appkey, mac_pwridx, mac_dr, mac_adr, mac_bat, mac_retx, mac_linkchk, mac_rxdelay1, mac_rxdelay2, mac_band,\n\t\t\tmac_ar, mac_rx2, mac_ch, mac_gwnb, mac_mrgn, mac_class, mac_status, mac_upctr, mac_dnctr};\n\n#define MAC_DEVADDR 0\n#define MAC_DEVEUI 1\n#define MAC_APPEUI 2\n#define MAC_NWKSKEY 3\n#define MAC_APPSKEY 4\n#define MAC_APPKEY 5\n#define MAC_PWRIDX 6\n#define MAC_DR 7\n#define MAC_ADR 8\n#define MAC_BAT 9\n#define MAC_RETX 10\n#define MAC_LINKCHK 11\n#define MAC_RXDELAY1 12\n#define MAC_RXDELAY2 13\n#define MAC_BAND 14\n#define MAC_AR 15\n#define MAC_RX2 16\n#define MAC_CH 17\n#define MAC_GWNB 18\n#define MAC_MRGN 19\n#define MAC_CLASS 20\n#define MAC_STATUS 21\n#define MAC_UPCTR 22\n#define MAC_DNCTR 23\n\nconst char mac_join_mode_otaa[] PROGMEM = \"otaa\";\nconst char mac_join_mode_abp[] PROGMEM = \"abp\";\n\nconst char *const mac_join_mode[] PROGMEM = {mac_join_mode_otaa, mac_join_mode_abp};\n\n#define MAC_JOIN_MODE_OTAA 0\n#define MAC_JOIN_MODE_ABP 1\n\nconst char channel_dcycle[] PROGMEM = \"dcycle\";\nconst char channel_drrange[] PROGMEM = \"drrange\";\nconst char channel_freq[] PROGMEM = \"freq\";\nconst char channel_status[] PROGMEM = \"status\";\n\nconst char *const mac_ch_options[] PROGMEM = {channel_dcycle, channel_drrange, channel_freq, channel_status};\n\n#define MAC_CHANNEL_DCYCLE 0\n#define MAC_CHANNEL_DRRANGE 1\n#define MAC_CHANNEL_FREQ 2\n#define MAC_CHANNEL_STATUS 3\n\nconst char mac_tx_type_cnf[] PROGMEM = \"cnf\";\nconst char mac_tx_type_ucnf[] PROGMEM = \"uncnf\";\n\nconst char *const mac_tx_table[] PROGMEM = {mac_tx_type_cnf, mac_tx_type_ucnf};\n\n#define MAC_TX_TYPE_CNF 0\n#define MAC_TX_TYPE_UCNF 1\n\n#define MAC_TABLE 0\n#define MAC_GET_SET_TABLE 1\n#define MAC_JOIN_TABLE 2\n#define MAC_CH_TABLE 3\n#define MAC_TX_TABLE 4\n#define SYS_TABLE 5\n#define RADIO_TABLE 6\n#define ERR_MESSAGE 7\n#define SUCCESS_MESSAGE 8\n#define CMP_TABLE 9\n#define CMP_ERR_TABLE 10\n\nint pgmstrcmp(const char *str1, uint8_t str2Index, uint8_t table = CMP_TABLE)\n{\n  if (0 == strlen(str1))\n\t  return -1;\n\n  char str2[128];\n\n  switch (table) {\n  case CMP_ERR_TABLE:\n    strcpy_P(str2, (char *)pgm_read_word(&(compareerr_table[str2Index])));\n    break;\n\n  default:\n  case CMP_TABLE:\n    strcpy_P(str2, (char *)pgm_read_word(&(compare_table[str2Index])));\n  }\n\n  return memcmp(str1, str2, min(strlen(str1), strlen(str2)));\n}\n\nuint8_t digits(uint8_t port)\n{\n  if (port >= 100)\n  {\n    return 3;\n  }\n  else if (port >= 10)\n  {\n    return 2;\n  }\n  return 1;\n}\n\nuint8_t receivedPort(const char *s)\n{\n  uint8_t port = 0;\n  uint8_t i = 0;\n  while (s[i] != ' ' && s[i] != '\\0')\n  {\n    port *= 10;\n    port += s[i] - 48;\n    i++;\n  }\n  return port;\n}\n\nTheThingsNetwork::TheThingsNetwork(Stream &modemStream, Stream &debugStream, ttn_fp_t fp, uint8_t sf, uint8_t fsb)\n{\n  this->debugStream = &debugStream;\n  this->modemStream = &modemStream;\n  this->modemStream->setTimeout(TTN_DEFAULT_TIMEOUT);\n  this->fp = fp;\n  this->sf = sf;\n  this->fsb = fsb;\n  this->adr = false;\n  this->messageCallback = NULL;\n}\n\nsize_t TheThingsNetwork::getAppEui(char *buffer, size_t size)\n{\n  return readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_APPEUI, buffer, size);\n}\n\nsize_t TheThingsNetwork::getHardwareEui(char *buffer, size_t size)\n{\n  return readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, size);\n}\n\nsize_t TheThingsNetwork::getVersion(char *buffer, size_t size)\n{\n  return readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_VER, buffer, size);\n}\n\nuint16_t TheThingsNetwork::getVDD()\n{\n  if (readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_VDD, buffer, sizeof(buffer)) > 0) {\n    return atoi(buffer);\n  }\n  return 0;\n}\n\nuint8_t TheThingsNetwork::getBW()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_BW, buffer, sizeof(buffer)) > 0) {\n    return atoi(buffer);\n  }\n  return 0;\n}\n\nuint8_t TheThingsNetwork::getCR()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_CR, buffer, sizeof(buffer)) > 2) {\n    return atoi(buffer+2); // skip the first two chars \"4/\"\n  }\n  return 0;\n}\n\nuint32_t TheThingsNetwork::getFrequency()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_FREQ, buffer, sizeof(buffer)) > 0) {\n    return atol(buffer);\n  }\n  return 0;\n}\n\nuint32_t TheThingsNetwork::getFCU()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_UPCTR, buffer, sizeof(buffer)) > 0) {\n    return strtoul(buffer, NULL, 10);\n  }\n  return 0;\n}\n\nuint32_t TheThingsNetwork::getFCD()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DNCTR, buffer, sizeof(buffer)) > 0) {\n    return strtoul(buffer, NULL, 10);\n  }\n  return 0;\n}\n\nuint32_t TheThingsNetwork::getWatchDogTimer()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_WDT, buffer, sizeof(buffer)) > 0) {\n    return atol(buffer);\n  }\n  return 0;\n}\n\nenum ttn_modem_status_t TheThingsNetwork::getStatus()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_STATUS, buffer, sizeof(buffer)) > 0) {\n\tchar **endptr = NULL;\n\tint status = (strtol(buffer, endptr, 16) & 0x0F); // Mask out only active status\n\n\tif (endptr == NULL)\n\t\treturn (enum ttn_modem_status_t)status;\n  }\n  return TTN_MODEM_READ_ERR; // unable to read status\n}\n\nint8_t TheThingsNetwork::getPower()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_PWR, buffer, sizeof(buffer)) > 0) {\n    return atoi(buffer);\n  }\n  return -128;\n}\n\nint16_t TheThingsNetwork::getRSSI()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_RSSI, buffer, sizeof(buffer)) > 0) {\n    return atoi(buffer);\n  }\n  return -255;\n}\n\nint8_t TheThingsNetwork::getSNR()\n{\n  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_SNR, buffer, sizeof(buffer)) > 0) {\n    return atoi(buffer);\n  }\n  return -128;\n}\n\nint8_t TheThingsNetwork::getDR()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DR, buffer, sizeof(buffer))){\n    return atoi(buffer);\n  }\n  return -1;\n}\n\nint8_t TheThingsNetwork::getPowerIndex()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_PWRIDX, buffer, sizeof(buffer)) > 0) {\n    return atoi(buffer);\n  }\n  return -1;\n}\n\nbool TheThingsNetwork::getChannelStatus (uint8_t channel)\n{\n  char str[5];\n  if (channel > 9)\n  {\n\tstr[0] = ((channel - (channel % 10)) / 10) + 48;\n\tstr[1] = (channel % 10) + 48;\n\tstr[2] = '\\0';\n  }\n  else\n  {\n\tstr[0] = channel + 48;\n\tstr[1] = '\\0';\n  }\n  sendCommand(MAC_TABLE, MAC_PREFIX, true, false);\n  sendCommand(MAC_TABLE, MAC_GET, true, false); // default \"get \" in between (same as radio get)\n  sendCommand(MAC_GET_SET_TABLE, MAC_CH, true, false);\n  sendCommand(MAC_CH_TABLE, MAC_CHANNEL_STATUS, true, false);\n  modemStream->write(str);\n  modemStream->write(SEND_MSG);\n\n  if (readLine(buffer, sizeof(buffer)))\n\t  return (pgmstrcmp(buffer, CMP_ON) == 0); // true if on, false if off or an error occurs\n  else\n\t  return false; // error\n}\n\nttn_response_code_t TheThingsNetwork::getLastError(){\n\n\tint match, pos;\n\tfor (pos=0; pos <= CMP_ERR_LAST; pos++){\n\t\tmatch = pgmstrcmp(buffer, pos, CMP_ERR_TABLE);\n\t\tif (match == 0)\n\t\t\tbreak;\n\t}\n\n\treturn (ttn_response_code_t)(-1* pos); // code order is equal\n}\n\nvoid TheThingsNetwork::debugPrintIndex(uint8_t index, const char *value)\n{\n  char message[100];\n  strcpy_P(message, (char *)pgm_read_word(&(show_table[index])));\n  debugPrint(message);\n  if (value)\n  {\n    debugPrintLn(value);\n  }\n}\n\nvoid TheThingsNetwork::debugPrintMessage(uint8_t type, uint8_t index, const char *value)\n{\n  char message[100];\n  switch (type)\n  {\n  case ERR_MESSAGE:\n    strcpy_P(message, (char *)pgm_read_word(&(error_msg[index])));\n    break;\n  case SUCCESS_MESSAGE:\n    strcpy_P(message, (char *)pgm_read_word(&(success_msg[index])));\n    break;\n  }\n  debugPrint(message);\n  if (value)\n  {\n    debugPrintLn(value);\n  }\n  else\n  {\n    debugPrintLn();\n  }\n}\n\nvoid TheThingsNetwork::clearReadBuffer()\n{\n  while (modemStream->available())\n  {\n    modemStream->read();\n  }\n}\n\nsize_t TheThingsNetwork::readLine(char *buffer, size_t size, uint8_t attempts)\n{\n  size_t read = 0;\n  while (!read && attempts--)\n  {\n    read = modemStream->readBytesUntil('\\n', buffer, size);\n  }\n  if (!read)\n  { // If attempts is activated return 0 and set RN state marker\n    this->needsHardReset = true; // Inform the application about the radio module is not responsive.\n    debugPrintMessage(ERR_MESSAGE, ERR_NO_RESPONSE);\n    return 0;\n  }\n  buffer[read - 1] = '\\0'; // set \\r to \\0\n  return read;\n}\n\nsize_t TheThingsNetwork::readResponse(uint8_t prefixTable, uint8_t index, char *buffer, size_t size)\n{\n  clearReadBuffer();\n  sendCommand(prefixTable, 0, true, false);\n  sendCommand(prefixTable, index, false, false);\n  modemStream->write(SEND_MSG);\n  return readLine(buffer, size);\n}\n\nsize_t TheThingsNetwork::readResponse(uint8_t prefixTable, uint8_t indexTable, uint8_t index, char *buffer, size_t size)\n{\n  clearReadBuffer();\n  sendCommand(prefixTable, 0, true, false);\n  sendCommand(MAC_TABLE, MAC_GET, true, false);\n  sendCommand(indexTable, index, false, false);\n  modemStream->write(SEND_MSG);\n  return readLine(buffer, size);\n}\n\nvoid TheThingsNetwork::autoBaud()\n{\n  // Courtesy of @jpmeijers\n  modemStream->setTimeout(2000);\n  uint8_t attempts = 10;\n  size_t length = 0;\n  while (attempts-- && length == 0)\n  {\n    delay(100);\n    modemStream->write((byte)0x00);\n    modemStream->write(0x55);\n    modemStream->write(SEND_MSG);\n    sendCommand(SYS_TABLE, 0, true, false);\n    sendCommand(SYS_TABLE, SYS_GET, true, false);\n    sendCommand(SYS_TABLE, SYS_GET_VER, false, false);\n    modemStream->write(SEND_MSG);\n    length = modemStream->readBytesUntil('\\n', buffer, sizeof(buffer));\n  }\n  delay(100);\n  clearReadBuffer();\n  modemStream->setTimeout(TTN_DEFAULT_TIMEOUT);\n  baudDetermined = true;\n}\n\nvoid TheThingsNetwork::reset(bool adr)\n{\n  // autobaud and send \"sys reset\"\n  autoBaud();\n  readResponse(SYS_TABLE, SYS_RESET, buffer, sizeof(buffer));\n\n  // autobaud (again, because baudrate was reset with \"sys reset\") and get HW model and SW version\n  autoBaud();\n  getVersion(buffer, sizeof(buffer));\n\n  // buffer contains \"RN2xx3[xx] x.x.x ...\", splitting model from version\n  char *model = strtok(buffer, \" \");\n  debugPrintIndex(SHOW_MODEL, model);\n  char *version = strtok(NULL, \" \");\n  debugPrintIndex(SHOW_VERSION, version);\n\n  // set DEVEUI as HWEUI\n  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, sizeof(buffer));\n  sendMacSet(MAC_DEVEUI, buffer);\n  // set ADR\n  setADR(adr);\n}\n\nvoid TheThingsNetwork::resetHard(uint8_t resetPin){\n  digitalWrite(resetPin, LOW);\n  delay(1000);\n  digitalWrite(resetPin, HIGH);\n}\n\nvoid TheThingsNetwork::saveState()\n{\n  debugPrint(SENDING);\n  sendCommand(MAC_TABLE, MAC_PREFIX, true);\n  sendCommand(MAC_TABLE, MAC_SAVE, false);\n  modemStream->write(SEND_MSG);\n  debugPrintLn();\n  waitForOk();\n}\n\nvoid TheThingsNetwork::onMessage(void (*cb)(const uint8_t *payload, size_t size, port_t port))\n{\n  messageCallback = cb;\n}\n\nbool TheThingsNetwork::personalize(const char *devAddr, const char *nwkSKey, const char *appSKey, bool resetFirst)\n{\n  if(resetFirst) {\n    reset(adr);\n  }\n  if (strlen(devAddr) != 8 || strlen(appSKey) != 32 || strlen(nwkSKey) != 32)\n  {\n    debugPrintMessage(ERR_MESSAGE, ERR_KEY_LENGTH);\n    return false;\n  }\n  sendMacSet(MAC_DEVADDR, devAddr);\n  sendMacSet(MAC_NWKSKEY, nwkSKey);\n  sendMacSet(MAC_APPSKEY, appSKey);\n  return personalize();\n}\n\nbool TheThingsNetwork::personalize()\n{\n  configureChannels(fsb);\n  setSF(sf);\n  sendJoinSet(MAC_JOIN_MODE_ABP);\n  readLine(buffer, sizeof(buffer));\n  if (pgmstrcmp(buffer, CMP_ACCEPTED) != 0)\n  {\n    debugPrintMessage(ERR_MESSAGE, ERR_PERSONALIZE_NOT_ACCEPTED, buffer);\n    debugPrintMessage(ERR_MESSAGE, ERR_CHECK_CONFIGURATION);\n    return false;\n  }\n\n  readResponse(MAC_TABLE, MAC_CH_TABLE, MAC_CHANNEL_STATUS, buffer, sizeof(buffer));\n  debugPrintMessage(SUCCESS_MESSAGE, SCS_PERSONALIZE_ACCEPTED, buffer);\n  return true;\n}\n\nbool TheThingsNetwork::provision(const char *appEui, const char *appKey, bool resetFirst)\n{\n  if(resetFirst) {\n    reset(adr);\n  }\n  if (strlen(appEui) != 16 || strlen(appKey) != 32)\n  {\n    debugPrintMessage(ERR_MESSAGE, ERR_KEY_LENGTH);\n    return false;\n  }\n  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, sizeof(buffer));\n  sendMacSet(MAC_DEVEUI, buffer);\n  sendMacSet(MAC_APPEUI, appEui);\n  sendMacSet(MAC_APPKEY, appKey);\n  saveState();\n  return true;\n}\n\nbool TheThingsNetwork::join(int8_t retries, uint32_t retryDelay)\n{\n  int8_t attempts = 0;\n  configureChannels(fsb);\n  setSF(sf);\n  while (retries == -1 || attempts <= retries)\n  {\n    attempts++;\n    if (!sendJoinSet(MAC_JOIN_MODE_OTAA))\n    {\n      debugPrintMessage(ERR_MESSAGE, ERR_JOIN_FAILED);\n      delay(retryDelay);\n      continue;\n    }\n    readLine(buffer, sizeof(buffer));\n    if (pgmstrcmp(buffer, CMP_ACCEPTED) != 0)\n    {\n      debugPrintMessage(ERR_MESSAGE, ERR_JOIN_NOT_ACCEPTED, buffer);\n      debugPrintMessage(ERR_MESSAGE, ERR_CHECK_CONFIGURATION);\n      delay(retryDelay);\n      continue;\n    }\n    readResponse(MAC_TABLE, MAC_CH_TABLE, MAC_CHANNEL_STATUS, buffer, sizeof(buffer));\n    debugPrintMessage(SUCCESS_MESSAGE, SCS_JOIN_ACCEPTED, buffer);\n    readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DEVADDR, buffer, sizeof(buffer));\n    debugPrintIndex(SHOW_DEVADDR, buffer);\n    return true;\n  }\n  return false;\n}\n\nbool TheThingsNetwork::setClass(lorawan_class_t p_lw_class)\n{\n  switch(p_lw_class)\n  {\n\n  case CLASS_A:\n    {\n      lw_class = p_lw_class;\n      return sendMacSet(MAC_CLASS, \"a\");\n    }\n\n  // case CLASS_B: // Not yet supported. Use default case.\n\n  case CLASS_C:\n    {\n      bool result = sendMacSet(MAC_CLASS, \"c\");\n      // Older firmware does not support Class C. If setting change fails, keep on using Class A.\n      if(result) lw_class = p_lw_class;\n      return result;\n    }\n\n  default:\n    return false;\n\n  }\n}\n\nbool TheThingsNetwork::join(const char *appEui, const char *appKey, int8_t retries, uint32_t retryDelay, lorawan_class_t p_lw_class)\n{\n  return provision(appEui, appKey) && join(retries, retryDelay) && setClass(p_lw_class);\n}\n\nttn_response_t TheThingsNetwork::parseBytes(){\n    if (buffer[0]=='\\0')\n  \t  return TTN_UNSUCCESSFUL_RECEIVE;\n\n\tif (pgmstrcmp(buffer, CMP_MAC_RX) == 0)\n    {\n\t\tport_t downlinkPort = receivedPort(buffer + 7);\n\t\tchar *data = buffer + 7 + digits(downlinkPort) + 1;\n\t\tsize_t downlinkLength = strlen(data) / 2;\n\t\tif (downlinkLength > 0)\n\t\t{\n\t\t  uint8_t downlink[downlinkLength];\n\t\t  for (size_t i = 0, d = 0; i < downlinkLength; i++, d += 2)\n\t\t  {\n\t\t\tdownlink[i] = TTN_HEX_PAIR_TO_BYTE(data[d], data[d + 1]);\n\t\t  }\n\t\t  debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION_RECEIVED, data);\n\t\t  if (messageCallback)\n\t\t  {\n\t\t\tmessageCallback(downlink, downlinkLength, downlinkPort);\n\t\t  }\n\t\t}\n\t\telse\n\t\t{\n\t\t  debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION);\n\t\t}\n\t\treturn TTN_SUCCESSFUL_RECEIVE;\n\t}\n    // not REC but buffer FULL\n    debugPrintMessage(ERR_MESSAGE, ERR_UNEXPECTED_RESPONSE, buffer);\n    return TTN_ERROR_UNEXPECTED_RESPONSE;\n}\n\nttn_response_t TheThingsNetwork::sendBytes(const uint8_t *payload, size_t length, port_t port, bool confirm, uint8_t sf)\n{\n  if (sf != 0)\n  {\n    setSF(sf);\n  }\n\n  uint8_t mode = confirm ? MAC_TX_TYPE_CNF : MAC_TX_TYPE_UCNF;\n  if (!sendPayload(mode, port, (uint8_t *)payload, length))\n  {\n    debugPrintMessage(ERR_MESSAGE, ERR_SEND_COMMAND_FAILED);\n    return TTN_ERROR_SEND_COMMAND_FAILED;\n  }\n\n  // read modem response\n  if (!readLine(buffer, sizeof(buffer)) && confirm) // Read response\n\t  // confirmed and RX timeout -> ask to poll if necessary\n\t  return TTN_UNSUCCESSFUL_RECEIVE;\n\n  // TX only?\n  if (pgmstrcmp(buffer, CMP_MAC_TX_OK) == 0)\n  {\n    debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION);\n    return TTN_SUCCESSFUL_TRANSMISSION;\n  }\n  else if (pgmstrcmp(buffer, CMP_MAC_ERR) == 0)\n\treturn TTN_UNSUCCESSFUL_RECEIVE;\n\n  // Received downlink message?\n  return parseBytes();\n}\n\nttn_response_t TheThingsNetwork::poll(port_t port, bool confirm, bool modem_only)\n{\n  switch(lw_class)\n  {\n\n  case CLASS_A:\n\t  if (!modem_only)\n\t\t{\n\t\t  // Class A: send uplink and wait for rx windows\n\t\t  uint8_t payload[] = {0x00};\n\t\t  return sendBytes(payload, 1, port, confirm);\n\t\t}\n\t  else\n\t  {\n\t\t  if (!readLine(buffer, sizeof(buffer)) && confirm) // Read response\n\t\t\t  // confirmed and RX timeout -> ask to poll if necessary\n\t\t\t  return TTN_UNSUCCESSFUL_RECEIVE;\n\n\t\t  // Here we can have the result of pending TX, or pending RX (for confirmed messages)\n\t\t  if (pgmstrcmp(buffer, CMP_MAC_TX_OK) == 0)\n\t\t  {\n\t\t    debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION);\n\t\t    return TTN_SUCCESSFUL_TRANSMISSION;\n\t\t  }\n\t\t  else if (pgmstrcmp(buffer, CMP_MAC_ERR) == 0)\n\t\t\treturn TTN_UNSUCCESSFUL_RECEIVE;\n\n\t\t  // Receive Message\n\t\t  return parseBytes();\n\t  }\n\n\n  case CLASS_C:\n\t  {\n\t\t  // Class C: check rx buffer for any received data\n\t\t  memset(buffer, 0, sizeof(buffer));\n\n\t\t  uint32_t timeout = this->modemStream->getTimeout();\n\t\t  this->modemStream->setTimeout(100);\n\t\t  this->modemStream->readBytesUntil('\\n', buffer, sizeof(buffer));\n\t\t  this->modemStream->setTimeout(timeout);\n\n\t\t  return parseBytes();\n\t  }\n\n  default:\n  case CLASS_B: // Not yet supported. Use default case.\n\t  return TTN_UNSUCCESSFUL_RECEIVE;\n\n  }\n}\n\nvoid TheThingsNetwork::showStatus()\n{\n  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_EUI, buffer);\n  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_VDD, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_BATTERY, buffer);\n  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_APPEUI, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_APPEUI, buffer);\n  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DEVEUI, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_DEVEUI, buffer);\n  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DR, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_DATA_RATE, buffer);\n  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_RXDELAY1, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_RX_DELAY_1, buffer);\n  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_RXDELAY2, buffer, sizeof(buffer));\n  debugPrintIndex(SHOW_RX_DELAY_2, buffer);\n}\n\nbool TheThingsNetwork::checkValidModuleConnected(bool autoBaudFirst)\n{\n  // check if we want to autobaud first\n  if(autoBaudFirst)\n  {\n    autoBaud();\n  }\n  // send \"sys get ver\" to check if (and what) module is connected\n  getVersion(buffer, sizeof(buffer));\n  // check if we got a response (whatever it might be)\n  // needsHardReset flag is set by readLine() (called at some point down the line by getVersion())\n  if(this->needsHardReset)\n  {\n    return false;                                               // no response\n  }\n  // buffer contains \"RN2xx3[xx] x.x.x ...\", getting only model (RN2xx3[xx])\n  char *model = strtok(buffer, \" \");\n  debugPrintIndex(SHOW_MODEL, model);\n  // check if module is valid (must be RN2483, RN2483A, RN2903 or RN2903AS)\n  if(pgmstrcmp(model, CMP_RN2483) == 0 || pgmstrcmp(model, CMP_RN2483A) == 0 || pgmstrcmp(model, CMP_RN2903) == 0 || pgmstrcmp(model, CMP_RN2903AS) == 0)\n  {\n    debugPrintMessage(SUCCESS_MESSAGE, SCS_VALID_MODULE);\n    return true;                                                // module responded and is valid (recognized/supported)\n  }\n  debugPrintMessage(ERR_MESSAGE, ERR_INVALID_MODULE);\n  return false;                                                 // module responded but is invalid (unrecognized/unsupported)\n}\n\nvoid TheThingsNetwork::configureEU868()\n{\n  sendMacSet(MAC_RX2, 3, 869525000);\n  sendChSet(MAC_CHANNEL_DRRANGE, 1, \"0 6\");\n\n  char buf[10];\n  uint32_t freq = 867100000;\n  uint8_t ch;\n  for (ch = 0; ch < 8; ch++)\n  {\n    if (ch > 2)\n    {\n      sprintf(buf, \"%lu\", freq);\n      sendChSet(MAC_CHANNEL_FREQ, ch, buf);\n      sendChSet(MAC_CHANNEL_DRRANGE, ch, \"0 5\");\n      sendChSet(MAC_CHANNEL_DCYCLE, ch, 499); // 5*0.2% ETSI band G1, total 1%\n      setChannelStatus(ch, true);;\n      freq = freq + 200000;\n    }\n    else\n    \tsendChSet(MAC_CHANNEL_DCYCLE, ch, 299); // 3*0.33% ETSI band G, total 1%\n  }\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_EU868);\n}\n\nvoid TheThingsNetwork::configureUS915(uint8_t fsb)\n{\n  uint8_t ch;\n  uint8_t chLow = fsb > 0 ? (fsb - 1) * 8 : 0;\n  uint8_t chHigh = fsb > 0 ? chLow + 7 : 71;\n  uint8_t ch500 = fsb + 63;\n  for (ch = 0; ch < 72; ch++)\n  {\n    if (ch == ch500 || (ch <= chHigh && ch >= chLow))\n    {\n      setChannelStatus(ch, true);\n      if (ch < 63)\n      {\n        sendChSet(MAC_CHANNEL_DRRANGE, ch, \"0 3\");\n      }\n    }\n    else\n    {\n    \tsetChannelStatus(ch, false);\n    }\n  }\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_US915);\n}\n\nvoid TheThingsNetwork::configureAU915(uint8_t fsb)\n{\n  uint8_t ch;\n  uint8_t chLow = fsb > 0 ? (fsb - 1) * 8 : 0;\n  uint8_t chHigh = fsb > 0 ? chLow + 7 : 71;\n  uint8_t ch500 = fsb + 63;\n  for (ch = 0; ch < 72; ch++)\n  {\n    if (ch == ch500 || (ch <= chHigh && ch >= chLow))\n    {\n      setChannelStatus(ch, true);\n      if (ch < 63)\n      {\n        sendChSet(MAC_CHANNEL_DRRANGE, ch, \"0 3\");\n      }\n    }\n    else\n    {\n    \tsetChannelStatus(ch, false);\n    }\n  }\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_AU915);\n}\n\nvoid TheThingsNetwork::configureAS920_923()\n{\n  /* RN2903AS 1.0.3rc9 defaults\n   * CH0 = 923.2MHz\n   * CH1 = 923.4MHz\n   */\n  setADR(false); // TODO: remove when ADR is implemented for this plan\n  sendMacSet(MAC_RX2, 2, 923200000);\n\n  char buf[10];\n  uint32_t freq = 922000000;\n  uint8_t ch;\n  for (ch = 0; ch < 8; ch++)\n  {\n    sendChSet(MAC_CHANNEL_DCYCLE, ch, 799);\n    if (ch > 1)\n    {\n      sprintf(buf, \"%lu\", freq);\n      sendChSet(MAC_CHANNEL_FREQ, ch, buf);\n      sendChSet(MAC_CHANNEL_DRRANGE, ch, \"0 5\");\n      setChannelStatus(ch, true);\n      freq = freq + 200000;\n    }\n  }\n  // TODO: SF7BW250/DR6 channel, not properly supported by RN2903AS yet\n  //sendChSet(MAC_CHANNEL_DCYCLE, 8, 799);\n  //sendChSet(MAC_CHANNEL_FREQ, 8, 922100000);\n  //sendChSet(MAC_CHANNEL_DRRANGE, 8, \"6 6\");\n  //setChannelStatus(8, true);\n  // TODO: Add FSK channel on 921800000\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_AS920_923);\n}\n\nvoid TheThingsNetwork::configureAS923_925()\n{\n  /* RN2903AS 1.0.3rc9 defaults\n   * CH0 = 923.2MHz\n   * CH1 = 923.4MHz\n   */\n  setADR(false); // TODO: remove when ADR is implemented for this plan\n  sendMacSet(MAC_RX2, 2, 923200000);\n\n  char buf[10];\n  uint32_t freq = 923600000;\n  uint8_t ch;\n  for (ch = 0; ch < 8; ch++)\n  {\n    sendChSet(MAC_CHANNEL_DCYCLE, ch, 799);\n    if (ch > 1)\n    {\n      sprintf(buf, \"%lu\", freq);\n      sendChSet(MAC_CHANNEL_FREQ, ch, buf);\n      sendChSet(MAC_CHANNEL_DRRANGE, ch, \"0 5\");\n      setChannelStatus(ch, true);\n      freq = freq + 200000;\n    }\n  }\n  // TODO: SF7BW250/DR6 channel, not properly supported by RN2903AS yet\n  //sendChSet(MAC_CHANNEL_DCYCLE, 8, 799);\n  //sendChSet(MAC_CHANNEL_FREQ, 8, 924500000);\n  //sendChSet(MAC_CHANNEL_DRRANGE, 8, \"6 6\");\n  //setChannelStatus(8, true);\n  // TODO: Add FSK channel on 924800000\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_AS923_925);\n}\n\nvoid TheThingsNetwork::configureKR920_923()\n{\n  setADR(false); // TODO: remove when ADR is implemented for this plan\n  sendMacSet(MAC_RX2, 0, 921900000); // KR still uses SF12 for now. Might change to SF9 later.\n\n  //disable two default LoRaWAN channels\n  setChannelStatus(0, false);\n  setChannelStatus(1, false);\n\n  char buf[10];\n  uint32_t freq = 922100000;\n  uint8_t ch;\n  for (ch = 2; ch < 9; ch++)\n  {\n    sendChSet(MAC_CHANNEL_DCYCLE, ch, 799);\n    sprintf(buf, \"%lu\", freq);\n    sendChSet(MAC_CHANNEL_FREQ, ch, buf);\n    sendChSet(MAC_CHANNEL_DRRANGE, ch, \"0 5\");\n    setChannelStatus(ch, true);\n    freq = freq + 200000;\n  }\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_KR920_923);\n}\n\nvoid TheThingsNetwork::configureIN865_867()\n{\n  setADR(false); // TODO: remove when ADR is implemented for this plan\n  sendMacSet(MAC_RX2, 2, 866550000); // SF10\n\n  // Disable the three default LoRaWAN channels\n  setChannelStatus(0, false);\n  setChannelStatus(1, false);\n  setChannelStatus(2, false);\n\n  // Channel 3\n  sendChSet(MAC_CHANNEL_DCYCLE, 3, 299);\n  sendChSet(MAC_CHANNEL_FREQ, 3, 865062500);\n  sendChSet(MAC_CHANNEL_DRRANGE, 3, \"0 5\");\n  setChannelStatus(3, true);\n\n  // Channel 4\n  sendChSet(MAC_CHANNEL_DCYCLE, 4, 299);\n  sendChSet(MAC_CHANNEL_FREQ, 4, 865402500);\n  sendChSet(MAC_CHANNEL_DRRANGE, 4, \"0 5\");\n  setChannelStatus(4, true);\n\n  // Channel 5\n  sendChSet(MAC_CHANNEL_DCYCLE, 5, 299);\n  sendChSet(MAC_CHANNEL_FREQ, 5, 865985000);\n  sendChSet(MAC_CHANNEL_DRRANGE, 5, \"0 5\");\n  setChannelStatus(5, true);\n\n  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_IN865_867);\n}\n\nvoid TheThingsNetwork::configureChannels(uint8_t fsb)\n{\n  switch (fp)\n  {\n  case TTN_FP_EU868:\n    configureEU868();\n    break;\n  case TTN_FP_US915:\n    configureUS915(fsb);\n    break;\n  case TTN_FP_AU915:\n    configureAU915(fsb);\n    break;\n  case TTN_FP_AS920_923:\n    configureAS920_923();\n    break;\n  case TTN_FP_AS923_925:\n    configureAS923_925();\n    break;\n  case TTN_FP_KR920_923:\n    configureKR920_923();\n    break;\n  case TTN_FP_IN865_867:\n    configureIN865_867();\n    break;\n  default:\n    debugPrintMessage(ERR_MESSAGE, ERR_INVALID_FP);\n    break;\n  }\n  sendMacSet(MAC_RETX, TTN_RETX);\n}\n\nbool TheThingsNetwork::setChannel(uint8_t channel, uint32_t frequency, uint8_t dr_min, uint8_t dr_max){\n\n  bool done = true;\n\n  if (channel > 15)\n\t  return false;\n\n  if (frequency){\n\tchar buf[11];\n\tsprintf(buf, \"%lu\", frequency);\n\tdone &= sendChSet(MAC_CHANNEL_FREQ, channel, buf);\n  }\n\n  if (done && (dr_min < 16) && (dr_max < 16)){\n\tchar buf[11];\n\tsprintf(buf, \"%u %u\", dr_min, dr_max);\n\tdone &= sendChSet(MAC_CHANNEL_DRRANGE, channel, buf);\n  }\n  else\n\tdone &= (dr_min == 255) && (dr_max == 255);\n\n  return done;\n}\n\nbool TheThingsNetwork::setRx2Channel(uint32_t frequency, uint8_t dr){\n\n  char buf[15];\n  sprintf(buf, \"%u %lu\", dr, frequency);\n  return sendMacSet(MAC_RX2, buf);\n}\n\nbool TheThingsNetwork::setChannelStatus (uint8_t channel, bool status){\n  if (status)\n    return sendChSet(MAC_CHANNEL_STATUS, channel, \"on\");\n  else\n    return sendChSet(MAC_CHANNEL_STATUS, channel, \"off\");\n}\n\nbool TheThingsNetwork::setChannelDCycle (uint8_t channel, float duty_cycle){ // in percent\n  if (channel > 15 || duty_cycle > 100.0 || duty_cycle < 0.0)\n\treturn false;\n\n  char buf[6]; // number 99999\n  if (0.0 == duty_cycle)\n\t  (void)sprintf(buf, \"%u\", 65535u);\n  else\n\t  (void)sprintf(buf, \"%u\", (uint16_t)((100.0/duty_cycle) - 1));\n\n  return sendChSet(MAC_CHANNEL_DCYCLE, channel, buf);\n}\n\nbool TheThingsNetwork::setPowerIndex(uint8_t index){\n  char buf[4];\n  sprintf(buf, \"%u\",index);\n  return sendMacSet(MAC_PWRIDX, buf);\n}\n\nbool TheThingsNetwork::setDR(uint8_t dr){\n  char buf[4];\n  sprintf(buf, \"%u\",dr);\n  return sendMacSet(MAC_DR, buf);\n}\n\nbool TheThingsNetwork::setADR(bool adr){\n\tbool ret;\n\tif (adr)\n\t{\n\t\tret = sendMacSet(MAC_ADR, \"on\");\n\t}\n\telse\n\t{\n\t\tret = sendMacSet(MAC_ADR, \"off\");\n\t}\n\tthis->adr = adr;\n\treturn ret;\n}\n\nbool TheThingsNetwork::setSF(uint8_t sf)\n{\n  uint8_t dr;\n  switch (fp)\n  {\n  case TTN_FP_EU868:\n  case TTN_FP_IN865_867:\n  case TTN_FP_AS920_923:\n  case TTN_FP_AS923_925:\n  case TTN_FP_KR920_923:\n  default:\n    dr = 12 - sf;\n    break;\n  case TTN_FP_US915:\n  case TTN_FP_AU915:\n    dr = 10 - sf;\n    break;\n  }\n  char s[2];\n  s[0] = '0' + dr;\n  s[1] = '\\0';\n  return sendMacSet(MAC_DR, s);\n}\n\nbool TheThingsNetwork::setRX1Delay(uint16_t delay){\n\t  char buf[6];\n\t  sprintf(buf, \"%u\",delay);\n\t  return sendMacSet(MAC_RXDELAY1, buf);\n}\n\nbool TheThingsNetwork::setFCU(uint32_t fcu){\n  char buf[10];\n  sprintf(buf, \"%lu\", fcu);\n  return sendMacSet(MAC_UPCTR, buf);\n}\n\nbool TheThingsNetwork::setFCD(uint32_t fcd){\n  char buf[10];\n  sprintf(buf, \"%lu\", fcd);\n  return sendMacSet(MAC_DNCTR, buf);\n}\n\nvoid TheThingsNetwork::sendCommand(uint8_t table, uint8_t index, bool appendSpace, bool print)\n{\n  char command[100];\n  switch (table)\n  {\n  case MAC_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(mac_table[index])));\n    break;\n  case MAC_GET_SET_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(mac_options[index])));\n    break;\n  case MAC_JOIN_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(mac_join_mode[index])));\n    break;\n  case MAC_CH_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(mac_ch_options[index])));\n    break;\n  case MAC_TX_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(mac_tx_table[index])));\n    break;\n  case SYS_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(sys_table[index])));\n    break;\n  case RADIO_TABLE:\n    strcpy_P(command, (char *)pgm_read_word(&(radio_table[index])));\n    break;\n  default:\n    return;\n  }\n  modemStream->write(command);\n  if (appendSpace)\n  {\n    modemStream->write(\" \");\n  }\n  if (print)\n  {\n    debugPrint(command);\n    debugPrint(F(\" \"));\n  }\n}\n\nbool TheThingsNetwork::sendMacSet(uint8_t index, uint8_t value1, unsigned long value2)\n{\n\tchar buf[15];\n\tsprintf(buf, \"%u %lu\", value1, value2);\n\treturn sendMacSet(index, buf);\n}\n\nbool TheThingsNetwork::sendMacSet(uint8_t index, const char *value)\n{\n  clearReadBuffer();\n  debugPrint(SENDING);\n  sendCommand(MAC_TABLE, MAC_PREFIX, true);\n  sendCommand(MAC_TABLE, MAC_SET, true);\n  sendCommand(MAC_GET_SET_TABLE, index, true);\n  modemStream->write(value);\n  modemStream->write(SEND_MSG);\n  debugPrintLn(value);\n  return waitForOk();\n}\n\nbool TheThingsNetwork::waitForOk()\n{\n  readLine(buffer, sizeof(buffer));\n  if (pgmstrcmp(buffer, CMP_OK) != 0)\n  {\n    debugPrintMessage(ERR_MESSAGE, ERR_RESPONSE_IS_NOT_OK, buffer);\n    return false;\n  }\n  return true;\n}\n\nbool TheThingsNetwork::sendChSet(uint8_t index, uint8_t channel, unsigned long value)\n{\n\tchar buf[11];\n\tsprintf(buf, \"%lu\", value);\n\treturn sendChSet(index, channel, buf);\n}\n\nbool TheThingsNetwork::sendChSet(uint8_t index, uint8_t channel, const char *value)\n{\n  clearReadBuffer();\n  char ch[5];\n  if (channel > 9)\n  {\n    ch[0] = ((channel - (channel % 10)) / 10) + 48;\n    ch[1] = (channel % 10) + 48;\n    ch[2] = '\\0';\n  }\n  else\n  {\n    ch[0] = channel + 48;\n    ch[1] = '\\0';\n  }\n  debugPrint(F(SENDING));\n  sendCommand(MAC_TABLE, MAC_PREFIX, true);\n  sendCommand(MAC_TABLE, MAC_SET, true);\n  sendCommand(MAC_GET_SET_TABLE, MAC_CH, true);\n  sendCommand(MAC_CH_TABLE, index, true);\n  modemStream->write(ch);\n  modemStream->write(\" \");\n  modemStream->write(value);\n  modemStream->write(SEND_MSG);\n  debugPrint(channel);\n  debugPrint(F(\" \"));\n  debugPrintLn(value);\n  return waitForOk();\n}\n\nbool TheThingsNetwork::sendJoinSet(uint8_t type)\n{\n  clearReadBuffer();\n  debugPrint(F(SENDING));\n  sendCommand(MAC_TABLE, MAC_PREFIX, true);\n  sendCommand(MAC_TABLE, MAC_JOIN, true);\n  sendCommand(MAC_JOIN_TABLE, type, false);\n  modemStream->write(SEND_MSG);\n  debugPrintLn();\n  return waitForOk();\n}\n\nbool TheThingsNetwork::sendPayload(uint8_t mode, uint8_t port, uint8_t *payload, size_t length)\n{\n  clearReadBuffer();\n  debugPrint(F(SENDING));\n  sendCommand(MAC_TABLE, MAC_PREFIX, true);\n  sendCommand(MAC_TABLE, MAC_TX, true);\n  sendCommand(MAC_TX_TABLE, mode, true);\n  char sport[4];\n  if (port > 99)\n  {\n    sport[0] = ((port - (port % 100)) / 100) + 48;\n    sport[1] = (((port % 100) - (port % 10)) / 10) + 48;\n    sport[2] = (port % 10) + 48;\n    sport[3] = '\\0';\n  }\n  else if (port > 9)\n  {\n    sport[0] = ((port - (port % 10)) / 10) + 48;\n    sport[1] = (port % 10) + 48;\n    sport[2] = '\\0';\n  }\n  else\n  {\n    sport[0] = port + 48;\n    sport[1] = '\\0';\n  }\n  modemStream->write(sport);\n  modemStream->print(\" \");\n  debugPrint(sport);\n  debugPrint(F(\" \"));\n  uint8_t i = 0;\n  for (i = 0; i < length; i++)\n  {\n    if (payload[i] < 16)\n    {\n      modemStream->print(\"0\");\n      modemStream->print(payload[i], HEX);\n      debugPrint(F(\"0\"));\n      debugPrint(payload[i], HEX);\n    }\n    else\n    {\n      modemStream->print(payload[i], HEX);\n      debugPrint(payload[i], HEX);\n    }\n  }\n  modemStream->write(SEND_MSG);\n  debugPrintLn();\n  return waitForOk();\n}\n\nvoid TheThingsNetwork::sleep(uint32_t mseconds)\n{\n  if (mseconds < 100)\n  {\n    return;\n  }\n\n  debugPrint(F(SENDING));\n  sendCommand(SYS_TABLE, SYS_PREFIX, true);\n  sendCommand(SYS_TABLE, SYS_SLEEP, true);\n\n  sprintf(buffer, \"%lu\", mseconds);\n  modemStream->write(buffer);\n  modemStream->write(SEND_MSG);\n  debugPrintLn(buffer);\n}\n\nvoid TheThingsNetwork::wake()\n{\n  autoBaud();\n}\n\nvoid TheThingsNetwork::linkCheck(uint16_t seconds)\n{\n  clearReadBuffer();\n  debugPrint(SENDING);\n  sendCommand(MAC_TABLE, MAC_PREFIX, true);\n  sendCommand(MAC_TABLE, MAC_SET, true);\n  sendCommand(MAC_GET_SET_TABLE, MAC_LINKCHK, true);\n\n  sprintf(buffer, \"%u\", seconds);\n  modemStream->write(buffer);\n  modemStream->write(SEND_MSG);\n  debugPrintLn(buffer);\n  waitForOk();\n}\n\nuint8_t TheThingsNetwork::getLinkCheckGateways()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_GWNB, buffer, sizeof(buffer))){\n\t  char **endptr = NULL;\n\t  uint8_t gwnb = strtol(buffer, endptr, 10);\n\t  if (endptr == NULL)\n\t\t  return gwnb;\n  }\n  return 0; // Gateway number defaults to 0\n}\n\nuint8_t TheThingsNetwork::getLinkCheckMargin()\n{\n  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_MRGN, buffer, sizeof(buffer))){\n\t  char **endptr = NULL;\n\t  uint8_t mgn = strtol(buffer, endptr, 10);\n\t  if (endptr == NULL)\n\t\t  return mgn;\n  }\n  return 255; // Signal margin defaults to 255\n}\n"
  },
  {
    "path": "src/TheThingsNetwork.h",
    "content": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in the LICENSE file.\n\n#ifndef _THETHINGSNETWORK_H_\n#define _THETHINGSNETWORK_H_\n\n#include <Arduino.h>\n#include <Stream.h>\n#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD)\n#include <avr/pgmspace.h>\n#else\n#include <pgmspace.h>\n#endif\n\n#define TTN_DEFAULT_SF 7\n#define TTN_DEFAULT_FSB 2\n#define TTN_RETX \"7\"\n\n#define TTN_PWRIDX_EU868 \"1\"\n#define TTN_PWRIDX_US915 \"5\"\n#define TTN_PWRIDX_AU915 \"5\"\n#define TTN_PWRIDX_AS920_923 \"1\" // TODO: should be 0, but the current RN2903AS firmware doesn't accept that value (probably still using EU868: 1=14dBm)\n#define TTN_PWRIDX_AS923_925 \"1\" // TODO: should be 0\n#define TTN_PWRIDX_KR920_923 \"1\" // TODO: should be 0\n#define TTN_PWRIDX_IN865_867 \"1\" // TODO: should be 0\n\n#define TTN_BUFFER_SIZE 300\n#define TTN_DEFAULT_TIMEOUT 10000\t// Default modem timeout in ms\n\ntypedef uint8_t port_t;\n\nenum ttn_response_t\n{\n  TTN_ERROR_SEND_COMMAND_FAILED = (-1),\n  TTN_ERROR_UNEXPECTED_RESPONSE = (-10),\n  TTN_SUCCESSFUL_TRANSMISSION = 1,\n  TTN_SUCCESSFUL_RECEIVE = 2,\n  TTN_UNSUCCESSFUL_RECEIVE = 3\n};\n\nenum ttn_fp_t\n{\n  TTN_FP_EU868,\n  TTN_FP_US915,\n  TTN_FP_AU915,\n  TTN_FP_AS920_923,\n  TTN_FP_AS923_925,\n  TTN_FP_KR920_923,\n  TTN_FP_IN865_867\n};\n\nenum lorawan_class_t\n{\n  CLASS_A,\n  CLASS_B,\n  CLASS_C\n};\n\nenum ttn_response_code_t\n{\n\tTTN_OK,\n\tTTN_ERROR_BUSY = (-1),\n\tTTN_ERROR_FRAME_COUNTER_ERROR = (-2),\n\tTTN_ERROR_INVALID_CLASS = (-3),\n\tTTN_ERROR_INVALID_LENGTH = (-4),\n\tTTN_ERROR_INVALID_PARAMETER = (-5),\n\tTTN_ERROR_NO_KEY_INTITIALIZED = (-6),\n\tTTN_ERROR_MAC_PAUSE = (-7),\n\tTTN_ERROR_NO_KEY_MULTICAST = (-8),\n\tTTN_ERROR_NO_FREE_CHANNEL = (-9),\n\tTTN_ERROR_NOT_JOINED = (-10),\n\tTTN_ERROR_SILENT = (-11),\n\tTTN_ERROR_ERR = (-12),\n};\n\nenum ttn_modem_status_t\n{\n\tTTN_MODEM_READ_ERR = -1,\n\tTTN_MODEM_IDLE = 0,\n\tTTN_MODEM_TX,\n\tTTN_MODEM_BEFORE_RX,\n\tTTN_MODEM_RX1,\n\tTTN_MODEM_BEFORE_RX2,\n\tTTN_MODEM_RETX_DELAY,\n\tTTN_MODEM_APB_DELAY,\n\tTTN_MODEM_C_RX1,\n\tTTN_MODEM_C_RX2\n};\n\nclass TheThingsNetwork\n{\nprivate:\n  Stream *modemStream;\n  Stream *debugStream = NULL;\n  ttn_fp_t fp;\n  uint8_t sf;\n  uint8_t fsb;\n  bool adr;\n  char buffer[512];\n  bool baudDetermined = false;\n  void (*messageCallback)(const uint8_t *payload, size_t size, port_t port);\n  lorawan_class_t lw_class = CLASS_A;\n\n  void clearReadBuffer();\n  size_t readLine(char *buffer, size_t size, uint8_t attempts = 3);\n  size_t readResponse(uint8_t prefixTable, uint8_t indexTable, uint8_t index, char *buffer, size_t size);\n  size_t readResponse(uint8_t table, uint8_t index, char *buffer, size_t size);\n\n  void debugPrintIndex(uint8_t index, const char *value = NULL);\n  void debugPrintMessage(uint8_t type, uint8_t index, const char *value = NULL);\n\n  void autoBaud();\n  void configureEU868();\n  void configureUS915(uint8_t fsb);\n  void configureAU915(uint8_t fsb);\n  void configureAS920_923();\n  void configureAS923_925();\n  void configureKR920_923();\n  void configureIN865_867();\n  void configureChannels(uint8_t fsb);\n  bool setSF(uint8_t sf);\n  bool waitForOk();\n\n  ttn_response_t parseBytes();\n  void sendCommand(uint8_t table, uint8_t index, bool appendSpace, bool print = true);\n  bool sendMacSet(uint8_t index, uint8_t value1, unsigned long value2);\n  bool sendMacSet(uint8_t index, const char *value);\n  bool sendChSet(uint8_t index, uint8_t channel, unsigned long value);\n  bool sendChSet(uint8_t index, uint8_t channel, const char *value);\n  bool sendJoinSet(uint8_t type);\n  bool sendPayload(uint8_t mode, uint8_t port, uint8_t *payload, size_t len);\n  void sendGetValue(uint8_t table, uint8_t prefix, uint8_t index);\n\npublic:\n  bool needsHardReset = false;\n\n  TheThingsNetwork(Stream &modemStream, Stream &debugStream, ttn_fp_t fp, uint8_t sf = TTN_DEFAULT_SF, uint8_t fsb = TTN_DEFAULT_FSB);\n  void reset(bool adr = true);\n  void resetHard(uint8_t resetPin);\n  void showStatus();\n  size_t getHardwareEui(char *buffer, size_t size);\n  size_t getAppEui(char *buffer, size_t size);\n  size_t getVersion(char *buffer, size_t size);\n  enum ttn_modem_status_t getStatus();\n  uint16_t getVDD();\n  int16_t getRSSI();\n  uint32_t getFrequency();\n  uint32_t getWatchDogTimer();\n  uint32_t getFCU();\n  uint32_t getFCD();\n  uint8_t getBW();\n  uint8_t getCR();\n  int8_t getPower();\n  int8_t getSNR();\n  int8_t getDR();\n  int8_t getPowerIndex();\n  bool getChannelStatus (uint8_t channel);\n  ttn_response_code_t getLastError();\n  void onMessage(void (*cb)(const uint8_t *payload, size_t size, port_t port));\n  bool provision(const char *appEui, const char *appKey, bool resetFirst = true);\n  bool join(const char *appEui, const char *appKey, int8_t retries = -1, uint32_t retryDelay = 10000, lorawan_class_t = CLASS_A);\n  bool join(int8_t retries = -1, uint32_t retryDelay = 10000);\n  bool personalize(const char *devAddr, const char *nwkSKey, const char *appSKey, bool resetFirst = true);\n  bool personalize();\n  bool setClass(lorawan_class_t p_lw_class);\n  ttn_response_t sendBytes(const uint8_t *payload, size_t length, port_t port = 1, bool confirm = false, uint8_t sf = 0);\n  ttn_response_t poll(port_t port = 1, bool confirm = false, bool modem_only = false);\n  void sleep(uint32_t mseconds);\n  void wake();\n  void saveState();\n  void linkCheck(uint16_t seconds);\n  uint8_t getLinkCheckGateways();\n  uint8_t getLinkCheckMargin();\n  bool setChannel(uint8_t channel, uint32_t frequency = 0l, uint8_t dr_min = 255, uint8_t dr_max = 255);\n  bool setRx2Channel(uint32_t frequency, uint8_t dr);\n  bool setChannelDCycle (uint8_t channel, float duty_cycle);\n  bool setChannelStatus (uint8_t channel, bool status);\n  bool setPowerIndex(uint8_t index);\n  bool setDR(uint8_t dr);\n  bool setADR(bool adr);\n  bool setRX1Delay(uint16_t delay);\n  bool setFCU(uint32_t fcu);\n  bool setFCD(uint32_t fcd);\n  bool checkValidModuleConnected(bool autoBaudFirst = false);\n};\n\n#endif\n"
  },
  {
    "path": "src/api/appData.proto",
    "content": "syntax = \"proto2\";\n\npackage api;\n\nmessage AppData {\n        optional bool light = 1;\n        optional bool activate = 2;\n}\n"
  },
  {
    "path": "src/api/deviceData.proto",
    "content": "syntax = \"proto2\";\n\npackage api;\n\nmessage Location {\n        optional float longitude = 1;\n        optional float latitude = 2;\n        optional int32 altitude = 3;\n}\n\nmessage DeviceData {\n        optional bool motion = 1;\n        optional uint32 water = 2;\n        optional float temperature_celcius = 3;\n        optional float temperature_fahrenheit = 4;\n        optional float humidity = 5;\n\n        optional Location location = 6;\n        optional float level = 7;\n        optional bool triggered = 8;\n        optional bool actuator_active = 9;\n        optional float actuator_time = 10;\n\n        repeated uint32 analog_readings = 110;\n}\n"
  },
  {
    "path": "src/appData.pb.c",
    "content": "/* Automatically generated nanopb constant definitions */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n#include \"appData.pb.h\"\n\n/* @@protoc_insertion_point(includes) */\n#if PB_PROTO_HEADER_VERSION != 30\n#error Regenerate this file with the current version of nanopb generator.\n#endif\n\n\n\nconst pb_field_t api_AppData_fields[3] = {\n    PB_FIELD(  1, BOOL    , OPTIONAL, STATIC  , FIRST, api_AppData, light, light, 0),\n    PB_FIELD(  2, BOOL    , OPTIONAL, STATIC  , OTHER, api_AppData, activate, light, 0),\n    PB_LAST_FIELD\n};\n\n\n/* @@protoc_insertion_point(eof) */\n"
  },
  {
    "path": "src/appData.pb.h",
    "content": "/* Automatically generated nanopb header */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n#ifndef PB_API_APPDATA_PB_H_INCLUDED\n#define PB_API_APPDATA_PB_H_INCLUDED\n#include \"pb.h\"\n\n/* @@protoc_insertion_point(includes) */\n#if PB_PROTO_HEADER_VERSION != 30\n#error Regenerate this file with the current version of nanopb generator.\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Struct definitions */\ntypedef struct _api_AppData {\n    bool has_light;\n    bool light;\n    bool has_activate;\n    bool activate;\n/* @@protoc_insertion_point(struct:api_AppData) */\n} api_AppData;\n\n/* Default values for struct fields */\n\n/* Initializer values for message structs */\n#define api_AppData_init_default                 {false, 0, false, 0}\n#define api_AppData_init_zero                    {false, 0, false, 0}\n\n/* Field tags (for use in manual encoding/decoding) */\n#define api_AppData_light_tag                    1\n#define api_AppData_activate_tag                 2\n\n/* Struct field encoding specification for nanopb */\nextern const pb_field_t api_AppData_fields[3];\n\n/* Maximum encoded size of messages (where known) */\n#define api_AppData_size                         4\n\n/* Message IDs (where set with \"msgid\" option) */\n#ifdef PB_MSGID\n\n#define APPDATA_MESSAGES \\\n\n\n#endif\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n/* @@protoc_insertion_point(eof) */\n\n#endif\n"
  },
  {
    "path": "src/deviceData.pb.c",
    "content": "/* Automatically generated nanopb constant definitions */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n#include \"deviceData.pb.h\"\n\n/* @@protoc_insertion_point(includes) */\n#if PB_PROTO_HEADER_VERSION != 30\n#error Regenerate this file with the current version of nanopb generator.\n#endif\n\n\n\nconst pb_field_t api_Location_fields[4] = {\n    PB_FIELD(  1, FLOAT   , OPTIONAL, STATIC  , FIRST, api_Location, longitude, longitude, 0),\n    PB_FIELD(  2, FLOAT   , OPTIONAL, STATIC  , OTHER, api_Location, latitude, longitude, 0),\n    PB_FIELD(  3, INT32   , OPTIONAL, STATIC  , OTHER, api_Location, altitude, latitude, 0),\n    PB_LAST_FIELD\n};\n\nconst pb_field_t api_DeviceData_fields[12] = {\n    PB_FIELD(  1, BOOL    , OPTIONAL, STATIC  , FIRST, api_DeviceData, motion, motion, 0),\n    PB_FIELD(  2, UINT32  , OPTIONAL, STATIC  , OTHER, api_DeviceData, water, motion, 0),\n    PB_FIELD(  3, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, temperature_celcius, water, 0),\n    PB_FIELD(  4, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, temperature_fahrenheit, temperature_celcius, 0),\n    PB_FIELD(  5, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, humidity, temperature_fahrenheit, 0),\n    PB_FIELD(  6, MESSAGE , OPTIONAL, STATIC  , OTHER, api_DeviceData, location, humidity, &api_Location_fields),\n    PB_FIELD(  7, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, level, location, 0),\n    PB_FIELD(  8, BOOL    , OPTIONAL, STATIC  , OTHER, api_DeviceData, triggered, level, 0),\n    PB_FIELD(  9, BOOL    , OPTIONAL, STATIC  , OTHER, api_DeviceData, actuator_active, triggered, 0),\n    PB_FIELD( 10, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, actuator_time, actuator_active, 0),\n    PB_FIELD(110, UINT32  , REPEATED, CALLBACK, OTHER, api_DeviceData, analog_readings, actuator_time, 0),\n    PB_LAST_FIELD\n};\n\n\n/* Check that field information fits in pb_field_t */\n#if !defined(PB_FIELD_32BIT)\n/* If you get an error here, it means that you need to define PB_FIELD_32BIT\n * compile-time option. You can do that in pb.h or on compiler command line.\n * \n * The reason you need to do this is that some of your messages contain tag\n * numbers or field sizes that are larger than what can fit in 8 or 16 bit\n * field descriptors.\n */\nPB_STATIC_ASSERT((pb_membersize(api_DeviceData, location) < 65536), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_api_Location_api_DeviceData)\n#endif\n\n#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)\n/* If you get an error here, it means that you need to define PB_FIELD_16BIT\n * compile-time option. You can do that in pb.h or on compiler command line.\n * \n * The reason you need to do this is that some of your messages contain tag\n * numbers or field sizes that are larger than what can fit in the default\n * 8 bit descriptors.\n */\nPB_STATIC_ASSERT((pb_membersize(api_DeviceData, location) < 256), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_api_Location_api_DeviceData)\n#endif\n\n\n/* @@protoc_insertion_point(eof) */\n"
  },
  {
    "path": "src/deviceData.pb.h",
    "content": "/* Automatically generated nanopb header */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n#ifndef PB_API_DEVICEDATA_PB_H_INCLUDED\n#define PB_API_DEVICEDATA_PB_H_INCLUDED\n#include \"pb.h\"\n\n/* @@protoc_insertion_point(includes) */\n#if PB_PROTO_HEADER_VERSION != 30\n#error Regenerate this file with the current version of nanopb generator.\n#endif\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Struct definitions */\ntypedef struct _api_Location {\n    bool has_longitude;\n    float longitude;\n    bool has_latitude;\n    float latitude;\n    bool has_altitude;\n    int32_t altitude;\n/* @@protoc_insertion_point(struct:api_Location) */\n} api_Location;\n\ntypedef struct _api_DeviceData {\n    bool has_motion;\n    bool motion;\n    bool has_water;\n    uint32_t water;\n    bool has_temperature_celcius;\n    float temperature_celcius;\n    bool has_temperature_fahrenheit;\n    float temperature_fahrenheit;\n    bool has_humidity;\n    float humidity;\n    bool has_location;\n    api_Location location;\n    bool has_level;\n    float level;\n    bool has_triggered;\n    bool triggered;\n    bool has_actuator_active;\n    bool actuator_active;\n    bool has_actuator_time;\n    float actuator_time;\n    pb_callback_t analog_readings;\n/* @@protoc_insertion_point(struct:api_DeviceData) */\n} api_DeviceData;\n\n/* Default values for struct fields */\n\n/* Initializer values for message structs */\n#define api_Location_init_default                {false, 0, false, 0, false, 0}\n#define api_DeviceData_init_default              {false, 0, false, 0, false, 0, false, 0, false, 0, false, api_Location_init_default, false, 0, false, 0, false, 0, false, 0, {{NULL}, NULL}}\n#define api_Location_init_zero                   {false, 0, false, 0, false, 0}\n#define api_DeviceData_init_zero                 {false, 0, false, 0, false, 0, false, 0, false, 0, false, api_Location_init_zero, false, 0, false, 0, false, 0, false, 0, {{NULL}, NULL}}\n\n/* Field tags (for use in manual encoding/decoding) */\n#define api_Location_longitude_tag               1\n#define api_Location_latitude_tag                2\n#define api_Location_altitude_tag                3\n#define api_DeviceData_motion_tag                1\n#define api_DeviceData_water_tag                 2\n#define api_DeviceData_temperature_celcius_tag   3\n#define api_DeviceData_temperature_fahrenheit_tag 4\n#define api_DeviceData_humidity_tag              5\n#define api_DeviceData_location_tag              6\n#define api_DeviceData_level_tag                 7\n#define api_DeviceData_triggered_tag             8\n#define api_DeviceData_actuator_active_tag       9\n#define api_DeviceData_actuator_time_tag         10\n#define api_DeviceData_analog_readings_tag       110\n\n/* Struct field encoding specification for nanopb */\nextern const pb_field_t api_Location_fields[4];\nextern const pb_field_t api_DeviceData_fields[12];\n\n/* Maximum encoded size of messages (where known) */\n#define api_Location_size                        21\n/* api_DeviceData_size depends on runtime parameters */\n\n/* Message IDs (where set with \"msgid\" option) */\n#ifdef PB_MSGID\n\n#define DEVICEDATA_MESSAGES \\\n\n\n#endif\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n/* @@protoc_insertion_point(eof) */\n\n#endif\n"
  },
  {
    "path": "src/pb.h",
    "content": "/* Common parts of the nanopb library. Most of these are quite low-level\n * stuff. For the high-level interface, see pb_encode.h and pb_decode.h.\n */\n\n#ifndef PB_H_INCLUDED\n#define PB_H_INCLUDED\n\n/*****************************************************************\n * Nanopb compilation time options. You can change these here by *\n * uncommenting the lines, or on the compiler command line.      *\n *****************************************************************/\n\n/* Enable support for dynamically allocated fields */\n/* #define PB_ENABLE_MALLOC 1 */\n\n/* Define this if your CPU / compiler combination does not support\n * unaligned memory access to packed structures. */\n/* #define PB_NO_PACKED_STRUCTS 1 */\n\n/* Increase the number of required fields that are tracked.\n * A compiler warning will tell if you need this. */\n/* #define PB_MAX_REQUIRED_FIELDS 256 */\n\n/* Add support for tag numbers > 255 and fields larger than 255 bytes. */\n/* #define PB_FIELD_16BIT 1 */\n\n/* Add support for tag numbers > 65536 and fields larger than 65536 bytes. */\n/* #define PB_FIELD_32BIT 1 */\n\n/* Disable support for error messages in order to save some code space. */\n/* #define PB_NO_ERRMSG 1 */\n\n/* Disable support for custom streams (support only memory buffers). */\n/* #define PB_BUFFER_ONLY 1 */\n\n/* Switch back to the old-style callback function signature.\n * This was the default until nanopb-0.2.1. */\n/* #define PB_OLD_CALLBACK_STYLE */\n\n\n/******************************************************************\n * You usually don't need to change anything below this line.     *\n * Feel free to look around and use the defined macros, though.   *\n ******************************************************************/\n\n\n/* Version of the nanopb library. Just in case you want to check it in\n * your own program. */\n#define NANOPB_VERSION nanopb-0.3.6\n\n/* Include all the system headers needed by nanopb. You will need the\n * definitions of the following:\n * - strlen, memcpy, memset functions\n * - [u]int_least8_t, uint_fast8_t, [u]int_least16_t, [u]int32_t, [u]int64_t\n * - size_t\n * - bool\n *\n * If you don't have the standard header files, you can instead provide\n * a custom header that defines or includes all this. In that case,\n * define PB_SYSTEM_HEADER to the path of this file.\n */\n#ifdef PB_SYSTEM_HEADER\n#include PB_SYSTEM_HEADER\n#else\n#include <stdint.h>\n#include <stddef.h>\n#include <stdbool.h>\n#include <string.h>\n\n#ifdef PB_ENABLE_MALLOC\n#include <stdlib.h>\n#endif\n#endif\n\n/* Macro for defining packed structures (compiler dependent).\n * This just reduces memory requirements, but is not required.\n */\n#if defined(PB_NO_PACKED_STRUCTS)\n    /* Disable struct packing */\n#   define PB_PACKED_STRUCT_START\n#   define PB_PACKED_STRUCT_END\n#   define pb_packed\n#elif defined(__GNUC__) || defined(__clang__)\n    /* For GCC and clang */\n#   define PB_PACKED_STRUCT_START\n#   define PB_PACKED_STRUCT_END\n#   define pb_packed __attribute__((packed))\n#elif defined(__ICCARM__) || defined(__CC_ARM)\n    /* For IAR ARM and Keil MDK-ARM compilers */\n#   define PB_PACKED_STRUCT_START _Pragma(\"pack(push, 1)\")\n#   define PB_PACKED_STRUCT_END _Pragma(\"pack(pop)\")\n#   define pb_packed\n#elif defined(_MSC_VER) && (_MSC_VER >= 1500)\n    /* For Microsoft Visual C++ */\n#   define PB_PACKED_STRUCT_START __pragma(pack(push, 1))\n#   define PB_PACKED_STRUCT_END __pragma(pack(pop))\n#   define pb_packed\n#else\n    /* Unknown compiler */\n#   define PB_PACKED_STRUCT_START\n#   define PB_PACKED_STRUCT_END\n#   define pb_packed\n#endif\n\n/* Handly macro for suppressing unreferenced-parameter compiler warnings. */\n#ifndef PB_UNUSED\n#define PB_UNUSED(x) (void)(x)\n#endif\n\n/* Compile-time assertion, used for checking compatible compilation options.\n * If this does not work properly on your compiler, use\n * #define PB_NO_STATIC_ASSERT to disable it.\n *\n * But before doing that, check carefully the error message / place where it\n * comes from to see if the error has a real cause. Unfortunately the error\n * message is not always very clear to read, but you can see the reason better\n * in the place where the PB_STATIC_ASSERT macro was called.\n */\n#ifndef PB_NO_STATIC_ASSERT\n#ifndef PB_STATIC_ASSERT\n#define PB_STATIC_ASSERT(COND,MSG) typedef char PB_STATIC_ASSERT_MSG(MSG, __LINE__, __COUNTER__)[(COND)?1:-1];\n#define PB_STATIC_ASSERT_MSG(MSG, LINE, COUNTER) PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER)\n#define PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER) pb_static_assertion_##MSG##LINE##COUNTER\n#endif\n#else\n#define PB_STATIC_ASSERT(COND,MSG)\n#endif\n\n/* Number of required fields to keep track of. */\n#ifndef PB_MAX_REQUIRED_FIELDS\n#define PB_MAX_REQUIRED_FIELDS 64\n#endif\n\n#if PB_MAX_REQUIRED_FIELDS < 64\n#error You should not lower PB_MAX_REQUIRED_FIELDS from the default value (64).\n#endif\n\n/* List of possible field types. These are used in the autogenerated code.\n * Least-significant 4 bits tell the scalar type\n * Most-significant 4 bits specify repeated/required/packed etc.\n */\n\ntypedef uint_least8_t pb_type_t;\n\n/**** Field data types ****/\n\n/* Numeric types */\n#define PB_LTYPE_VARINT  0x00 /* int32, int64, enum, bool */\n#define PB_LTYPE_UVARINT 0x01 /* uint32, uint64 */\n#define PB_LTYPE_SVARINT 0x02 /* sint32, sint64 */\n#define PB_LTYPE_FIXED32 0x03 /* fixed32, sfixed32, float */\n#define PB_LTYPE_FIXED64 0x04 /* fixed64, sfixed64, double */\n\n/* Marker for last packable field type. */\n#define PB_LTYPE_LAST_PACKABLE 0x04\n\n/* Byte array with pre-allocated buffer.\n * data_size is the length of the allocated PB_BYTES_ARRAY structure. */\n#define PB_LTYPE_BYTES 0x05\n\n/* String with pre-allocated buffer.\n * data_size is the maximum length. */\n#define PB_LTYPE_STRING 0x06\n\n/* Submessage\n * submsg_fields is pointer to field descriptions */\n#define PB_LTYPE_SUBMESSAGE 0x07\n\n/* Extension pseudo-field\n * The field contains a pointer to pb_extension_t */\n#define PB_LTYPE_EXTENSION 0x08\n\n/* Number of declared LTYPES */\n#define PB_LTYPES_COUNT 9\n#define PB_LTYPE_MASK 0x0F\n\n/**** Field repetition rules ****/\n\n#define PB_HTYPE_REQUIRED 0x00\n#define PB_HTYPE_OPTIONAL 0x10\n#define PB_HTYPE_REPEATED 0x20\n#define PB_HTYPE_ONEOF    0x30\n#define PB_HTYPE_MASK     0x30\n\n/**** Field allocation types ****/\n \n#define PB_ATYPE_STATIC   0x00\n#define PB_ATYPE_POINTER  0x80\n#define PB_ATYPE_CALLBACK 0x40\n#define PB_ATYPE_MASK     0xC0\n\n#define PB_ATYPE(x) ((x) & PB_ATYPE_MASK)\n#define PB_HTYPE(x) ((x) & PB_HTYPE_MASK)\n#define PB_LTYPE(x) ((x) & PB_LTYPE_MASK)\n\n/* Data type used for storing sizes of struct fields\n * and array counts.\n */\n#if defined(PB_FIELD_32BIT)\n    typedef uint32_t pb_size_t;\n    typedef int32_t pb_ssize_t;\n#elif defined(PB_FIELD_16BIT)\n    typedef uint_least16_t pb_size_t;\n    typedef int_least16_t pb_ssize_t;\n#else\n    typedef uint_least8_t pb_size_t;\n    typedef int_least8_t pb_ssize_t;\n#endif\n#define PB_SIZE_MAX ((pb_size_t)-1)\n\n/* Data type for storing encoded data and other byte streams.\n * This typedef exists to support platforms where uint8_t does not exist.\n * You can regard it as equivalent on uint8_t on other platforms.\n */\ntypedef uint_least8_t pb_byte_t;\n\n/* This structure is used in auto-generated constants\n * to specify struct fields.\n * You can change field sizes if you need structures\n * larger than 256 bytes or field tags larger than 256.\n * The compiler should complain if your .proto has such\n * structures. Fix that by defining PB_FIELD_16BIT or\n * PB_FIELD_32BIT.\n */\nPB_PACKED_STRUCT_START\ntypedef struct pb_field_s pb_field_t;\nstruct pb_field_s {\n    pb_size_t tag;\n    pb_type_t type;\n    pb_size_t data_offset; /* Offset of field data, relative to previous field. */\n    pb_ssize_t size_offset; /* Offset of array size or has-boolean, relative to data */\n    pb_size_t data_size; /* Data size in bytes for a single item */\n    pb_size_t array_size; /* Maximum number of entries in array */\n    \n    /* Field definitions for submessage\n     * OR default value for all other non-array, non-callback types\n     * If null, then field will zeroed. */\n    const void *ptr;\n} pb_packed;\nPB_PACKED_STRUCT_END\n\n/* Make sure that the standard integer types are of the expected sizes.\n * Otherwise fixed32/fixed64 fields can break.\n *\n * If you get errors here, it probably means that your stdint.h is not\n * correct for your platform.\n */\nPB_STATIC_ASSERT(sizeof(int64_t) == 2 * sizeof(int32_t), INT64_T_WRONG_SIZE)\nPB_STATIC_ASSERT(sizeof(uint64_t) == 2 * sizeof(uint32_t), UINT64_T_WRONG_SIZE)\n\n/* This structure is used for 'bytes' arrays.\n * It has the number of bytes in the beginning, and after that an array.\n * Note that actual structs used will have a different length of bytes array.\n */\n#define PB_BYTES_ARRAY_T(n) struct { pb_size_t size; pb_byte_t bytes[n]; }\n#define PB_BYTES_ARRAY_T_ALLOCSIZE(n) ((size_t)n + offsetof(pb_bytes_array_t, bytes))\n\nstruct pb_bytes_array_s {\n    pb_size_t size;\n    pb_byte_t bytes[1];\n};\ntypedef struct pb_bytes_array_s pb_bytes_array_t;\n\n/* This structure is used for giving the callback function.\n * It is stored in the message structure and filled in by the method that\n * calls pb_decode.\n *\n * The decoding callback will be given a limited-length stream\n * If the wire type was string, the length is the length of the string.\n * If the wire type was a varint/fixed32/fixed64, the length is the length\n * of the actual value.\n * The function may be called multiple times (especially for repeated types,\n * but also otherwise if the message happens to contain the field multiple\n * times.)\n *\n * The encoding callback will receive the actual output stream.\n * It should write all the data in one call, including the field tag and\n * wire type. It can write multiple fields.\n *\n * The callback can be null if you want to skip a field.\n */\ntypedef struct pb_istream_s pb_istream_t;\ntypedef struct pb_ostream_s pb_ostream_t;\ntypedef struct pb_callback_s pb_callback_t;\nstruct pb_callback_s {\n#ifdef PB_OLD_CALLBACK_STYLE\n    /* Deprecated since nanopb-0.2.1 */\n    union {\n        bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg);\n        bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg);\n    } funcs;\n#else\n    /* New function signature, which allows modifying arg contents in callback. */\n    union {\n        bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg);\n        bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);\n    } funcs;\n#endif    \n    \n    /* Free arg for use by callback */\n    void *arg;\n};\n\n/* Wire types. Library user needs these only in encoder callbacks. */\ntypedef enum {\n    PB_WT_VARINT = 0,\n    PB_WT_64BIT  = 1,\n    PB_WT_STRING = 2,\n    PB_WT_32BIT  = 5\n} pb_wire_type_t;\n\n/* Structure for defining the handling of unknown/extension fields.\n * Usually the pb_extension_type_t structure is automatically generated,\n * while the pb_extension_t structure is created by the user. However,\n * if you want to catch all unknown fields, you can also create a custom\n * pb_extension_type_t with your own callback.\n */\ntypedef struct pb_extension_type_s pb_extension_type_t;\ntypedef struct pb_extension_s pb_extension_t;\nstruct pb_extension_type_s {\n    /* Called for each unknown field in the message.\n     * If you handle the field, read off all of its data and return true.\n     * If you do not handle the field, do not read anything and return true.\n     * If you run into an error, return false.\n     * Set to NULL for default handler.\n     */\n    bool (*decode)(pb_istream_t *stream, pb_extension_t *extension,\n                   uint32_t tag, pb_wire_type_t wire_type);\n    \n    /* Called once after all regular fields have been encoded.\n     * If you have something to write, do so and return true.\n     * If you do not have anything to write, just return true.\n     * If you run into an error, return false.\n     * Set to NULL for default handler.\n     */\n    bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension);\n    \n    /* Free field for use by the callback. */\n    const void *arg;\n};\n\nstruct pb_extension_s {\n    /* Type describing the extension field. Usually you'll initialize\n     * this to a pointer to the automatically generated structure. */\n    const pb_extension_type_t *type;\n    \n    /* Destination for the decoded data. This must match the datatype\n     * of the extension field. */\n    void *dest;\n    \n    /* Pointer to the next extension handler, or NULL.\n     * If this extension does not match a field, the next handler is\n     * automatically called. */\n    pb_extension_t *next;\n\n    /* The decoder sets this to true if the extension was found.\n     * Ignored for encoding. */\n    bool found;\n};\n\n/* Memory allocation functions to use. You can define pb_realloc and\n * pb_free to custom functions if you want. */\n#ifdef PB_ENABLE_MALLOC\n#   ifndef pb_realloc\n#       define pb_realloc(ptr, size) realloc(ptr, size)\n#   endif\n#   ifndef pb_free\n#       define pb_free(ptr) free(ptr)\n#   endif\n#endif\n\n/* This is used to inform about need to regenerate .pb.h/.pb.c files. */\n#define PB_PROTO_HEADER_VERSION 30\n\n/* These macros are used to declare pb_field_t's in the constant array. */\n/* Size of a structure member, in bytes. */\n#define pb_membersize(st, m) (sizeof ((st*)0)->m)\n/* Number of entries in an array. */\n#define pb_arraysize(st, m) (pb_membersize(st, m) / pb_membersize(st, m[0]))\n/* Delta from start of one member to the start of another member. */\n#define pb_delta(st, m1, m2) ((int)offsetof(st, m1) - (int)offsetof(st, m2))\n/* Marks the end of the field list */\n#define PB_LAST_FIELD {0,(pb_type_t) 0,0,0,0,0,0}\n\n/* Macros for filling in the data_offset field */\n/* data_offset for first field in a message */\n#define PB_DATAOFFSET_FIRST(st, m1, m2) (offsetof(st, m1))\n/* data_offset for subsequent fields */\n#define PB_DATAOFFSET_OTHER(st, m1, m2) (offsetof(st, m1) - offsetof(st, m2) - pb_membersize(st, m2))\n/* Choose first/other based on m1 == m2 (deprecated, remains for backwards compatibility) */\n#define PB_DATAOFFSET_CHOOSE(st, m1, m2) (int)(offsetof(st, m1) == offsetof(st, m2) \\\n                                  ? PB_DATAOFFSET_FIRST(st, m1, m2) \\\n                                  : PB_DATAOFFSET_OTHER(st, m1, m2))\n\n/* Required fields are the simplest. They just have delta (padding) from\n * previous field end, and the size of the field. Pointer is used for\n * submessages and default values.\n */\n#define PB_REQUIRED_STATIC(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_STATIC | PB_HTYPE_REQUIRED | ltype, \\\n    fd, 0, pb_membersize(st, m), 0, ptr}\n\n/* Optional fields add the delta to the has_ variable. */\n#define PB_OPTIONAL_STATIC(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \\\n    fd, \\\n    pb_delta(st, has_ ## m, m), \\\n    pb_membersize(st, m), 0, ptr}\n\n/* Repeated fields have a _count field and also the maximum number of entries. */\n#define PB_REPEATED_STATIC(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_STATIC | PB_HTYPE_REPEATED | ltype, \\\n    fd, \\\n    pb_delta(st, m ## _count, m), \\\n    pb_membersize(st, m[0]), \\\n    pb_arraysize(st, m), ptr}\n\n/* Allocated fields carry the size of the actual data, not the pointer */\n#define PB_REQUIRED_POINTER(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_POINTER | PB_HTYPE_REQUIRED | ltype, \\\n    fd, 0, pb_membersize(st, m[0]), 0, ptr}\n\n/* Optional fields don't need a has_ variable, as information would be redundant */\n#define PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_POINTER | PB_HTYPE_OPTIONAL | ltype, \\\n    fd, 0, pb_membersize(st, m[0]), 0, ptr}\n\n/* Repeated fields have a _count field and a pointer to array of pointers */\n#define PB_REPEATED_POINTER(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_POINTER | PB_HTYPE_REPEATED | ltype, \\\n    fd, pb_delta(st, m ## _count, m), \\\n    pb_membersize(st, m[0]), 0, ptr}\n\n/* Callbacks are much like required fields except with special datatype. */\n#define PB_REQUIRED_CALLBACK(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REQUIRED | ltype, \\\n    fd, 0, pb_membersize(st, m), 0, ptr}\n\n#define PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_CALLBACK | PB_HTYPE_OPTIONAL | ltype, \\\n    fd, 0, pb_membersize(st, m), 0, ptr}\n    \n#define PB_REPEATED_CALLBACK(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REPEATED | ltype, \\\n    fd, 0, pb_membersize(st, m), 0, ptr}\n\n/* Optional extensions don't have the has_ field, as that would be redundant. */\n#define PB_OPTEXT_STATIC(tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \\\n    0, \\\n    0, \\\n    pb_membersize(st, m), 0, ptr}\n\n#define PB_OPTEXT_POINTER(tag, st, m, fd, ltype, ptr) \\\n    PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr)\n\n#define PB_OPTEXT_CALLBACK(tag, st, m, fd, ltype, ptr) \\\n    PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr)\n\n/* The mapping from protobuf types to LTYPEs is done using these macros. */\n#define PB_LTYPE_MAP_BOOL       PB_LTYPE_VARINT\n#define PB_LTYPE_MAP_BYTES      PB_LTYPE_BYTES\n#define PB_LTYPE_MAP_DOUBLE     PB_LTYPE_FIXED64\n#define PB_LTYPE_MAP_ENUM       PB_LTYPE_VARINT\n#define PB_LTYPE_MAP_UENUM      PB_LTYPE_UVARINT\n#define PB_LTYPE_MAP_FIXED32    PB_LTYPE_FIXED32\n#define PB_LTYPE_MAP_FIXED64    PB_LTYPE_FIXED64\n#define PB_LTYPE_MAP_FLOAT      PB_LTYPE_FIXED32\n#define PB_LTYPE_MAP_INT32      PB_LTYPE_VARINT\n#define PB_LTYPE_MAP_INT64      PB_LTYPE_VARINT\n#define PB_LTYPE_MAP_MESSAGE    PB_LTYPE_SUBMESSAGE\n#define PB_LTYPE_MAP_SFIXED32   PB_LTYPE_FIXED32\n#define PB_LTYPE_MAP_SFIXED64   PB_LTYPE_FIXED64\n#define PB_LTYPE_MAP_SINT32     PB_LTYPE_SVARINT\n#define PB_LTYPE_MAP_SINT64     PB_LTYPE_SVARINT\n#define PB_LTYPE_MAP_STRING     PB_LTYPE_STRING\n#define PB_LTYPE_MAP_UINT32     PB_LTYPE_UVARINT\n#define PB_LTYPE_MAP_UINT64     PB_LTYPE_UVARINT\n#define PB_LTYPE_MAP_EXTENSION  PB_LTYPE_EXTENSION\n\n/* This is the actual macro used in field descriptions.\n * It takes these arguments:\n * - Field tag number\n * - Field type:   BOOL, BYTES, DOUBLE, ENUM, UENUM, FIXED32, FIXED64,\n *                 FLOAT, INT32, INT64, MESSAGE, SFIXED32, SFIXED64\n *                 SINT32, SINT64, STRING, UINT32, UINT64 or EXTENSION\n * - Field rules:  REQUIRED, OPTIONAL or REPEATED\n * - Allocation:   STATIC or CALLBACK\n * - Placement: FIRST or OTHER, depending on if this is the first field in structure.\n * - Message name\n * - Field name\n * - Previous field name (or field name again for first field)\n * - Pointer to default value or submsg fields.\n */\n\n#define PB_FIELD(tag, type, rules, allocation, placement, message, field, prevfield, ptr) \\\n        PB_ ## rules ## _ ## allocation(tag, message, field, \\\n        PB_DATAOFFSET_ ## placement(message, field, prevfield), \\\n        PB_LTYPE_MAP_ ## type, ptr)\n\n/* Field description for oneof fields. This requires taking into account the\n * union name also, that's why a separate set of macros is needed.\n */\n#define PB_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \\\n    fd, pb_delta(st, which_ ## u, u.m), \\\n    pb_membersize(st, u.m), 0, ptr}\n\n#define PB_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \\\n    fd, pb_delta(st, which_ ## u, u.m), \\\n    pb_membersize(st, u.m[0]), 0, ptr}\n\n#define PB_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \\\n        PB_ONEOF_ ## allocation(union_name, tag, message, field, \\\n        PB_DATAOFFSET_ ## placement(message, union_name.field, prevfield), \\\n        PB_LTYPE_MAP_ ## type, ptr)\n\n#define PB_ANONYMOUS_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \\\n    fd, pb_delta(st, which_ ## u, m), \\\n    pb_membersize(st, m), 0, ptr}\n\n#define PB_ANONYMOUS_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \\\n    {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \\\n    fd, pb_delta(st, which_ ## u, m), \\\n    pb_membersize(st, m[0]), 0, ptr}\n\n#define PB_ANONYMOUS_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \\\n        PB_ANONYMOUS_ONEOF_ ## allocation(union_name, tag, message, field, \\\n        PB_DATAOFFSET_ ## placement(message, field, prevfield), \\\n        PB_LTYPE_MAP_ ## type, ptr)\n\n/* These macros are used for giving out error messages.\n * They are mostly a debugging aid; the main error information\n * is the true/false return value from functions.\n * Some code space can be saved by disabling the error\n * messages if not used.\n *\n * PB_SET_ERROR() sets the error message if none has been set yet.\n *                msg must be a constant string literal.\n * PB_GET_ERROR() always returns a pointer to a string.\n * PB_RETURN_ERROR() sets the error and returns false from current\n *                   function.\n */\n#ifdef PB_NO_ERRMSG\n#define PB_SET_ERROR(stream, msg) PB_UNUSED(stream)\n#define PB_GET_ERROR(stream) \"(errmsg disabled)\"\n#else\n#define PB_SET_ERROR(stream, msg) (stream->errmsg = (stream)->errmsg ? (stream)->errmsg : (msg))\n#define PB_GET_ERROR(stream) ((stream)->errmsg ? (stream)->errmsg : \"(none)\")\n#endif\n\n#define PB_RETURN_ERROR(stream, msg) return PB_SET_ERROR(stream, msg), false\n\n#endif\n"
  },
  {
    "path": "src/pb_common.c",
    "content": "/* pb_common.c: Common support functions for pb_encode.c and pb_decode.c.\n *\n * 2014 Petteri Aimonen <jpa@kapsi.fi>\n */\n\n#include \"pb_common.h\"\n\nbool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct)\n{\n    iter->start = fields;\n    iter->pos = fields;\n    iter->required_field_index = 0;\n    iter->dest_struct = dest_struct;\n    iter->pData = (char*)dest_struct + iter->pos->data_offset;\n    iter->pSize = (char*)iter->pData + iter->pos->size_offset;\n    \n    return (iter->pos->tag != 0);\n}\n\nbool pb_field_iter_next(pb_field_iter_t *iter)\n{\n    const pb_field_t *prev_field = iter->pos;\n\n    if (prev_field->tag == 0)\n    {\n        /* Handle empty message types, where the first field is already the terminator.\n         * In other cases, the iter->pos never points to the terminator. */\n        return false;\n    }\n    \n    iter->pos++;\n    \n    if (iter->pos->tag == 0)\n    {\n        /* Wrapped back to beginning, reinitialize */\n        (void)pb_field_iter_begin(iter, iter->start, iter->dest_struct);\n        return false;\n    }\n    else\n    {\n        /* Increment the pointers based on previous field size */\n        size_t prev_size = prev_field->data_size;\n    \n        if (PB_HTYPE(prev_field->type) == PB_HTYPE_ONEOF &&\n            PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)\n        {\n            /* Don't advance pointers inside unions */\n            prev_size = 0;\n            iter->pData = (char*)iter->pData - prev_field->data_offset;\n        }\n        else if (PB_ATYPE(prev_field->type) == PB_ATYPE_STATIC &&\n                 PB_HTYPE(prev_field->type) == PB_HTYPE_REPEATED)\n        {\n            /* In static arrays, the data_size tells the size of a single entry and\n             * array_size is the number of entries */\n            prev_size *= prev_field->array_size;\n        }\n        else if (PB_ATYPE(prev_field->type) == PB_ATYPE_POINTER)\n        {\n            /* Pointer fields always have a constant size in the main structure.\n             * The data_size only applies to the dynamically allocated area. */\n            prev_size = sizeof(void*);\n        }\n\n        if (PB_HTYPE(prev_field->type) == PB_HTYPE_REQUIRED)\n        {\n            /* Count the required fields, in order to check their presence in the\n             * decoder. */\n            iter->required_field_index++;\n        }\n    \n        iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset;\n        iter->pSize = (char*)iter->pData + iter->pos->size_offset;\n        return true;\n    }\n}\n\nbool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag)\n{\n    const pb_field_t *start = iter->pos;\n    \n    do {\n        if (iter->pos->tag == tag &&\n            PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION)\n        {\n            /* Found the wanted field */\n            return true;\n        }\n        \n        (void)pb_field_iter_next(iter);\n    } while (iter->pos != start);\n    \n    /* Searched all the way back to start, and found nothing. */\n    return false;\n}\n\n\n"
  },
  {
    "path": "src/pb_common.h",
    "content": "/* pb_common.h: Common support functions for pb_encode.c and pb_decode.c.\n * These functions are rarely needed by applications directly.\n */\n\n#ifndef PB_COMMON_H_INCLUDED\n#define PB_COMMON_H_INCLUDED\n\n#include \"pb.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Iterator for pb_field_t list */\nstruct pb_field_iter_s {\n    const pb_field_t *start;       /* Start of the pb_field_t array */\n    const pb_field_t *pos;         /* Current position of the iterator */\n    unsigned required_field_index; /* Zero-based index that counts only the required fields */\n    void *dest_struct;             /* Pointer to start of the structure */\n    void *pData;                   /* Pointer to current field value */\n    void *pSize;                   /* Pointer to count/has field */\n};\ntypedef struct pb_field_iter_s pb_field_iter_t;\n\n/* Initialize the field iterator structure to beginning.\n * Returns false if the message type is empty. */\nbool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct);\n\n/* Advance the iterator to the next field.\n * Returns false when the iterator wraps back to the first field. */\nbool pb_field_iter_next(pb_field_iter_t *iter);\n\n/* Advance the iterator until it points at a field with the given tag.\n * Returns false if no such field exists. */\nbool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif\n\n"
  },
  {
    "path": "src/pb_decode.c",
    "content": "/* pb_decode.c -- decode a protobuf using minimal resources\n *\n * 2011 Petteri Aimonen <jpa@kapsi.fi>\n */\n\n/* Use the GCC warn_unused_result attribute to check that all return values\n * are propagated correctly. On other compilers and gcc before 3.4.0 just\n * ignore the annotation.\n */\n#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)\n    #define checkreturn\n#else\n    #define checkreturn __attribute__((warn_unused_result))\n#endif\n\n#include \"pb.h\"\n#include \"pb_decode.h\"\n#include \"pb_common.h\"\n\n/**************************************\n * Declarations internal to this file *\n **************************************/\n\ntypedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;\n\nstatic bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);\nstatic bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest);\nstatic bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size);\nstatic bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);\nstatic bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);\nstatic bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);\nstatic void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension);\nstatic bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);\nstatic bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);\nstatic bool checkreturn find_extension_field(pb_field_iter_t *iter);\nstatic void pb_field_set_to_default(pb_field_iter_t *iter);\nstatic void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);\nstatic bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);\nstatic bool checkreturn pb_skip_varint(pb_istream_t *stream);\nstatic bool checkreturn pb_skip_string(pb_istream_t *stream);\n\n#ifdef PB_ENABLE_MALLOC\nstatic bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);\nstatic bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter);\nstatic void pb_release_single_field(const pb_field_iter_t *iter);\n#endif\n\n/* --- Function pointers to field decoders ---\n * Order in the array must match pb_action_t LTYPE numbering.\n */\nstatic const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {\n    &pb_dec_varint,\n    &pb_dec_uvarint,\n    &pb_dec_svarint,\n    &pb_dec_fixed32,\n    &pb_dec_fixed64,\n    \n    &pb_dec_bytes,\n    &pb_dec_string,\n    &pb_dec_submessage,\n    NULL /* extensions */\n};\n\n/*******************************\n * pb_istream_t implementation *\n *******************************/\n\nstatic bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)\n{\n    const pb_byte_t *source = (const pb_byte_t*)stream->state;\n    stream->state = (pb_byte_t*)stream->state + count;\n    \n    if (buf != NULL)\n    {\n        while (count--)\n            *buf++ = *source++;\n    }\n    \n    return true;\n}\n\nbool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)\n{\n#ifndef PB_BUFFER_ONLY\n\tif (buf == NULL && stream->callback != buf_read)\n\t{\n\t\t/* Skip input bytes */\n\t\tpb_byte_t tmp[16];\n\t\twhile (count > 16)\n\t\t{\n\t\t\tif (!pb_read(stream, tmp, 16))\n\t\t\t\treturn false;\n\t\t\t\n\t\t\tcount -= 16;\n\t\t}\n\t\t\n\t\treturn pb_read(stream, tmp, count);\n\t}\n#endif\n\n    if (stream->bytes_left < count)\n        PB_RETURN_ERROR(stream, \"end-of-stream\");\n    \n#ifndef PB_BUFFER_ONLY\n    if (!stream->callback(stream, buf, count))\n        PB_RETURN_ERROR(stream, \"io error\");\n#else\n    if (!buf_read(stream, buf, count))\n        return false;\n#endif\n    \n    stream->bytes_left -= count;\n    return true;\n}\n\n/* Read a single byte from input stream. buf may not be NULL.\n * This is an optimization for the varint decoding. */\nstatic bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf)\n{\n    if (stream->bytes_left == 0)\n        PB_RETURN_ERROR(stream, \"end-of-stream\");\n\n#ifndef PB_BUFFER_ONLY\n    if (!stream->callback(stream, buf, 1))\n        PB_RETURN_ERROR(stream, \"io error\");\n#else\n    *buf = *(const pb_byte_t*)stream->state;\n    stream->state = (pb_byte_t*)stream->state + 1;\n#endif\n\n    stream->bytes_left--;\n    \n    return true;    \n}\n\npb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize)\n{\n    pb_istream_t stream;\n    /* Cast away the const from buf without a compiler error.  We are\n     * careful to use it only in a const manner in the callbacks.\n     */\n    union {\n        void *state;\n        const void *c_state;\n    } state;\n#ifdef PB_BUFFER_ONLY\n    stream.callback = NULL;\n#else\n    stream.callback = &buf_read;\n#endif\n    state.c_state = buf;\n    stream.state = state.state;\n    stream.bytes_left = bufsize;\n#ifndef PB_NO_ERRMSG\n    stream.errmsg = NULL;\n#endif\n    return stream;\n}\n\n/********************\n * Helper functions *\n ********************/\n\nstatic bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)\n{\n    pb_byte_t byte;\n    uint32_t result;\n    \n    if (!pb_readbyte(stream, &byte))\n        return false;\n    \n    if ((byte & 0x80) == 0)\n    {\n        /* Quick case, 1 byte value */\n        result = byte;\n    }\n    else\n    {\n        /* Multibyte case */\n        uint_fast8_t bitpos = 7;\n        result = byte & 0x7F;\n        \n        do\n        {\n            if (bitpos >= 32)\n                PB_RETURN_ERROR(stream, \"varint overflow\");\n            \n            if (!pb_readbyte(stream, &byte))\n                return false;\n            \n            result |= (uint32_t)(byte & 0x7F) << bitpos;\n            bitpos = (uint_fast8_t)(bitpos + 7);\n        } while (byte & 0x80);\n   }\n   \n   *dest = result;\n   return true;\n}\n\nbool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)\n{\n    pb_byte_t byte;\n    uint_fast8_t bitpos = 0;\n    uint64_t result = 0;\n    \n    do\n    {\n        if (bitpos >= 64)\n            PB_RETURN_ERROR(stream, \"varint overflow\");\n        \n        if (!pb_readbyte(stream, &byte))\n            return false;\n\n        result |= (uint64_t)(byte & 0x7F) << bitpos;\n        bitpos = (uint_fast8_t)(bitpos + 7);\n    } while (byte & 0x80);\n    \n    *dest = result;\n    return true;\n}\n\nbool checkreturn pb_skip_varint(pb_istream_t *stream)\n{\n    pb_byte_t byte;\n    do\n    {\n        if (!pb_read(stream, &byte, 1))\n            return false;\n    } while (byte & 0x80);\n    return true;\n}\n\nbool checkreturn pb_skip_string(pb_istream_t *stream)\n{\n    uint32_t length;\n    if (!pb_decode_varint32(stream, &length))\n        return false;\n    \n    return pb_read(stream, NULL, length);\n}\n\nbool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)\n{\n    uint32_t temp;\n    *eof = false;\n    *wire_type = (pb_wire_type_t) 0;\n    *tag = 0;\n    \n    if (!pb_decode_varint32(stream, &temp))\n    {\n        if (stream->bytes_left == 0)\n            *eof = true;\n\n        return false;\n    }\n    \n    if (temp == 0)\n    {\n        *eof = true; /* Special feature: allow 0-terminated messages. */\n        return false;\n    }\n    \n    *tag = temp >> 3;\n    *wire_type = (pb_wire_type_t)(temp & 7);\n    return true;\n}\n\nbool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)\n{\n    switch (wire_type)\n    {\n        case PB_WT_VARINT: return pb_skip_varint(stream);\n        case PB_WT_64BIT: return pb_read(stream, NULL, 8);\n        case PB_WT_STRING: return pb_skip_string(stream);\n        case PB_WT_32BIT: return pb_read(stream, NULL, 4);\n        default: PB_RETURN_ERROR(stream, \"invalid wire_type\");\n    }\n}\n\n/* Read a raw value to buffer, for the purpose of passing it to callback as\n * a substream. Size is maximum size on call, and actual size on return.\n */\nstatic bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size)\n{\n    size_t max_size = *size;\n    switch (wire_type)\n    {\n        case PB_WT_VARINT:\n            *size = 0;\n            do\n            {\n                (*size)++;\n                if (*size > max_size) return false;\n                if (!pb_read(stream, buf, 1)) return false;\n            } while (*buf++ & 0x80);\n            return true;\n            \n        case PB_WT_64BIT:\n            *size = 8;\n            return pb_read(stream, buf, 8);\n        \n        case PB_WT_32BIT:\n            *size = 4;\n            return pb_read(stream, buf, 4);\n        \n        default: PB_RETURN_ERROR(stream, \"invalid wire_type\");\n    }\n}\n\n/* Decode string length from stream and return a substream with limited length.\n * Remember to close the substream using pb_close_string_substream().\n */\nbool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)\n{\n    uint32_t size;\n    if (!pb_decode_varint32(stream, &size))\n        return false;\n    \n    *substream = *stream;\n    if (substream->bytes_left < size)\n        PB_RETURN_ERROR(stream, \"parent stream too short\");\n    \n    substream->bytes_left = size;\n    stream->bytes_left -= size;\n    return true;\n}\n\nvoid pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)\n{\n    stream->state = substream->state;\n\n#ifndef PB_NO_ERRMSG\n    stream->errmsg = substream->errmsg;\n#endif\n}\n\n/*************************\n * Decode a single field *\n *************************/\n\nstatic bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n    pb_type_t type;\n    pb_decoder_t func;\n    \n    type = iter->pos->type;\n    func = PB_DECODERS[PB_LTYPE(type)];\n\n    switch (PB_HTYPE(type))\n    {\n        case PB_HTYPE_REQUIRED:\n            return func(stream, iter->pos, iter->pData);\n            \n        case PB_HTYPE_OPTIONAL:\n            *(bool*)iter->pSize = true;\n            return func(stream, iter->pos, iter->pData);\n    \n        case PB_HTYPE_REPEATED:\n            if (wire_type == PB_WT_STRING\n                && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n            {\n                /* Packed array */\n                bool status = true;\n                pb_size_t *size = (pb_size_t*)iter->pSize;\n                pb_istream_t substream;\n                if (!pb_make_string_substream(stream, &substream))\n                    return false;\n                \n                while (substream.bytes_left > 0 && *size < iter->pos->array_size)\n                {\n                    void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);\n                    if (!func(&substream, iter->pos, pItem))\n                    {\n                        status = false;\n                        break;\n                    }\n                    (*size)++;\n                }\n                pb_close_string_substream(stream, &substream);\n                \n                if (substream.bytes_left != 0)\n                    PB_RETURN_ERROR(stream, \"array overflow\");\n                \n                return status;\n            }\n            else\n            {\n                /* Repeated field */\n                pb_size_t *size = (pb_size_t*)iter->pSize;\n                void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);\n                if (*size >= iter->pos->array_size)\n                    PB_RETURN_ERROR(stream, \"array overflow\");\n                \n                (*size)++;\n                return func(stream, iter->pos, pItem);\n            }\n\n        case PB_HTYPE_ONEOF:\n            *(pb_size_t*)iter->pSize = iter->pos->tag;\n            if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)\n            {\n                /* We memset to zero so that any callbacks are set to NULL.\n                 * Then set any default values. */\n                memset(iter->pData, 0, iter->pos->data_size);\n                pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);\n            }\n            return func(stream, iter->pos, iter->pData);\n\n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n}\n\n#ifdef PB_ENABLE_MALLOC\n/* Allocate storage for the field and store the pointer at iter->pData.\n * array_size is the number of entries to reserve in an array.\n * Zero size is not allowed, use pb_free() for releasing.\n */\nstatic bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)\n{    \n    void *ptr = *(void**)pData;\n    \n    if (data_size == 0 || array_size == 0)\n        PB_RETURN_ERROR(stream, \"invalid size\");\n    \n    /* Check for multiplication overflows.\n     * This code avoids the costly division if the sizes are small enough.\n     * Multiplication is safe as long as only half of bits are set\n     * in either multiplicand.\n     */\n    {\n        const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);\n        if (data_size >= check_limit || array_size >= check_limit)\n        {\n            const size_t size_max = (size_t)-1;\n            if (size_max / array_size < data_size)\n            {\n                PB_RETURN_ERROR(stream, \"size too large\");\n            }\n        }\n    }\n    \n    /* Allocate new or expand previous allocation */\n    /* Note: on failure the old pointer will remain in the structure,\n     * the message must be freed by caller also on error return. */\n    ptr = pb_realloc(ptr, array_size * data_size);\n    if (ptr == NULL)\n        PB_RETURN_ERROR(stream, \"realloc failed\");\n    \n    *(void**)pData = ptr;\n    return true;\n}\n\n/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */\nstatic void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)\n{\n    if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||\n        PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)\n    {\n        *(void**)pItem = NULL;\n    }\n    else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)\n    {\n        pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);\n    }\n}\n#endif\n\nstatic bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n#ifndef PB_ENABLE_MALLOC\n    PB_UNUSED(wire_type);\n    PB_UNUSED(iter);\n    PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n    pb_type_t type;\n    pb_decoder_t func;\n    \n    type = iter->pos->type;\n    func = PB_DECODERS[PB_LTYPE(type)];\n    \n    switch (PB_HTYPE(type))\n    {\n        case PB_HTYPE_REQUIRED:\n        case PB_HTYPE_OPTIONAL:\n        case PB_HTYPE_ONEOF:\n            if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&\n                *(void**)iter->pData != NULL)\n            {\n                /* Duplicate field, have to release the old allocation first. */\n                pb_release_single_field(iter);\n            }\n        \n            if (PB_HTYPE(type) == PB_HTYPE_ONEOF)\n            {\n                *(pb_size_t*)iter->pSize = iter->pos->tag;\n            }\n\n            if (PB_LTYPE(type) == PB_LTYPE_STRING ||\n                PB_LTYPE(type) == PB_LTYPE_BYTES)\n            {\n                return func(stream, iter->pos, iter->pData);\n            }\n            else\n            {\n                if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))\n                    return false;\n                \n                initialize_pointer_field(*(void**)iter->pData, iter);\n                return func(stream, iter->pos, *(void**)iter->pData);\n            }\n    \n        case PB_HTYPE_REPEATED:\n            if (wire_type == PB_WT_STRING\n                && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)\n            {\n                /* Packed array, multiple items come in at once. */\n                bool status = true;\n                pb_size_t *size = (pb_size_t*)iter->pSize;\n                size_t allocated_size = *size;\n                void *pItem;\n                pb_istream_t substream;\n                \n                if (!pb_make_string_substream(stream, &substream))\n                    return false;\n                \n                while (substream.bytes_left)\n                {\n                    if ((size_t)*size + 1 > allocated_size)\n                    {\n                        /* Allocate more storage. This tries to guess the\n                         * number of remaining entries. Round the division\n                         * upwards. */\n                        allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;\n                        \n                        if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))\n                        {\n                            status = false;\n                            break;\n                        }\n                    }\n\n                    /* Decode the array entry */\n                    pItem = *(char**)iter->pData + iter->pos->data_size * (*size);\n                    initialize_pointer_field(pItem, iter);\n                    if (!func(&substream, iter->pos, pItem))\n                    {\n                        status = false;\n                        break;\n                    }\n                    \n                    if (*size == PB_SIZE_MAX)\n                    {\n#ifndef PB_NO_ERRMSG\n                        stream->errmsg = \"too many array entries\";\n#endif\n                        status = false;\n                        break;\n                    }\n                    \n                    (*size)++;\n                }\n                pb_close_string_substream(stream, &substream);\n                \n                return status;\n            }\n            else\n            {\n                /* Normal repeated field, i.e. only one item at a time. */\n                pb_size_t *size = (pb_size_t*)iter->pSize;\n                void *pItem;\n                \n                if (*size == PB_SIZE_MAX)\n                    PB_RETURN_ERROR(stream, \"too many array entries\");\n                \n                (*size)++;\n                if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))\n                    return false;\n            \n                pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1);\n                initialize_pointer_field(pItem, iter);\n                return func(stream, iter->pos, pItem);\n            }\n\n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n#endif\n}\n\nstatic bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n    pb_callback_t *pCallback = (pb_callback_t*)iter->pData;\n    \n#ifdef PB_OLD_CALLBACK_STYLE\n    void *arg = pCallback->arg;\n#else\n    void **arg = &(pCallback->arg);\n#endif\n    \n    if (pCallback->funcs.decode == NULL)\n        return pb_skip_field(stream, wire_type);\n    \n    if (wire_type == PB_WT_STRING)\n    {\n        pb_istream_t substream;\n        \n        if (!pb_make_string_substream(stream, &substream))\n            return false;\n        \n        do\n        {\n            if (!pCallback->funcs.decode(&substream, iter->pos, arg))\n                PB_RETURN_ERROR(stream, \"callback failed\");\n        } while (substream.bytes_left);\n        \n        pb_close_string_substream(stream, &substream);\n        return true;\n    }\n    else\n    {\n        /* Copy the single scalar value to stack.\n         * This is required so that we can limit the stream length,\n         * which in turn allows to use same callback for packed and\n         * not-packed fields. */\n        pb_istream_t substream;\n        pb_byte_t buffer[10];\n        size_t size = sizeof(buffer);\n        \n        if (!read_raw_value(stream, wire_type, buffer, &size))\n            return false;\n        substream = pb_istream_from_buffer(buffer, size);\n        \n        return pCallback->funcs.decode(&substream, iter->pos, arg);\n    }\n}\n\nstatic bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n#ifdef PB_ENABLE_MALLOC\n    /* When decoding an oneof field, check if there is old data that must be\n     * released first. */\n    if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)\n    {\n        if (!pb_release_union_field(stream, iter))\n            return false;\n    }\n#endif\n\n    switch (PB_ATYPE(iter->pos->type))\n    {\n        case PB_ATYPE_STATIC:\n            return decode_static_field(stream, wire_type, iter);\n        \n        case PB_ATYPE_POINTER:\n            return decode_pointer_field(stream, wire_type, iter);\n        \n        case PB_ATYPE_CALLBACK:\n            return decode_callback_field(stream, wire_type, iter);\n        \n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n}\n\nstatic void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension)\n{\n    /* Fake a field iterator for the extension field.\n     * It is not actually safe to advance this iterator, but decode_field\n     * will not even try to. */\n    const pb_field_t *field = (const pb_field_t*)extension->type->arg;\n    (void)pb_field_iter_begin(iter, field, extension->dest);\n    iter->pData = extension->dest;\n    iter->pSize = &extension->found;\n    \n    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n    {\n        /* For pointer extensions, the pointer is stored directly\n         * in the extension structure. This avoids having an extra\n         * indirection. */\n        iter->pData = &extension->dest;\n    }\n}\n\n/* Default handler for extension fields. Expects a pb_field_t structure\n * in extension->type->arg. */\nstatic bool checkreturn default_extension_decoder(pb_istream_t *stream,\n    pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)\n{\n    const pb_field_t *field = (const pb_field_t*)extension->type->arg;\n    pb_field_iter_t iter;\n    \n    if (field->tag != tag)\n        return true;\n    \n    iter_from_extension(&iter, extension);\n    extension->found = true;\n    return decode_field(stream, wire_type, &iter);\n}\n\n/* Try to decode an unknown field as an extension field. Tries each extension\n * decoder in turn, until one of them handles the field or loop ends. */\nstatic bool checkreturn decode_extension(pb_istream_t *stream,\n    uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)\n{\n    pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;\n    size_t pos = stream->bytes_left;\n    \n    while (extension != NULL && pos == stream->bytes_left)\n    {\n        bool status;\n        if (extension->type->decode)\n            status = extension->type->decode(stream, extension, tag, wire_type);\n        else\n            status = default_extension_decoder(stream, extension, tag, wire_type);\n\n        if (!status)\n            return false;\n        \n        extension = extension->next;\n    }\n    \n    return true;\n}\n\n/* Step through the iterator until an extension field is found or until all\n * entries have been checked. There can be only one extension field per\n * message. Returns false if no extension field is found. */\nstatic bool checkreturn find_extension_field(pb_field_iter_t *iter)\n{\n    const pb_field_t *start = iter->pos;\n    \n    do {\n        if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)\n            return true;\n        (void)pb_field_iter_next(iter);\n    } while (iter->pos != start);\n    \n    return false;\n}\n\n/* Initialize message fields to default values, recursively */\nstatic void pb_field_set_to_default(pb_field_iter_t *iter)\n{\n    pb_type_t type;\n    type = iter->pos->type;\n    \n    if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)\n    {\n        pb_extension_t *ext = *(pb_extension_t* const *)iter->pData;\n        while (ext != NULL)\n        {\n            pb_field_iter_t ext_iter;\n            ext->found = false;\n            iter_from_extension(&ext_iter, ext);\n            pb_field_set_to_default(&ext_iter);\n            ext = ext->next;\n        }\n    }\n    else if (PB_ATYPE(type) == PB_ATYPE_STATIC)\n    {\n        bool init_data = true;\n        if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)\n        {\n            /* Set has_field to false. Still initialize the optional field\n             * itself also. */\n            *(bool*)iter->pSize = false;\n        }\n        else if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||\n                 PB_HTYPE(type) == PB_HTYPE_ONEOF)\n        {\n            /* REPEATED: Set array count to 0, no need to initialize contents.\n               ONEOF: Set which_field to 0. */\n            *(pb_size_t*)iter->pSize = 0;\n            init_data = false;\n        }\n\n        if (init_data)\n        {\n            if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)\n            {\n                /* Initialize submessage to defaults */\n                pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData);\n            }\n            else if (iter->pos->ptr != NULL)\n            {\n                /* Initialize to default value */\n                memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size);\n            }\n            else\n            {\n                /* Initialize to zeros */\n                memset(iter->pData, 0, iter->pos->data_size);\n            }\n        }\n    }\n    else if (PB_ATYPE(type) == PB_ATYPE_POINTER)\n    {\n        /* Initialize the pointer to NULL. */\n        *(void**)iter->pData = NULL;\n        \n        /* Initialize array count to 0. */\n        if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||\n            PB_HTYPE(type) == PB_HTYPE_ONEOF)\n        {\n            *(pb_size_t*)iter->pSize = 0;\n        }\n    }\n    else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)\n    {\n        /* Don't overwrite callback */\n    }\n}\n\nstatic void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)\n{\n    pb_field_iter_t iter;\n\n    if (!pb_field_iter_begin(&iter, fields, dest_struct))\n        return; /* Empty message type */\n    \n    do\n    {\n        pb_field_set_to_default(&iter);\n    } while (pb_field_iter_next(&iter));\n}\n\n/*********************\n * Decode all fields *\n *********************/\n\nbool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)\n{\n    uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0};\n    const uint32_t allbits = ~(uint32_t)0;\n    uint32_t extension_range_start = 0;\n    pb_field_iter_t iter;\n    \n    /* Return value ignored, as empty message types will be correctly handled by\n     * pb_field_iter_find() anyway. */\n    (void)pb_field_iter_begin(&iter, fields, dest_struct);\n    \n    while (stream->bytes_left)\n    {\n        uint32_t tag;\n        pb_wire_type_t wire_type;\n        bool eof;\n        \n        if (!pb_decode_tag(stream, &wire_type, &tag, &eof))\n        {\n            if (eof)\n                break;\n            else\n                return false;\n        }\n        \n        if (!pb_field_iter_find(&iter, tag))\n        {\n            /* No match found, check if it matches an extension. */\n            if (tag >= extension_range_start)\n            {\n                if (!find_extension_field(&iter))\n                    extension_range_start = (uint32_t)-1;\n                else\n                    extension_range_start = iter.pos->tag;\n                \n                if (tag >= extension_range_start)\n                {\n                    size_t pos = stream->bytes_left;\n                \n                    if (!decode_extension(stream, tag, wire_type, &iter))\n                        return false;\n                    \n                    if (pos != stream->bytes_left)\n                    {\n                        /* The field was handled */\n                        continue;                    \n                    }\n                }\n            }\n        \n            /* No match found, skip data */\n            if (!pb_skip_field(stream, wire_type))\n                return false;\n            continue;\n        }\n        \n        if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED\n            && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)\n        {\n            uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31));\n            fields_seen[iter.required_field_index >> 5] |= tmp;\n        }\n            \n        if (!decode_field(stream, wire_type, &iter))\n            return false;\n    }\n    \n    /* Check that all required fields were present. */\n    {\n        /* First figure out the number of required fields by\n         * seeking to the end of the field array. Usually we\n         * are already close to end after decoding.\n         */\n        unsigned req_field_count;\n        pb_type_t last_type;\n        unsigned i;\n        do {\n            req_field_count = iter.required_field_index;\n            last_type = iter.pos->type;\n        } while (pb_field_iter_next(&iter));\n        \n        /* Fixup if last field was also required. */\n        if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)\n            req_field_count++;\n        \n        if (req_field_count > 0)\n        {\n            /* Check the whole words */\n            for (i = 0; i < (req_field_count >> 5); i++)\n            {\n                if (fields_seen[i] != allbits)\n                    PB_RETURN_ERROR(stream, \"missing required field\");\n            }\n            \n            /* Check the remaining bits */\n            if (fields_seen[req_field_count >> 5] != (allbits >> (32 - (req_field_count & 31))))\n                PB_RETURN_ERROR(stream, \"missing required field\");\n        }\n    }\n    \n    return true;\n}\n\nbool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)\n{\n    bool status;\n    pb_message_set_to_defaults(fields, dest_struct);\n    status = pb_decode_noinit(stream, fields, dest_struct);\n    \n#ifdef PB_ENABLE_MALLOC\n    if (!status)\n        pb_release(fields, dest_struct);\n#endif\n    \n    return status;\n}\n\nbool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)\n{\n    pb_istream_t substream;\n    bool status;\n    \n    if (!pb_make_string_substream(stream, &substream))\n        return false;\n    \n    status = pb_decode(&substream, fields, dest_struct);\n    pb_close_string_substream(stream, &substream);\n    return status;\n}\n\n#ifdef PB_ENABLE_MALLOC\n/* Given an oneof field, if there has already been a field inside this oneof,\n * release it before overwriting with a different one. */\nstatic bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter)\n{\n    pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */\n    pb_size_t new_tag = iter->pos->tag; /* New which_ value */\n\n    if (old_tag == 0)\n        return true; /* Ok, no old data in union */\n\n    if (old_tag == new_tag)\n        return true; /* Ok, old data is of same type => merge */\n\n    /* Release old data. The find can fail if the message struct contains\n     * invalid data. */\n    if (!pb_field_iter_find(iter, old_tag))\n        PB_RETURN_ERROR(stream, \"invalid union tag\");\n\n    pb_release_single_field(iter);\n\n    /* Restore iterator to where it should be.\n     * This shouldn't fail unless the pb_field_t structure is corrupted. */\n    if (!pb_field_iter_find(iter, new_tag))\n        PB_RETURN_ERROR(stream, \"iterator error\");\n    \n    return true;\n}\n\nstatic void pb_release_single_field(const pb_field_iter_t *iter)\n{\n    pb_type_t type;\n    type = iter->pos->type;\n\n    if (PB_HTYPE(type) == PB_HTYPE_ONEOF)\n    {\n        if (*(pb_size_t*)iter->pSize != iter->pos->tag)\n            return; /* This is not the current field in the union */\n    }\n\n    /* Release anything contained inside an extension or submsg.\n     * This has to be done even if the submsg itself is statically\n     * allocated. */\n    if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)\n    {\n        /* Release fields from all extensions in the linked list */\n        pb_extension_t *ext = *(pb_extension_t**)iter->pData;\n        while (ext != NULL)\n        {\n            pb_field_iter_t ext_iter;\n            iter_from_extension(&ext_iter, ext);\n            pb_release_single_field(&ext_iter);\n            ext = ext->next;\n        }\n    }\n    else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)\n    {\n        /* Release fields in submessage or submsg array */\n        void *pItem = iter->pData;\n        pb_size_t count = 1;\n        \n        if (PB_ATYPE(type) == PB_ATYPE_POINTER)\n        {\n            pItem = *(void**)iter->pData;\n        }\n        \n        if (PB_HTYPE(type) == PB_HTYPE_REPEATED)\n        {\n            count = *(pb_size_t*)iter->pSize;\n\n            if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)\n            {\n                /* Protect against corrupted _count fields */\n                count = iter->pos->array_size;\n            }\n        }\n        \n        if (pItem)\n        {\n            while (count--)\n            {\n                pb_release((const pb_field_t*)iter->pos->ptr, pItem);\n                pItem = (char*)pItem + iter->pos->data_size;\n            }\n        }\n    }\n    \n    if (PB_ATYPE(type) == PB_ATYPE_POINTER)\n    {\n        if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&\n            (PB_LTYPE(type) == PB_LTYPE_STRING ||\n             PB_LTYPE(type) == PB_LTYPE_BYTES))\n        {\n            /* Release entries in repeated string or bytes array */\n            void **pItem = *(void***)iter->pData;\n            pb_size_t count = *(pb_size_t*)iter->pSize;\n            while (count--)\n            {\n                pb_free(*pItem);\n                *pItem++ = NULL;\n            }\n        }\n        \n        if (PB_HTYPE(type) == PB_HTYPE_REPEATED)\n        {\n            /* We are going to release the array, so set the size to 0 */\n            *(pb_size_t*)iter->pSize = 0;\n        }\n        \n        /* Release main item */\n        pb_free(*(void**)iter->pData);\n        *(void**)iter->pData = NULL;\n    }\n}\n\nvoid pb_release(const pb_field_t fields[], void *dest_struct)\n{\n    pb_field_iter_t iter;\n    \n    if (!dest_struct)\n        return; /* Ignore NULL pointers, similar to free() */\n\n    if (!pb_field_iter_begin(&iter, fields, dest_struct))\n        return; /* Empty message type */\n    \n    do\n    {\n        pb_release_single_field(&iter);\n    } while (pb_field_iter_next(&iter));\n}\n#endif\n\n/* Field decoders */\n\nbool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)\n{\n    uint64_t value;\n    if (!pb_decode_varint(stream, &value))\n        return false;\n    \n    if (value & 1)\n        *dest = (int64_t)(~(value >> 1));\n    else\n        *dest = (int64_t)(value >> 1);\n    \n    return true;\n}\n\nbool pb_decode_fixed32(pb_istream_t *stream, void *dest)\n{\n    pb_byte_t bytes[4];\n\n    if (!pb_read(stream, bytes, 4))\n        return false;\n    \n    *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) |\n                       ((uint32_t)bytes[1] << 8) |\n                       ((uint32_t)bytes[2] << 16) |\n                       ((uint32_t)bytes[3] << 24);\n    return true;\n}\n\nbool pb_decode_fixed64(pb_istream_t *stream, void *dest)\n{\n    pb_byte_t bytes[8];\n\n    if (!pb_read(stream, bytes, 8))\n        return false;\n    \n    *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) |\n                       ((uint64_t)bytes[1] << 8) |\n                       ((uint64_t)bytes[2] << 16) |\n                       ((uint64_t)bytes[3] << 24) |\n                       ((uint64_t)bytes[4] << 32) |\n                       ((uint64_t)bytes[5] << 40) |\n                       ((uint64_t)bytes[6] << 48) |\n                       ((uint64_t)bytes[7] << 56);\n    \n    return true;\n}\n\nstatic bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    uint64_t value;\n    int64_t svalue;\n    int64_t clamped;\n    if (!pb_decode_varint(stream, &value))\n        return false;\n    \n    /* See issue 97: Google's C++ protobuf allows negative varint values to\n     * be cast as int32_t, instead of the int64_t that should be used when\n     * encoding. Previous nanopb versions had a bug in encoding. In order to\n     * not break decoding of such messages, we cast <=32 bit fields to\n     * int32_t first to get the sign correct.\n     */\n    if (field->data_size == sizeof(int64_t))\n        svalue = (int64_t)value;\n    else\n        svalue = (int32_t)value;\n\n    /* Cast to the proper field size, while checking for overflows */\n    if (field->data_size == sizeof(int64_t))\n        clamped = *(int64_t*)dest = svalue;\n    else if (field->data_size == sizeof(int32_t))\n        clamped = *(int32_t*)dest = (int32_t)svalue;\n    else if (field->data_size == sizeof(int_least16_t))\n        clamped = *(int_least16_t*)dest = (int_least16_t)svalue;\n    else if (field->data_size == sizeof(int_least8_t))\n        clamped = *(int_least8_t*)dest = (int_least8_t)svalue;\n    else\n        PB_RETURN_ERROR(stream, \"invalid data_size\");\n\n    if (clamped != svalue)\n        PB_RETURN_ERROR(stream, \"integer too large\");\n    \n    return true;\n}\n\nstatic bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    uint64_t value, clamped;\n    if (!pb_decode_varint(stream, &value))\n        return false;\n    \n    /* Cast to the proper field size, while checking for overflows */\n    if (field->data_size == sizeof(uint64_t))\n        clamped = *(uint64_t*)dest = value;\n    else if (field->data_size == sizeof(uint32_t))\n        clamped = *(uint32_t*)dest = (uint32_t)value;\n    else if (field->data_size == sizeof(uint_least16_t))\n        clamped = *(uint_least16_t*)dest = (uint_least16_t)value;\n    else if (field->data_size == sizeof(uint_least8_t))\n        clamped = *(uint_least8_t*)dest = (uint_least8_t)value;\n    else\n        PB_RETURN_ERROR(stream, \"invalid data_size\");\n    \n    if (clamped != value)\n        PB_RETURN_ERROR(stream, \"integer too large\");\n\n    return true;\n}\n\nstatic bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    int64_t value, clamped;\n    if (!pb_decode_svarint(stream, &value))\n        return false;\n    \n    /* Cast to the proper field size, while checking for overflows */\n    if (field->data_size == sizeof(int64_t))\n        clamped = *(int64_t*)dest = value;\n    else if (field->data_size == sizeof(int32_t))\n        clamped = *(int32_t*)dest = (int32_t)value;\n    else if (field->data_size == sizeof(int_least16_t))\n        clamped = *(int_least16_t*)dest = (int_least16_t)value;\n    else if (field->data_size == sizeof(int_least8_t))\n        clamped = *(int_least8_t*)dest = (int_least8_t)value;\n    else\n        PB_RETURN_ERROR(stream, \"invalid data_size\");\n\n    if (clamped != value)\n        PB_RETURN_ERROR(stream, \"integer too large\");\n    \n    return true;\n}\n\nstatic bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    PB_UNUSED(field);\n    return pb_decode_fixed32(stream, dest);\n}\n\nstatic bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    PB_UNUSED(field);\n    return pb_decode_fixed64(stream, dest);\n}\n\nstatic bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    uint32_t size;\n    size_t alloc_size;\n    pb_bytes_array_t *bdest;\n    \n    if (!pb_decode_varint32(stream, &size))\n        return false;\n    \n    if (size > PB_SIZE_MAX)\n        PB_RETURN_ERROR(stream, \"bytes overflow\");\n    \n    alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);\n    if (size > alloc_size)\n        PB_RETURN_ERROR(stream, \"size too large\");\n    \n    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n    {\n#ifndef PB_ENABLE_MALLOC\n        PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n        if (!allocate_field(stream, dest, alloc_size, 1))\n            return false;\n        bdest = *(pb_bytes_array_t**)dest;\n#endif\n    }\n    else\n    {\n        if (alloc_size > field->data_size)\n            PB_RETURN_ERROR(stream, \"bytes overflow\");\n        bdest = (pb_bytes_array_t*)dest;\n    }\n\n    bdest->size = (pb_size_t)size;\n    return pb_read(stream, bdest->bytes, size);\n}\n\nstatic bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    uint32_t size;\n    size_t alloc_size;\n    bool status;\n    if (!pb_decode_varint32(stream, &size))\n        return false;\n    \n    /* Space for null terminator */\n    alloc_size = size + 1;\n    \n    if (alloc_size < size)\n        PB_RETURN_ERROR(stream, \"size too large\");\n    \n    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n    {\n#ifndef PB_ENABLE_MALLOC\n        PB_RETURN_ERROR(stream, \"no malloc support\");\n#else\n        if (!allocate_field(stream, dest, alloc_size, 1))\n            return false;\n        dest = *(void**)dest;\n#endif\n    }\n    else\n    {\n        if (alloc_size > field->data_size)\n            PB_RETURN_ERROR(stream, \"string overflow\");\n    }\n    \n    status = pb_read(stream, (pb_byte_t*)dest, size);\n    *((pb_byte_t*)dest + size) = 0;\n    return status;\n}\n\nstatic bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)\n{\n    bool status;\n    pb_istream_t substream;\n    const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;\n    \n    if (!pb_make_string_substream(stream, &substream))\n        return false;\n    \n    if (field->ptr == NULL)\n        PB_RETURN_ERROR(stream, \"invalid field descriptor\");\n    \n    /* New array entries need to be initialized, while required and optional\n     * submessages have already been initialized in the top-level pb_decode. */\n    if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)\n        status = pb_decode(&substream, submsg_fields, dest);\n    else\n        status = pb_decode_noinit(&substream, submsg_fields, dest);\n    \n    pb_close_string_substream(stream, &substream);\n    return status;\n}\n"
  },
  {
    "path": "src/pb_decode.h",
    "content": "/* pb_decode.h: Functions to decode protocol buffers. Depends on pb_decode.c.\n * The main function is pb_decode. You also need an input stream, and the\n * field descriptions created by nanopb_generator.py.\n */\n\n#ifndef PB_DECODE_H_INCLUDED\n#define PB_DECODE_H_INCLUDED\n\n#include \"pb.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Structure for defining custom input streams. You will need to provide\n * a callback function to read the bytes from your storage, which can be\n * for example a file or a network socket.\n * \n * The callback must conform to these rules:\n *\n * 1) Return false on IO errors. This will cause decoding to abort.\n * 2) You can use state to store your own data (e.g. buffer pointer),\n *    and rely on pb_read to verify that no-body reads past bytes_left.\n * 3) Your callback may be used with substreams, in which case bytes_left\n *    is different than from the main stream. Don't use bytes_left to compute\n *    any pointers.\n */\nstruct pb_istream_s\n{\n#ifdef PB_BUFFER_ONLY\n    /* Callback pointer is not used in buffer-only configuration.\n     * Having an int pointer here allows binary compatibility but\n     * gives an error if someone tries to assign callback function.\n     */\n    int *callback;\n#else\n    bool (*callback)(pb_istream_t *stream, pb_byte_t *buf, size_t count);\n#endif\n\n    void *state; /* Free field for use by callback implementation */\n    size_t bytes_left;\n    \n#ifndef PB_NO_ERRMSG\n    const char *errmsg;\n#endif\n};\n\n/***************************\n * Main decoding functions *\n ***************************/\n \n/* Decode a single protocol buffers message from input stream into a C structure.\n * Returns true on success, false on any failure.\n * The actual struct pointed to by dest must match the description in fields.\n * Callback fields of the destination structure must be initialized by caller.\n * All other fields will be initialized by this function.\n *\n * Example usage:\n *    MyMessage msg = {};\n *    uint8_t buffer[64];\n *    pb_istream_t stream;\n *    \n *    // ... read some data into buffer ...\n *\n *    stream = pb_istream_from_buffer(buffer, count);\n *    pb_decode(&stream, MyMessage_fields, &msg);\n */\nbool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);\n\n/* Same as pb_decode, except does not initialize the destination structure\n * to default values. This is slightly faster if you need no default values\n * and just do memset(struct, 0, sizeof(struct)) yourself.\n *\n * This can also be used for 'merging' two messages, i.e. update only the\n * fields that exist in the new message.\n *\n * Note: If this function returns with an error, it will not release any\n * dynamically allocated fields. You will need to call pb_release() yourself.\n */\nbool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);\n\n/* Same as pb_decode, except expects the stream to start with the message size\n * encoded as varint. Corresponds to parseDelimitedFrom() in Google's\n * protobuf API.\n */\nbool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);\n\n#ifdef PB_ENABLE_MALLOC\n/* Release any allocated pointer fields. If you use dynamic allocation, you should\n * call this for any successfully decoded message when you are done with it. If\n * pb_decode() returns with an error, the message is already released.\n */\nvoid pb_release(const pb_field_t fields[], void *dest_struct);\n#endif\n\n\n/**************************************\n * Functions for manipulating streams *\n **************************************/\n\n/* Create an input stream for reading from a memory buffer.\n *\n * Alternatively, you can use a custom stream that reads directly from e.g.\n * a file or a network socket.\n */\npb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize);\n\n/* Function to read from a pb_istream_t. You can use this if you need to\n * read some custom header data, or to read data in field callbacks.\n */\nbool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);\n\n\n/************************************************\n * Helper functions for writing field callbacks *\n ************************************************/\n\n/* Decode the tag for the next field in the stream. Gives the wire type and\n * field tag. At end of the message, returns false and sets eof to true. */\nbool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof);\n\n/* Skip the field payload data, given the wire type. */\nbool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type);\n\n/* Decode an integer in the varint format. This works for bool, enum, int32,\n * int64, uint32 and uint64 field types. */\nbool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);\n\n/* Decode an integer in the zig-zagged svarint format. This works for sint32\n * and sint64. */\nbool pb_decode_svarint(pb_istream_t *stream, int64_t *dest);\n\n/* Decode a fixed32, sfixed32 or float value. You need to pass a pointer to\n * a 4-byte wide C variable. */\nbool pb_decode_fixed32(pb_istream_t *stream, void *dest);\n\n/* Decode a fixed64, sfixed64 or double value. You need to pass a pointer to\n * a 8-byte wide C variable. */\nbool pb_decode_fixed64(pb_istream_t *stream, void *dest);\n\n/* Make a limited-length substream for reading a PB_WT_STRING field. */\nbool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream);\nvoid pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif\n"
  },
  {
    "path": "src/pb_encode.c",
    "content": "/* pb_encode.c -- encode a protobuf using minimal resources\n *\n * 2011 Petteri Aimonen <jpa@kapsi.fi>\n */\n\n#include \"pb.h\"\n#include \"pb_encode.h\"\n#include \"pb_common.h\"\n\n/* Use the GCC warn_unused_result attribute to check that all return values\n * are propagated correctly. On other compilers and gcc before 3.4.0 just\n * ignore the annotation.\n */\n#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)\n    #define checkreturn\n#else\n    #define checkreturn __attribute__((warn_unused_result))\n#endif\n\n/**************************************\n * Declarations internal to this file *\n **************************************/\ntypedef bool (*pb_encoder_t)(pb_ostream_t *stream, const pb_field_t *field, const void *src) checkreturn;\n\nstatic bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);\nstatic bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, const void *pData, size_t count, pb_encoder_t func);\nstatic bool checkreturn encode_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData);\nstatic bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension);\nstatic bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData);\nstatic bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src);\nstatic bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src);\n\n/* --- Function pointers to field encoders ---\n * Order in the array must match pb_action_t LTYPE numbering.\n */\nstatic const pb_encoder_t PB_ENCODERS[PB_LTYPES_COUNT] = {\n    &pb_enc_varint,\n    &pb_enc_uvarint,\n    &pb_enc_svarint,\n    &pb_enc_fixed32,\n    &pb_enc_fixed64,\n\n    &pb_enc_bytes,\n    &pb_enc_string,\n    &pb_enc_submessage,\n    NULL /* extensions */\n};\n\n/*******************************\n * pb_ostream_t implementation *\n *******************************/\n\nstatic bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)\n{\n    pb_byte_t *dest = (pb_byte_t*)stream->state;\n    stream->state = dest + count;\n    \n    while (count--)\n        *dest++ = *buf++;\n    \n    return true;\n}\n\npb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)\n{\n    pb_ostream_t stream;\n#ifdef PB_BUFFER_ONLY\n    stream.callback = (void*)1; /* Just a marker value */\n#else\n    stream.callback = &buf_write;\n#endif\n    stream.state = buf;\n    stream.max_size = bufsize;\n    stream.bytes_written = 0;\n#ifndef PB_NO_ERRMSG\n    stream.errmsg = NULL;\n#endif\n    return stream;\n}\n\nbool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count)\n{\n    if (stream->callback != NULL)\n    {\n        if (stream->bytes_written + count > stream->max_size)\n            PB_RETURN_ERROR(stream, \"stream full\");\n\n#ifdef PB_BUFFER_ONLY\n        if (!buf_write(stream, buf, count))\n            PB_RETURN_ERROR(stream, \"io error\");\n#else        \n        if (!stream->callback(stream, buf, count))\n            PB_RETURN_ERROR(stream, \"io error\");\n#endif\n    }\n    \n    stream->bytes_written += count;\n    return true;\n}\n\n/*************************\n * Encode a single field *\n *************************/\n\n/* Encode a static array. Handles the size calculations and possible packing. */\nstatic bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field,\n                         const void *pData, size_t count, pb_encoder_t func)\n{\n    size_t i;\n    const void *p;\n    size_t size;\n    \n    if (count == 0)\n        return true;\n\n    if (PB_ATYPE(field->type) != PB_ATYPE_POINTER && count > field->array_size)\n        PB_RETURN_ERROR(stream, \"array max size exceeded\");\n    \n    /* We always pack arrays if the datatype allows it. */\n    if (PB_LTYPE(field->type) <= PB_LTYPE_LAST_PACKABLE)\n    {\n        if (!pb_encode_tag(stream, PB_WT_STRING, field->tag))\n            return false;\n        \n        /* Determine the total size of packed array. */\n        if (PB_LTYPE(field->type) == PB_LTYPE_FIXED32)\n        {\n            size = 4 * count;\n        }\n        else if (PB_LTYPE(field->type) == PB_LTYPE_FIXED64)\n        {\n            size = 8 * count;\n        }\n        else\n        { \n            pb_ostream_t sizestream = PB_OSTREAM_SIZING;\n            p = pData;\n            for (i = 0; i < count; i++)\n            {\n                if (!func(&sizestream, field, p))\n                    return false;\n                p = (const char*)p + field->data_size;\n            }\n            size = sizestream.bytes_written;\n        }\n        \n        if (!pb_encode_varint(stream, (uint64_t)size))\n            return false;\n        \n        if (stream->callback == NULL)\n            return pb_write(stream, NULL, size); /* Just sizing.. */\n        \n        /* Write the data */\n        p = pData;\n        for (i = 0; i < count; i++)\n        {\n            if (!func(stream, field, p))\n                return false;\n            p = (const char*)p + field->data_size;\n        }\n    }\n    else\n    {\n        p = pData;\n        for (i = 0; i < count; i++)\n        {\n            if (!pb_encode_tag_for_field(stream, field))\n                return false;\n\n            /* Normally the data is stored directly in the array entries, but\n             * for pointer-type string and bytes fields, the array entries are\n             * actually pointers themselves also. So we have to dereference once\n             * more to get to the actual data. */\n            if (PB_ATYPE(field->type) == PB_ATYPE_POINTER &&\n                (PB_LTYPE(field->type) == PB_LTYPE_STRING ||\n                 PB_LTYPE(field->type) == PB_LTYPE_BYTES))\n            {\n                if (!func(stream, field, *(const void* const*)p))\n                    return false;      \n            }\n            else\n            {\n                if (!func(stream, field, p))\n                    return false;\n            }\n            p = (const char*)p + field->data_size;\n        }\n    }\n    \n    return true;\n}\n\n/* Encode a field with static or pointer allocation, i.e. one whose data\n * is available to the encoder directly. */\nstatic bool checkreturn encode_basic_field(pb_ostream_t *stream,\n    const pb_field_t *field, const void *pData)\n{\n    pb_encoder_t func;\n    const void *pSize;\n    bool implicit_has = true;\n    \n    func = PB_ENCODERS[PB_LTYPE(field->type)];\n    \n    if (field->size_offset)\n        pSize = (const char*)pData + field->size_offset;\n    else\n        pSize = &implicit_has;\n\n    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n    {\n        /* pData is a pointer to the field, which contains pointer to\n         * the data. If the 2nd pointer is NULL, it is interpreted as if\n         * the has_field was false.\n         */\n        \n        pData = *(const void* const*)pData;\n        implicit_has = (pData != NULL);\n    }\n\n    switch (PB_HTYPE(field->type))\n    {\n        case PB_HTYPE_REQUIRED:\n            if (!pData)\n                PB_RETURN_ERROR(stream, \"missing required field\");\n            if (!pb_encode_tag_for_field(stream, field))\n                return false;\n            if (!func(stream, field, pData))\n                return false;\n            break;\n        \n        case PB_HTYPE_OPTIONAL:\n            if (*(const bool*)pSize)\n            {\n                if (!pb_encode_tag_for_field(stream, field))\n                    return false;\n            \n                if (!func(stream, field, pData))\n                    return false;\n            }\n            break;\n        \n        case PB_HTYPE_REPEATED:\n            if (!encode_array(stream, field, pData, *(const pb_size_t*)pSize, func))\n                return false;\n            break;\n        \n        case PB_HTYPE_ONEOF:\n            if (*(const pb_size_t*)pSize == field->tag)\n            {\n                if (!pb_encode_tag_for_field(stream, field))\n                    return false;\n\n                if (!func(stream, field, pData))\n                    return false;\n            }\n            break;\n            \n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n    \n    return true;\n}\n\n/* Encode a field with callback semantics. This means that a user function is\n * called to provide and encode the actual data. */\nstatic bool checkreturn encode_callback_field(pb_ostream_t *stream,\n    const pb_field_t *field, const void *pData)\n{\n    const pb_callback_t *callback = (const pb_callback_t*)pData;\n    \n#ifdef PB_OLD_CALLBACK_STYLE\n    const void *arg = callback->arg;\n#else\n    void * const *arg = &(callback->arg);\n#endif    \n    \n    if (callback->funcs.encode != NULL)\n    {\n        if (!callback->funcs.encode(stream, field, arg))\n            PB_RETURN_ERROR(stream, \"callback error\");\n    }\n    return true;\n}\n\n/* Encode a single field of any callback or static type. */\nstatic bool checkreturn encode_field(pb_ostream_t *stream,\n    const pb_field_t *field, const void *pData)\n{\n    switch (PB_ATYPE(field->type))\n    {\n        case PB_ATYPE_STATIC:\n        case PB_ATYPE_POINTER:\n            return encode_basic_field(stream, field, pData);\n        \n        case PB_ATYPE_CALLBACK:\n            return encode_callback_field(stream, field, pData);\n        \n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n}\n\n/* Default handler for extension fields. Expects to have a pb_field_t\n * pointer in the extension->type->arg field. */\nstatic bool checkreturn default_extension_encoder(pb_ostream_t *stream,\n    const pb_extension_t *extension)\n{\n    const pb_field_t *field = (const pb_field_t*)extension->type->arg;\n    \n    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n    {\n        /* For pointer extensions, the pointer is stored directly\n         * in the extension structure. This avoids having an extra\n         * indirection. */\n        return encode_field(stream, field, &extension->dest);\n    }\n    else\n    {\n        return encode_field(stream, field, extension->dest);\n    }\n}\n\n/* Walk through all the registered extensions and give them a chance\n * to encode themselves. */\nstatic bool checkreturn encode_extension_field(pb_ostream_t *stream,\n    const pb_field_t *field, const void *pData)\n{\n    const pb_extension_t *extension = *(const pb_extension_t* const *)pData;\n    PB_UNUSED(field);\n    \n    while (extension)\n    {\n        bool status;\n        if (extension->type->encode)\n            status = extension->type->encode(stream, extension);\n        else\n            status = default_extension_encoder(stream, extension);\n\n        if (!status)\n            return false;\n        \n        extension = extension->next;\n    }\n    \n    return true;\n}\n\n/*********************\n * Encode all fields *\n *********************/\n\nstatic void *remove_const(const void *p)\n{\n    /* Note: this casts away const, in order to use the common field iterator\n     * logic for both encoding and decoding. */\n    union {\n        void *p1;\n        const void *p2;\n    } t;\n    t.p2 = p;\n    return t.p1;\n}\n\nbool checkreturn pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct)\n{\n    pb_field_iter_t iter;\n    if (!pb_field_iter_begin(&iter, fields, remove_const(src_struct)))\n        return true; /* Empty message type */\n    \n    do {\n        if (PB_LTYPE(iter.pos->type) == PB_LTYPE_EXTENSION)\n        {\n            /* Special case for the extension field placeholder */\n            if (!encode_extension_field(stream, iter.pos, iter.pData))\n                return false;\n        }\n        else\n        {\n            /* Regular field */\n            if (!encode_field(stream, iter.pos, iter.pData))\n                return false;\n        }\n    } while (pb_field_iter_next(&iter));\n    \n    return true;\n}\n\nbool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct)\n{\n    return pb_encode_submessage(stream, fields, src_struct);\n}\n\nbool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct)\n{\n    pb_ostream_t stream = PB_OSTREAM_SIZING;\n    \n    if (!pb_encode(&stream, fields, src_struct))\n        return false;\n    \n    *size = stream.bytes_written;\n    return true;\n}\n\n/********************\n * Helper functions *\n ********************/\nbool checkreturn pb_encode_varint(pb_ostream_t *stream, uint64_t value)\n{\n    pb_byte_t buffer[10];\n    size_t i = 0;\n    \n    if (value <= 0x7F)\n    {\n        pb_byte_t v = (pb_byte_t)value;\n        return pb_write(stream, &v, 1);\n    }\n    \n    while (value)\n    {\n        buffer[i] = (pb_byte_t)((value & 0x7F) | 0x80);\n        value >>= 7;\n        i++;\n    }\n    buffer[i-1] &= 0x7F; /* Unset top bit on last byte */\n    \n    return pb_write(stream, buffer, i);\n}\n\nbool checkreturn pb_encode_svarint(pb_ostream_t *stream, int64_t value)\n{\n    uint64_t zigzagged;\n    if (value < 0)\n        zigzagged = ~((uint64_t)value << 1);\n    else\n        zigzagged = (uint64_t)value << 1;\n    \n    return pb_encode_varint(stream, zigzagged);\n}\n\nbool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value)\n{\n    uint32_t val = *(const uint32_t*)value;\n    pb_byte_t bytes[4];\n    bytes[0] = (pb_byte_t)(val & 0xFF);\n    bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);\n    bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);\n    bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);\n    return pb_write(stream, bytes, 4);\n}\n\nbool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value)\n{\n    uint64_t val = *(const uint64_t*)value;\n    pb_byte_t bytes[8];\n    bytes[0] = (pb_byte_t)(val & 0xFF);\n    bytes[1] = (pb_byte_t)((val >> 8) & 0xFF);\n    bytes[2] = (pb_byte_t)((val >> 16) & 0xFF);\n    bytes[3] = (pb_byte_t)((val >> 24) & 0xFF);\n    bytes[4] = (pb_byte_t)((val >> 32) & 0xFF);\n    bytes[5] = (pb_byte_t)((val >> 40) & 0xFF);\n    bytes[6] = (pb_byte_t)((val >> 48) & 0xFF);\n    bytes[7] = (pb_byte_t)((val >> 56) & 0xFF);\n    return pb_write(stream, bytes, 8);\n}\n\nbool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number)\n{\n    uint64_t tag = ((uint64_t)field_number << 3) | wiretype;\n    return pb_encode_varint(stream, tag);\n}\n\nbool checkreturn pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field)\n{\n    pb_wire_type_t wiretype;\n    switch (PB_LTYPE(field->type))\n    {\n        case PB_LTYPE_VARINT:\n        case PB_LTYPE_UVARINT:\n        case PB_LTYPE_SVARINT:\n            wiretype = PB_WT_VARINT;\n            break;\n        \n        case PB_LTYPE_FIXED32:\n            wiretype = PB_WT_32BIT;\n            break;\n        \n        case PB_LTYPE_FIXED64:\n            wiretype = PB_WT_64BIT;\n            break;\n        \n        case PB_LTYPE_BYTES:\n        case PB_LTYPE_STRING:\n        case PB_LTYPE_SUBMESSAGE:\n            wiretype = PB_WT_STRING;\n            break;\n        \n        default:\n            PB_RETURN_ERROR(stream, \"invalid field type\");\n    }\n    \n    return pb_encode_tag(stream, wiretype, field->tag);\n}\n\nbool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size)\n{\n    if (!pb_encode_varint(stream, (uint64_t)size))\n        return false;\n    \n    return pb_write(stream, buffer, size);\n}\n\nbool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct)\n{\n    /* First calculate the message size using a non-writing substream. */\n    pb_ostream_t substream = PB_OSTREAM_SIZING;\n    size_t size;\n    bool status;\n    \n    if (!pb_encode(&substream, fields, src_struct))\n    {\n#ifndef PB_NO_ERRMSG\n        stream->errmsg = substream.errmsg;\n#endif\n        return false;\n    }\n    \n    size = substream.bytes_written;\n    \n    if (!pb_encode_varint(stream, (uint64_t)size))\n        return false;\n    \n    if (stream->callback == NULL)\n        return pb_write(stream, NULL, size); /* Just sizing */\n    \n    if (stream->bytes_written + size > stream->max_size)\n        PB_RETURN_ERROR(stream, \"stream full\");\n        \n    /* Use a substream to verify that a callback doesn't write more than\n     * what it did the first time. */\n    substream.callback = stream->callback;\n    substream.state = stream->state;\n    substream.max_size = size;\n    substream.bytes_written = 0;\n#ifndef PB_NO_ERRMSG\n    substream.errmsg = NULL;\n#endif\n    \n    status = pb_encode(&substream, fields, src_struct);\n    \n    stream->bytes_written += substream.bytes_written;\n    stream->state = substream.state;\n#ifndef PB_NO_ERRMSG\n    stream->errmsg = substream.errmsg;\n#endif\n    \n    if (substream.bytes_written != size)\n        PB_RETURN_ERROR(stream, \"submsg size changed\");\n    \n    return status;\n}\n\n/* Field encoders */\n\nstatic bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    int64_t value = 0;\n    \n    if (field->data_size == sizeof(int_least8_t))\n        value = *(const int_least8_t*)src;\n    else if (field->data_size == sizeof(int_least16_t))\n        value = *(const int_least16_t*)src;\n    else if (field->data_size == sizeof(int32_t))\n        value = *(const int32_t*)src;\n    else if (field->data_size == sizeof(int64_t))\n        value = *(const int64_t*)src;\n    else\n        PB_RETURN_ERROR(stream, \"invalid data_size\");\n    \n    return pb_encode_varint(stream, (uint64_t)value);\n}\n\nstatic bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    uint64_t value = 0;\n    \n    if (field->data_size == sizeof(uint_least8_t))\n        value = *(const uint_least8_t*)src;\n    else if (field->data_size == sizeof(uint_least16_t))\n        value = *(const uint_least16_t*)src;\n    else if (field->data_size == sizeof(uint32_t))\n        value = *(const uint32_t*)src;\n    else if (field->data_size == sizeof(uint64_t))\n        value = *(const uint64_t*)src;\n    else\n        PB_RETURN_ERROR(stream, \"invalid data_size\");\n    \n    return pb_encode_varint(stream, value);\n}\n\nstatic bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    int64_t value = 0;\n    \n    if (field->data_size == sizeof(int_least8_t))\n        value = *(const int_least8_t*)src;\n    else if (field->data_size == sizeof(int_least16_t))\n        value = *(const int_least16_t*)src;\n    else if (field->data_size == sizeof(int32_t))\n        value = *(const int32_t*)src;\n    else if (field->data_size == sizeof(int64_t))\n        value = *(const int64_t*)src;\n    else\n        PB_RETURN_ERROR(stream, \"invalid data_size\");\n    \n    return pb_encode_svarint(stream, value);\n}\n\nstatic bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    PB_UNUSED(field);\n    return pb_encode_fixed64(stream, src);\n}\n\nstatic bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    PB_UNUSED(field);\n    return pb_encode_fixed32(stream, src);\n}\n\nstatic bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    const pb_bytes_array_t *bytes = (const pb_bytes_array_t*)src;\n    \n    if (src == NULL)\n    {\n        /* Threat null pointer as an empty bytes field */\n        return pb_encode_string(stream, NULL, 0);\n    }\n    \n    if (PB_ATYPE(field->type) == PB_ATYPE_STATIC &&\n        PB_BYTES_ARRAY_T_ALLOCSIZE(bytes->size) > field->data_size)\n    {\n        PB_RETURN_ERROR(stream, \"bytes size exceeded\");\n    }\n    \n    return pb_encode_string(stream, bytes->bytes, bytes->size);\n}\n\nstatic bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    size_t size = 0;\n    size_t max_size = field->data_size;\n    const char *p = (const char*)src;\n    \n    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)\n        max_size = (size_t)-1;\n\n    if (src == NULL)\n    {\n        size = 0; /* Threat null pointer as an empty string */\n    }\n    else\n    {\n        /* strnlen() is not always available, so just use a loop */\n        while (size < max_size && *p != '\\0')\n        {\n            size++;\n            p++;\n        }\n    }\n\n    return pb_encode_string(stream, (const pb_byte_t*)src, size);\n}\n\nstatic bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src)\n{\n    if (field->ptr == NULL)\n        PB_RETURN_ERROR(stream, \"invalid field descriptor\");\n    \n    return pb_encode_submessage(stream, (const pb_field_t*)field->ptr, src);\n}\n\n"
  },
  {
    "path": "src/pb_encode.h",
    "content": "/* pb_encode.h: Functions to encode protocol buffers. Depends on pb_encode.c.\n * The main function is pb_encode. You also need an output stream, and the\n * field descriptions created by nanopb_generator.py.\n */\n\n#ifndef PB_ENCODE_H_INCLUDED\n#define PB_ENCODE_H_INCLUDED\n\n#include \"pb.h\"\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n/* Structure for defining custom output streams. You will need to provide\n * a callback function to write the bytes to your storage, which can be\n * for example a file or a network socket.\n *\n * The callback must conform to these rules:\n *\n * 1) Return false on IO errors. This will cause encoding to abort.\n * 2) You can use state to store your own data (e.g. buffer pointer).\n * 3) pb_write will update bytes_written after your callback runs.\n * 4) Substreams will modify max_size and bytes_written. Don't use them\n *    to calculate any pointers.\n */\nstruct pb_ostream_s\n{\n#ifdef PB_BUFFER_ONLY\n    /* Callback pointer is not used in buffer-only configuration.\n     * Having an int pointer here allows binary compatibility but\n     * gives an error if someone tries to assign callback function.\n     * Also, NULL pointer marks a 'sizing stream' that does not\n     * write anything.\n     */\n    int *callback;\n#else\n    bool (*callback)(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);\n#endif\n    void *state;          /* Free field for use by callback implementation. */\n    size_t max_size;      /* Limit number of output bytes written (or use SIZE_MAX). */\n    size_t bytes_written; /* Number of bytes written so far. */\n    \n#ifndef PB_NO_ERRMSG\n    const char *errmsg;\n#endif\n};\n\n/***************************\n * Main encoding functions *\n ***************************/\n\n/* Encode a single protocol buffers message from C structure into a stream.\n * Returns true on success, false on any failure.\n * The actual struct pointed to by src_struct must match the description in fields.\n * All required fields in the struct are assumed to have been filled in.\n *\n * Example usage:\n *    MyMessage msg = {};\n *    uint8_t buffer[64];\n *    pb_ostream_t stream;\n *\n *    msg.field1 = 42;\n *    stream = pb_ostream_from_buffer(buffer, sizeof(buffer));\n *    pb_encode(&stream, MyMessage_fields, &msg);\n */\nbool pb_encode(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);\n\n/* Same as pb_encode, but prepends the length of the message as a varint.\n * Corresponds to writeDelimitedTo() in Google's protobuf API.\n */\nbool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);\n\n/* Encode the message to get the size of the encoded data, but do not store\n * the data. */\nbool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const void *src_struct);\n\n/**************************************\n * Functions for manipulating streams *\n **************************************/\n\n/* Create an output stream for writing into a memory buffer.\n * The number of bytes written can be found in stream.bytes_written after\n * encoding the message.\n *\n * Alternatively, you can use a custom stream that writes directly to e.g.\n * a file or a network socket.\n */\npb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize);\n\n/* Pseudo-stream for measuring the size of a message without actually storing\n * the encoded data.\n * \n * Example usage:\n *    MyMessage msg = {};\n *    pb_ostream_t stream = PB_OSTREAM_SIZING;\n *    pb_encode(&stream, MyMessage_fields, &msg);\n *    printf(\"Message size is %d\\n\", stream.bytes_written);\n */\n#ifndef PB_NO_ERRMSG\n#define PB_OSTREAM_SIZING {0,0,0,0,0}\n#else\n#define PB_OSTREAM_SIZING {0,0,0,0}\n#endif\n\n/* Function to write into a pb_ostream_t stream. You can use this if you need\n * to append or prepend some custom headers to the message.\n */\nbool pb_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);\n\n\n/************************************************\n * Helper functions for writing field callbacks *\n ************************************************/\n\n/* Encode field header based on type and field number defined in the field\n * structure. Call this from the callback before writing out field contents. */\nbool pb_encode_tag_for_field(pb_ostream_t *stream, const pb_field_t *field);\n\n/* Encode field header by manually specifing wire type. You need to use this\n * if you want to write out packed arrays from a callback field. */\nbool pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wiretype, uint32_t field_number);\n\n/* Encode an integer in the varint format.\n * This works for bool, enum, int32, int64, uint32 and uint64 field types. */\nbool pb_encode_varint(pb_ostream_t *stream, uint64_t value);\n\n/* Encode an integer in the zig-zagged svarint format.\n * This works for sint32 and sint64. */\nbool pb_encode_svarint(pb_ostream_t *stream, int64_t value);\n\n/* Encode a string or bytes type field. For strings, pass strlen(s) as size. */\nbool pb_encode_string(pb_ostream_t *stream, const pb_byte_t *buffer, size_t size);\n\n/* Encode a fixed32, sfixed32 or float value.\n * You need to pass a pointer to a 4-byte wide C variable. */\nbool pb_encode_fixed32(pb_ostream_t *stream, const void *value);\n\n/* Encode a fixed64, sfixed64 or double value.\n * You need to pass a pointer to a 8-byte wide C variable. */\nbool pb_encode_fixed64(pb_ostream_t *stream, const void *value);\n\n/* Encode a submessage field.\n * You need to pass the pb_field_t array and pointer to struct, just like\n * with pb_encode(). This internally encodes the submessage twice, first to\n * calculate message size and then to actually write it out.\n */\nbool pb_encode_submessage(pb_ostream_t *stream, const pb_field_t fields[], const void *src_struct);\n\n#ifdef __cplusplus\n} /* extern \"C\" */\n#endif\n\n#endif\n"
  },
  {
    "path": "test/TheThingsMessage/TheThingsMessage.ino",
    "content": "#include <TheThingsMessage.h>\n\ndevicedata_t data = api_DeviceData_init_default;\n\nvoid setup() {\n  data.has_motion = true;\n  data.has_water = false;\n  data.has_temperature_celcius = true;\n  data.has_temperature_fahrenheit = true;\n  data.has_humidity = true;\n}\n\nvoid loop() {\n  data.motion = true;\n  data.water = 682;\n  data.temperature_celcius = 30;\n  data.temperature_fahrenheit = 86;\n  data.humidity = 97;\n\n  byte *buffer;\n  size_t size;\n\n  TheThingsMessage::encodeDeviceData(&data, &buffer, &size);\n}\n"
  },
  {
    "path": "test/TheThingsNetwork/TheThingsNetwork.ino",
    "content": "#include <TheThingsNetwork.h>\n\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000000000\";\n\nconst char *devAddr = \"00000000\";\nconst char *nwkSKey = \"00000000000000000000000000000000\";\nconst char *appSKey = \"00000000000000000000000000000000\";\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\nTheThingsNetwork ttn(loraSerial, debugSerial, TTN_FP_EU868);\n\nTheThingsNetwork ttn2(loraSerial, debugSerial, TTN_FP_US915, 10);\n\nTheThingsNetwork ttn3(loraSerial, debugSerial, TTN_FP_AS923_925, 10, 4);\n\n\nvoid setup()\n{\n  loraSerial.begin(57600);\n  debugSerial.begin(9600);\n\n  ttn.provision(appEui, appKey);\n\n  ttn.join(appEui, appKey);\n\n  ttn.join(appEui, appKey, 3);\n\n  ttn.join(appEui, appKey, 3, 60000);\n\n  ttn.join();\n\n  ttn.join(3);\n\n  ttn.join(3, 60000);\n\n  ttn.personalize(devAddr, nwkSKey, appSKey);\n\n  ttn.personalize();\n\n  ttn.showStatus();\n\n  ttn.onMessage(message);\n}\n\nvoid loop()\n{\n  byte payload[1] = {0x00};\n  ttn.sendBytes(payload, sizeof(payload));\n\n  ttn.sendBytes(payload, sizeof(payload), 2);\n\n  ttn.sendBytes(payload, sizeof(payload), 2, true);\n\n  ttn.poll();\n\n  ttn.poll(2);\n\n  ttn.poll(2, true);\n}\n\nvoid message(const uint8_t *payload, size_t length, port_t port) {}\n"
  },
  {
    "path": "test/verify",
    "content": "#!/bin/bash\nBOARD=$1\nINO=$2\nSTD=`arduino --verify --board ${BOARD} ${INO} 2>&1`\nEXIT=$?\necho \"${STD}\"\nif [[ $EXIT != 0 || $STD == *\": warning: \"* ]]\nthen\n    exit 1;\nfi"
  }
]