master d2e30f1e99aa cached
55 files
214.4 KB
60.4k tokens
126 symbols
1 requests
Download .txt
Showing preview only (229K chars total). Download the full file or copy to clipboard to get everything.
Repository: TheThingsNetwork/arduino-device-lib
Branch: master
Commit: d2e30f1e99aa
Files: 55
Total size: 214.4 KB

Directory structure:
gitextract_010a_2wt/

├── .editorconfig
├── .gitignore
├── .travis.yml
├── AUTHORS
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── docs/
│   ├── CayenneLPP.md
│   ├── RN2903A-programming.docx
│   ├── RN2903A-uart-bootloader.docx
│   ├── TheThingsMessage.md
│   └── TheThingsNetwork.md
├── examples/
│   ├── CayenneLPP/
│   │   └── CayenneLPP.ino
│   ├── CheckModule/
│   │   └── CheckModule.ino
│   ├── DeviceInfo/
│   │   └── DeviceInfo.ino
│   ├── PassThrough/
│   │   └── PassThrough.ino
│   ├── QuickStart/
│   │   ├── Converter.js
│   │   ├── Decoder.js
│   │   ├── Encoder.js
│   │   ├── QuickStart.ino
│   │   └── Validator.js
│   ├── Receive/
│   │   └── Receive.ino
│   ├── ReceiveClassC/
│   │   └── ReceiveClassC.ino
│   ├── SendABP/
│   │   └── SendABP.ino
│   ├── SendOTAA/
│   │   └── SendOTAA.ino
│   ├── Sensors/
│   │   ├── DHT/
│   │   │   └── DHT.ino
│   │   └── LightSensor/
│   │       └── LightSensor.ino
│   ├── TheThingsMessage/
│   │   ├── Receive/
│   │   │   └── Receive.ino
│   │   └── Send/
│   │       └── Send.ino
│   └── Workshop/
│       └── Workshop.ino
├── keywords.txt
├── library.properties
├── src/
│   ├── CayenneLPP.cpp
│   ├── CayenneLPP.h
│   ├── TheThingsMessage.cpp
│   ├── TheThingsMessage.h
│   ├── TheThingsNetwork.cpp
│   ├── TheThingsNetwork.h
│   ├── api/
│   │   ├── appData.proto
│   │   └── deviceData.proto
│   ├── appData.pb.c
│   ├── appData.pb.h
│   ├── deviceData.pb.c
│   ├── deviceData.pb.h
│   ├── pb.h
│   ├── pb_common.c
│   ├── pb_common.h
│   ├── pb_decode.c
│   ├── pb_decode.h
│   ├── pb_encode.c
│   └── pb_encode.h
└── test/
    ├── TheThingsMessage/
    │   └── TheThingsMessage.ino
    ├── TheThingsNetwork/
    │   └── TheThingsNetwork.ino
    └── verify

================================================
FILE CONTENTS
================================================

================================================
FILE: .editorconfig
================================================
# editorconfig.org
root = true

[*]
indent_style = space
indent_size = 2
insert_final_newline = true


================================================
FILE: .gitignore
================================================
.DS_Store
.vscode


================================================
FILE: .travis.yml
================================================
language: c
env:
  - ARDUINO_VERSION=1.6.13
before_install:
  - "/sbin/start-stop-daemon --start --quiet --pidfile /tmp/custom_xvfb_1.pid --make-pidfile --background --exec /usr/bin/Xvfb -- :1 -ac -screen 0 1280x1024x16"
  - sleep 3
  - export DISPLAY=:1.0
  - wget http://downloads.arduino.cc/arduino-$ARDUINO_VERSION-linux64.tar.xz
  - tar xf arduino-$ARDUINO_VERSION-linux64.tar.xz
  - sudo mv arduino-$ARDUINO_VERSION /usr/local/share/arduino
  - sudo ln -s /usr/local/share/arduino/arduino /usr/local/bin/arduino
install:
  - ln -s $PWD /usr/local/share/arduino/libraries/TheThingsNetwork
  - arduino --install-library "DHT sensor library:1.3.0,Adafruit Unified Sensor:1.0.2"
before_script:
  # Replace placeholders with actual frequency plan (on Mac OS folow -i by '')
  - find $PWD/examples -type f -name "*.ino" -exec sed -i 's/REPLACE_ME/TTN_FP_EU868/g' {} +
script:
  - test/verify arduino:avr:leonardo examples/SendABP/SendABP.ino
  - test/verify arduino:avr:leonardo examples/DeviceInfo/DeviceInfo.ino
  - test/verify arduino:avr:leonardo examples/TheThingsMessage/Receive/Receive.ino
  - test/verify arduino:avr:leonardo examples/TheThingsMessage/Send/Send.ino
  - test/verify arduino:avr:leonardo examples/PassThrough/PassThrough.ino
  - test/verify arduino:avr:leonardo examples/QuickStart/QuickStart.ino
  - test/verify arduino:avr:leonardo examples/Receive/Receive.ino
  - test/verify arduino:avr:leonardo examples/ReceiveClassC/ReceiveClassC.ino
  - test/verify arduino:avr:leonardo examples/SendOTAA/SendOTAA.ino
  - test/verify arduino:avr:leonardo examples/Sensors/DHT/DHT.ino
  - test/verify arduino:avr:leonardo examples/Sensors/LightSensor/LightSensor.ino
  - test/verify arduino:avr:leonardo examples/Workshop/Workshop.ino
  - test/verify arduino:avr:leonardo test/TheThingsMessage/TheThingsMessage.ino
  - test/verify arduino:avr:leonardo test/TheThingsNetwork/TheThingsNetwork.ino
notifications:
  email:
    on_success: change
    on_failure: change


================================================
FILE: AUTHORS
================================================
Johan Stokking <johan@thethingsnetwork.org>
Fokke Zandbergen <mail@fokkezb.nl>
Alessandro Blason <mrblason@gmail.com>
JP Meijers <git@jpmeijers.com>


================================================
FILE: CONTRIBUTING.md
================================================
## Contributing

We'd ❤️ to welcome your contribution. Please make sure your changes include:

1.  Examples: [examples](examples)
2.  Syntax highlighting: [keywords.txt](keywords.txt)
3.  Documentation: [docs](docs)
4.  Tests: [test](test)
5.  Verification of the examples and tests: [.travis.yml](.travis.yml)


================================================
FILE: LICENSE
================================================
The MIT License (MIT)

Copyright (c) 2016 The Things Network

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


================================================
FILE: Makefile
================================================
PROTOC = $(NANOPB)/generator-bin/protoc --proto_path=src/api --nanopb_out="-v:src"

.PHONY: proto

proto:
	$(PROTOC) src/api/*.proto


================================================
FILE: README.md
================================================
# The Things Network Arduino Library
[![Build Status](https://travis-ci.org/TheThingsNetwork/arduino-device-lib.svg?branch=master)](https://travis-ci.org/TheThingsNetwork/arduino-device-lib)

This 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).

> 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).

## Installation

* Install the library by [Using the Library Manager](https://www.arduino.cc/en/Guide/Libraries#toc3)
* **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.

## Documentation

* [The Things Network Documentation](https://www.thethingsnetwork.org/docs/devices/arduino/)
* API References:
    * [TheThingsNetwork](docs/TheThingsNetwork.md)
    * [TheThingsMessage](docs/TheThingsMessage.md)

## Examples

The 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**.


================================================
FILE: docs/CayenneLPP.md
================================================
# API Reference

The `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)

## Class: `CayenneLPP`

Include 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.

```c
#include <CayenneLPP.h>

CayenneLPP lpp(uint8_t size);
```

- `uint8_t size`: The maximum payload size to send, e.g. `51`.

## Example

```c
TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);
CayenneLPP lpp(51);

lpp.reset();
lpp.addTemperature(1, 22.5);
lpp.addBarometricPressure(2, 1073.21);
lpp.addGPS(3, 52.37365, 4.88650, 2);

ttn.sendBytes(lpp.getBuffer(), lpp.getSize());
```

See the [CayenneLPP](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/CayenneLPP/CayenneLPP.ino) example. 

## Method: `reset`

Resets the buffer.

```c
void reset(void);
```

## Method: `getSize`

Returns the size of the buffer.

```c
uint8_t getSize(void);
```

## Method: `getBuffer`

Returns a pointer to the buffer.

```c
uint8_t *getBuffer(void);
```

## Method: `copy`

Copies the internal buffer to a specified buffer and returns the copied size.

```c
uint8_t copy(uint8_t *buffer);
```

## Methods: `add...`

Add 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.

```c
uint8_t addDigitalInput(uint8_t channel, uint8_t value);
uint8_t addDigitalOutput(uint8_t channel, uint8_t value);

uint8_t addAnalogInput(uint8_t channel, float value);
uint8_t addAnalogOutput(uint8_t channel, float value);

uint8_t addLuminosity(uint8_t channel, uint16_t lux);
uint8_t addPresence(uint8_t channel, uint8_t value);
uint8_t addTemperature(uint8_t channel, float celsius);
uint8_t addRelativeHumidity(uint8_t channel, float rh);
uint8_t addAccelerometer(uint8_t channel, float x, float y, float z);
uint8_t addBarometricPressure(uint8_t channel, float hpa);
uint8_t addGyrometer(uint8_t channel, float x, float y, float z);
uint8_t addGPS(uint8_t channel, float latitude, float longitude, float meters);
```


================================================
FILE: docs/TheThingsMessage.md
================================================
# API Reference

## Class: `TheThingsMessage`
The `TheThingsMessage` class provides structs for sensor and application data you can encode and decode as bytes.

```c
#include <TheThingsMessage.h>
```

## Type: `devicedata_t`

Create a struct of this type using `api_DeviceData_init_default` as defaults.

```c
devicedata_t data = api_DeviceData_init_default;
```

Then in your `setup()` function select what fields of the struct should be included when encoding it as bytes:

```c
data.has_motion = true;
data.has_water = false;
data.has_temperature_celcius = true;
data.has_temperature_fahrenheit = true;
data.has_humidity = true;
```

In your `loop()` function read your sensors and set the fields of the struct:

```c
data.motion = true;
data.water = 682;
data.temperature_celcius = 30
data.temperature_fahrenheit = 86;
data.humidity = 97;
```

### Additional analog readings

You can also add other analog readings.

> **TODO:** Document how this works and include in example.

## Method: `encodeDeviceData`

Encode the message you want to send.

```c
static void encodeDeviceData(devicedata_t *data, byte **buffer, size_t *size);
```

- `devicedata_t *data`: Structure containing typical fields that devices send.
- `byte **buffer`: Bytes to send.
- `size_t *size`: The number of bytes to send.

Usage:

```c
byte *buffer;
size_t size;
TheThingsMessage::encodeDeviceData(&data, &buffer, &size);
```

## Method: `decodeAppData`

Decode the message you received.

```c
static bool decodeAppData(appdata_t *receiveData, const byte *payload, size_t length);
```

- `appdata_t *receiveData`: Structure containing all the message we can interpret.
- `const byte *payload`: Bytes received.
- `size_t *length`: The number of bytes.

Usage:

```c
const byte *payload;
size_t length;
TheThingsMessage::decodeAppData(&receiveData, payload, length);
```


================================================
FILE: docs/TheThingsNetwork.md
================================================
# API Reference

The `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.

## Class: `TheThingsNetwork`

Include 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.

```c
#include <TheThingsNetwork.h>

TheThingsNetwork ttn(Stream& modemStream, Stream& debugStream, fp_ttn_t fp, uint8_t sf = 7, uint8_t fsb = 2);
```

- `Stream& modemStream`: Stream for the LoRa modem ([see notes](https://www.thethingsnetwork.org/docs/devices/arduino/usage.html)).
- `Stream& debugStream`: Stream to write debug logs to ([see notes](https://www.thethingsnetwork.org/docs/devices/arduino/usage.html)).
- `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).
- `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`.
- `uint8_t fsb = 2`: Optional custom frequency subband. Can be `1` to `8`. Defaults to `2` (for US915).

## Method: `reset`

Performs a software reset of the RN module. This does not clear saved state, e.g. provisioned keys.

```c
void reset(bool adr);
```

- `bool adr`: Enable/disable Adaptive Data Rate.

## Method: `hardReset`

Performs 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.

```c
void hardReset(uint8_t resetPin);
```

- `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.

## Method: `getHardwareEui`

Gets the unique hardware EUI, often used as the DevEUI.

```c
size_t getHardwareEui(char *buffer, size_t size);
```

## Method: `getAppEui`

Gets the provisioned AppEUI. The AppEUI is set using `provision()` or `join()`.

```c
size_t getAppEui(char *buffer, size_t size);
```

## Method: `getVersion`

Gets the response from a `sys get ver` command (i.e. the hardware model, the the software version, etc.).

```c
size_t getVersion(char *buffer, size_t size);
```

## Method: `showStatus`

Writes information about the device and LoRa module to `debugStream`.

```c
void showStatus();
```

Will write something like:

```bash
EUI: 0004A30B001B7AD2
Battery: 3223
AppEUI: 70B3D57EF000001C
DevEUI: 0004A30B001B7AD2
Data Rate: 5
RX Delay 1: 1000
RX Delay 2: 2000
```

See the [DeviceInfo](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/DeviceInfo/DeviceInfo.ino) example.

## Method: `onMessage`

Sets 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.

```c
void onMessage(void (*cb)(const byte* payload, size_t length, port_t port));
```

- `const byte* payload`: Bytes received.
- `size_t length`: Number of bytes.
- `port_t port`: The port addressed.

See the [Receive](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/Receive/Receive.ino) example.

## Method: `join`

Activate the device via OTAA (default).

```c
bool join(const char *appEui, const char *appKey, int8_t retries = -1, uint32_t retryDelay = 10000, lorawan_class = CLASS_A);
bool join(int8_t retries = -1, uint32_t retryDelay = 10000);
```

- `const char *appEui`: Application EUI the device is registered to.
- `const char *appKey`: Application Key assigned to the device.
- `int8_t retries = -1`: Number of times to retry after failed or unconfirmed join. Defaults to `-1`, which means infinite.
- `uint32_t retryDelay = 10000`: Delay in ms between attempts. Defaults to 10 seconds.
- `lorawan_class = CLASS_A`: The LoRaWAN class to use for downlink message reception.

Returns `true` or `false` depending on whether it received confirmation that the activation was successful before the maximum number of attempts.

Call the method without the first two arguments if the device's LoRa module comes with pre-flashed values.

## Method: `personalize`

Activate the device via ABP.

```c
bool personalize(const char *devAddr, const char *nwkSKey, const char *appSKey, bool reset_first);
bool personalize();
```

- `const char *devAddr`: Device Address assigned to the device.
- `const char *nwkSKey`: Network Session Key assigned to the device for identification.
- `const char *appSKey`: Application Session Key assigned to the device for encryption.
- `bool reset_first`: Soft reset the module before performing any other action. Default is `true`.

Returns `true` or `false` depending on whether the activation was successful.

Call the method with no arguments if the device's LoRa module comes with pre-flashed values.

See the [SendABP](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/SendABP/SendABP.ino) example.

## Method: `setClass`

Change 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.

```c
bool setClass(lorawan_class p_lw_class);
```

- `lorawan_class p_lw_class`: The LoRaWAN class. Either `CLASS_A` or `CLASS_C`.

Returns `true` if the change was successful, or `false` if not successful.

The receive window only opens after a transmit. Therefore Class C receive will only start after calling `sendBytes()`.

See the [ReceiveClassC](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/ReceiveClassC/ReceiveClassC.ino) example.

## Method: `sendBytes`

Send a message to the application using raw bytes.

```c
ttn_response_t sendBytes(const byte* payload, size_t length, port_t port = 1, bool confirm = false, uint8_t sf = 0);
```

- `const byte* payload `: Bytes to send.
- `size_t length`: The number of bytes. Use `sizeof(payload)` to get it.
- `port_t port = 1`: The port to address. Defaults to `1`.
- `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`.
- `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.

Returns a success or error code and logs the related error message:

* `TTN_ERROR_SEND_COMMAND_FAILED`: Send command failed.
* `TTN_SUCCESSFUL_TRANSMISSION`: Successful transmission.
* `TTN_SUCCESSFUL_RECEIVE`: Successful transmission. Received \<N> bytes
* `TTN_UNSUCCESSFUL_RECEIVE`: if we sent a confirmed message but did not get an acknowledgment
* `TTN_ERROR_UNEXPECTED_RESPONSE`: Unexpected response: \<Response>

See the [SendOTAA](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/SendOTAA/SendOTAA.ino) example.

## Method: `poll`

Calls `sendBytes()` with `{ 0x00 }` as payload to poll for incoming messages.

```c
int8_t poll(port_t port = 1, bool confirm = false);
```

- `port_t port = 1`: The port to address. Defaults to `1`.
- `bool confirm = false`: Whether to ask for confirmation.
- `bool modem_only = false`: (only class A) Whether to avoid sending an empty frame and only listen to the modem's incoming message.

Returns the result of `sendBytes()`, with one difference:
* `TTN_UNSUCCESSFUL_RECEIVE`: In class C or class A `modem_only` poll, we only listened, and there was no incoming message.

The `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.

See the [Receive](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/Receive/Receive.ino) example.

## Method: `provision`

Sets the information needed to activate the device via OTAA, without actually activating. Call join() without the first 2 arguments to activate.

```c
bool provision(const char *appEui, const char *appKey, bool reset_first);
```

- `const char *appEui`: Application Identifier for the device.
- `const char *appKey`: Application Key assigned to the device.
- `bool reset_first`: Soft reset the module before performing any other action. Default is `true`.

## Method: `sleep`

Sleep the LoRa module for a specified number of milliseconds.

```c
void sleep(unsigned long mseconds);
```

- `unsigned long mseconds`: number of milliseconds to sleep.

## Method: `wake`

Wake up the LoRa module from sleep before the expiration of the defined time.

```c
void wake();
```

## Method: `linkCheck`

Sets 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.

```c
void linkCheck(uint16_t seconds);
```

- `uint16_t seconds`: the time interval in seconds. A value of 0 will disable the link check process.

## Method: `getLinkCheckGateways`

Gets the number of gateways that successfully received the last Link Check Request frame.

```c
uint8_t getLinkCheckGateways();
```

## Method: `getLinkCheckMargin`

Gets the demodulation margin as received in the last Link Check Answer frame.

```c
uint8_t getLinkCheckMargin();
```

# Additional for operation

## Method: `getVDD`

Returns 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.

```c
uint16_t getVDD();
```

## Method: `getStatus`

Returns 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`.

```c
enum ttn_modem_status_t getStatus()
```

Possible return codes are:

- `TTN_MODEM_READ_ERR` could not read out the status
- `TTN_MODEM_IDLE` modem idle, ready for next tx
- `TTN_MODEM_TX` modem transmitting
- `TTN_MODEM_BEFORE_RX` waiting time between tx and rx1 windows
- `TTN_MODEM_RX1` RX1 window open
- `TTN_MODEM_BEFORE_RX2` waiting time between the two rx windows
- `TTN_MODEM_RETRY_DELAY` waiting before retry again
- `TTN_MODEM_APB_DELAY` APB join delay
- `TTN_MODEM_C_RX1` RX1 window open in class C
- `TTN_MODEM_C_RX2` RX2 window open in class C


## Method: `getLastError`

Returns 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.

```c
ttn_response_code_t getLastError();
```

For 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.

Possible error codes are:

 - `TTN_OK` nothing actually went wrong.
 - `TTN_ERROR_BUSY` busy sending a message
 - `TTN_ERROR_FRAME_COUNTER_ERROR` if the frame counter rolled over
 - `TTN_ERROR_INVALID_CLASS` selected LoRaWan class is invalid
 - `TTN_ERROR_INVALID_LENGTH` data length is not available for the current configuration
 - `TTN_ERROR_INVALID_PARAMETER` invalid parameter specified
 - `TTN_ERROR_NO_KEY_INTITIALIZED` network keys not initialized
 - `TTN_ERROR_MAC_PAUSE` mac level has been paused
 - `TTN_ERROR_NO_KEY_MULTICAST` multicast keys not set
 - `TTN_ERROR_NO_FREE_CHANNEL` all channels exhausted their duty cycle, so we can not send
 - `TTN_ERROR_NOT_JOINED` modem did not join a network
 - `TTN_ERROR_SILENT` if the module is in a Silent Immediately state
 - `TTN_ERROR_ERR` other unspecified error 

## Method: `getFCU`

Returns 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.

```c
uint32_t getFCU();
```

## Method: `setFCU`

Sets the FCU as of above. The method returns true if successful.

```c
bool setFCU(uint32_t fcu);
```

## Method: `getFCD`

Returns 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.

```c
uint32_t getFCD();
```

## Method: `setFCD`

Sets the FCD as of above. The method returns true if successful.

```c
bool setFCD(uint32_t fcd);
```

## Method: `getDR`

Returns the data rate that the modem will use for the next uplink frame. If the readout is unsuccessful, the method returns -1.

```c
int8_t getDR();
```

## Method: `setDR`

Sets 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.

```c
bool setDR(uint8_t dr);
```

## Method: `getPowerIndex`

Returns the power index that the LoRa modem will use for the next uplink frame. If the readout is unsuccessful, the method returns -1.

```c
int8_t getPowerIndex();
```

## Method: `setPowerIndex`

Sets 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.

```c
bool setPowerIndex(uint8_t index);
```

## Method: `setChannel`

The 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.

```c
bool setChannel(uint8_t channel, uint32_t frequency = 0l, uint8_t dr_min = 255, uint8_t dr_max = 255);
```

Alternatively, you can only re-set the data rates for the channel by leaving (omitting) frequency to 0.
 
```c
setChannel(2, dr_min = 0, dr_max = 4);
```
  
Or, you can only re-set the frequency for the channel by leaving (omitting) dr_* to 255.

```c
setChannel(2, 863500000);
```

However, the whole configuration must have been set at least once to be successful in both cases.

## Method: `setRX2Channel`

In 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.

```c
bool setRx2Channel(uint32_t frequency, uint8_t dr);
```

## Method: `getChannelStatus`

The TTN module can store multiple channel configurations. This method returns true if the channel is enabled for transmission and/or receiving.

```c
bool getChannelStatus (uint8_t channel);
```

## Method: `setChannelStatus`

Sets 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.

```c
bool setChannelStatus (uint8_t channel, bool status);
```

## Method: `setChannelDCycle`

Sets 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.

```c
bool setChannelDCycle (uint8_t channel, float duty_cycle);
```

## Method: `setADR`

We 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.

```c
bool setADR(bool adr);
```

## Method: `setRX1Delay`

When 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.

```c
bool setRX1Delay(uint16_t delay);
```

## Method: `checkValidModuleConnected`

Checks 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.

```c
bool checkValidModuleConnected(bool autobaud_first);
```

- `bool autobaud_first`: Perform a call to `autoBaud()` before checking connection. Default is `false`.

Returns:

* `false` if no response was received (i.e. `needsHardReset` is `true`)
* `false` if the module is invalid (unsupported), i.e. **not** one of the following:
    * `RN2483`
    * `RN2483A`
    * `RN2903`
    * `RN2903AS`
* `true` if the module responded (i.e. `needsHardReset` is `false`) and is valid (supported).

See the [CheckModule](https://github.com/TheThingsNetwork/arduino-device-lib/blob/master/examples/CheckModule/CheckModule.ino) example.

# Additional for statistics 

## Method: `getRSSI`

Returns 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.

```c
int16_t getRSSI();
```

## Method: `getSNR`

Returns 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.

```c
int8_t getSNR();
```

## Method: `getFrequency`

Returns the channel frequency of the last received frame in `Hz`. If the readout is unsuccessful, the method returns 0.

```c
uint32_t getFrequency();
```

## Method: `getWatchDogTimer`

Returns 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.

```c
uint32_t getWatchDogTimer();
```

## Method: `getBW`

Returns the used channel bandwidth of the last received frame in `kHz`. If the readout is unsuccessful, the method returns 0.

```c
uint8_t getBW();
```

## Method: `getCR`

Returns the used code rate of the last received frame in `4/x`. If the readout is unsuccessful, the method returns 0.

```c
uint8_t getCR();
```

## Method: `getPower`

Returns the power of the last incoming transmission in `dBm`. If the readout is unsuccessful, the method returns -128.

```c
int8_t getPower();
```


================================================
FILE: examples/CayenneLPP/CayenneLPP.ino
================================================
#include <TheThingsNetwork.h>
#include <CayenneLPP.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);
CayenneLPP lpp(51);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);
}

void loop()
{
  debugSerial.println("-- LOOP");

  lpp.reset();
  lpp.addTemperature(1, 22.5);
  lpp.addBarometricPressure(2, 1073.21);
  lpp.addGPS(3, 52.37365, 4.88650, 2);

  // Send it off
  ttn.sendBytes(lpp.getBuffer(), lpp.getSize());

  delay(10000);
}


================================================
FILE: examples/CheckModule/CheckModule.ino
================================================
#include <TheThingsNetwork.h>

// Set your DevAddr, NwkSKey, AppSKey and the frequency plan
const char *devAddr = "00000000";
const char *nwkSKey = "00000000000000000000000000000000";
const char *appSKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  // RN2XX3 reset pin connected to Arduino pin 12
  pinMode(12, OUTPUT);
  digitalWrite(12, HIGH);
  // hard reset module and wait for startup
  debugSerial.println("-- CHECK COMM");
  ttn.resetHard(12);
  delay(100);
  // check if a valid module responded
  // (if no module is connected or wiring is bad, checkValidModuleConnected() will
  //  take about ~30s to return (another ~30s if autobaud_first is true))
  if(!ttn.checkValidModuleConnected(true))
  {
    if(ttn.needsHardReset)
    {
      debugSerial.println("Module unresponsive, please power cycle or hard reset board!");
    }
    else
    {
      debugSerial.println("Module unsupported!");       // module must be RN2483, RN2483A, RN2903, RN2903AS
    }
    while(true)                                         // stop code execution
    {
      ;
    }
  }

  // do an ABP join
  debugSerial.println("-- PERSONALIZE");
  // false is added as fourth argument to the personalize() call so that it
  // does not perform a soft reset, because the module was already hard reset before via pin 12.
  ttn.personalize(devAddr, nwkSKey, appSKey, false);

  debugSerial.println("-- STATUS");
  ttn.showStatus();
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Prepare payload of 1 byte to indicate LED status
  byte payload[1];
  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;

  // Send it off
  ttn.sendBytes(payload, sizeof(payload));

  delay(10000);
}


================================================
FILE: examples/DeviceInfo/DeviceInfo.ino
================================================
#include <TheThingsNetwork.h>

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);
}

void loop()
{
  debugSerial.println("Device Information");
  debugSerial.println();
  ttn.showStatus();
  debugSerial.println();
  debugSerial.println("Use the EUI to register the device for OTAA");
  debugSerial.println("-------------------------------------------");
  debugSerial.println();

  delay(10000);
}


================================================
FILE: examples/PassThrough/PassThrough.ino
================================================
/**
 * Use this sketch to talk directly to the LoRa module.
 * 
 * In Serial Monitor, select "Both NL & CR" and "115200 baud" in
 * the bottom right dropdowns and send command a command like:
 *
 * mac get deveui
 * sys reset
 */

#define loraSerial Serial1
#define debugSerial Serial

void setup()
{
  while (!debugSerial || !loraSerial)
    ;

  debugSerial.begin(115200);
  delay(1000);

  loraSerial.begin(57600);
}

void loop()
{
  while (debugSerial.available())
  {
    loraSerial.write(debugSerial.read());
  }
  while (loraSerial.available())
  {
    debugSerial.write(loraSerial.read());
  }
}


================================================
FILE: examples/QuickStart/Converter.js
================================================
function Converter(decoded, port) {
  // Merge, split or otherwise
  // mutate decoded fields.
  var converted = decoded;
    
  if (port === 1 && (converted.led === 0 || converted.led === 1)) {
    converted.led = Boolean(converted.led);
  }
    
  return converted;
}


================================================
FILE: examples/QuickStart/Decoder.js
================================================
function Decoder(bytes, port) {
  // Decode an uplink message from a buffer
  // (array) of bytes to an object of fields.
  var decoded = {};
    
  if (port === 1) {
    decoded.led = bytes[0];
  }
    
  return decoded;
}


================================================
FILE: examples/QuickStart/Encoder.js
================================================
function Encoder(object, port) {
  // Encode downlink messages sent as
  // object to an array or buffer of bytes.
  var bytes = [];
    
  if (port === 1) {
    bytes[0] = object.led ? 1 : 0;
  }
    
  return bytes;
}


================================================
FILE: examples/QuickStart/QuickStart.ino
================================================
#include <TheThingsNetwork.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  // Set callback for incoming messages
  ttn.onMessage(message);

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Prepare payload of 1 byte to indicate LED status
  byte payload[1];
  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;

  // Send it off
  ttn.sendBytes(payload, sizeof(payload));

  delay(10000);
}

void message(const byte *payload, size_t length, port_t port)
{
  debugSerial.println("-- MESSAGE");

  // Only handle messages of a single byte
  if (length != 1)
  {
    return;
  }

  if (payload[0] == 0)
  {
    debugSerial.println("LED: off");
    digitalWrite(LED_BUILTIN, LOW);
  }
  else if (payload[0] == 1)
  {
    debugSerial.println("LED: on");
    digitalWrite(LED_BUILTIN, HIGH);
  }
}


================================================
FILE: examples/QuickStart/Validator.js
================================================
function Validator(converted, port) {
  // Return false if the decoded, converted
  // message is invalid and should be dropped.
    
  if (port === 1 && typeof converted.led !== 'boolean') {
    return false;
  }
    
  return true;
}


================================================
FILE: examples/Receive/Receive.ino
================================================
#include <TheThingsNetwork.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  // Set callback for incoming messages
  ttn.onMessage(message);

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Send single byte to poll for incoming messages
  ttn.poll();

  delay(10000);
}

void message(const uint8_t *payload, size_t size, port_t port)
{
  debugSerial.println("-- MESSAGE");
  debugSerial.print("Received " + String(size) + " bytes on port " + String(port) + ":");

  for (int i = 0; i < size; i++)
  {
    debugSerial.print(" " + String(payload[i]));
  }

  debugSerial.println();
}


================================================
FILE: examples/ReceiveClassC/ReceiveClassC.ino
================================================
#include <TheThingsNetwork.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  // Set callback for incoming messages
  ttn.onMessage(message);

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey, -1, 10000, CLASS_C);

  // Class C RX only takes affect after a TX
  uint8_t payload[] = {0x00};
  ttn.sendBytes(payload, 1);
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Check for received data.
  ttn.poll();

  // When using Class C we can poll as quickly as we can, as we only check the serial buffer.
  //delay(1000);
}

void message(const uint8_t *payload, size_t size, port_t port)
{
  debugSerial.println("-- MESSAGE");
  debugSerial.print("Received " + String(size) + " bytes on port " + String(port) + ":");

  for (int i = 0; i < size; i++)
  {
    debugSerial.print(" " + String(payload[i]));
  }

  debugSerial.println();
}


================================================
FILE: examples/SendABP/SendABP.ino
================================================
#include <TheThingsNetwork.h>

// Set your DevAddr, NwkSKey, AppSKey and the frequency plan
const char *devAddr = "00000000";
const char *nwkSKey = "00000000000000000000000000000000";
const char *appSKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  debugSerial.println("-- PERSONALIZE");
  ttn.personalize(devAddr, nwkSKey, appSKey);

  debugSerial.println("-- STATUS");
  ttn.showStatus();
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Prepare payload of 1 byte to indicate LED status
  byte payload[1];
  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;

  // Send it off
  ttn.sendBytes(payload, sizeof(payload));

  delay(10000);
}


================================================
FILE: examples/SendOTAA/SendOTAA.ino
================================================
#include <TheThingsNetwork.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Prepare payload of 1 byte to indicate LED status
  byte payload[1];
  payload[0] = (digitalRead(LED_BUILTIN) == HIGH) ? 1 : 0;

  // Send it off
  ttn.sendBytes(payload, sizeof(payload));

  delay(10000);
}


================================================
FILE: examples/Sensors/DHT/DHT.ino
================================================
#include <TheThingsNetwork.h>

// First install "DHT sensor library" via the Library Manager
#include <DHT.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

#define DHTPIN 2

//Choose your DHT sensor moddel
//#define DHTTYPE DHT11
//#define DHTTYPE DHT21
#define DHTTYPE DHT22

DHT dht(DHTPIN, DHTTYPE);

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);

  dht.begin();
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Read sensor values and multiply by 100 to effictively have 2 decimals
  uint16_t humidity = dht.readHumidity(false) * 100;

  // false: Celsius (default)
  // true: Farenheit
  uint16_t temperature = dht.readTemperature(false) * 100;

  // Split both words (16 bits) into 2 bytes of 8
  byte payload[4];
  payload[0] = highByte(temperature);
  payload[1] = lowByte(temperature);
  payload[2] = highByte(humidity);
  payload[3] = lowByte(humidity);

  debugSerial.print("Temperature: ");
  debugSerial.println(temperature);
  debugSerial.print("Humidity: ");
  debugSerial.println(humidity);

  ttn.sendBytes(payload, sizeof(payload));

  delay(20000);
}


================================================
FILE: examples/Sensors/LightSensor/LightSensor.ino
================================================
#include <TheThingsNetwork.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

//define AnalogPin for sensor
#define LightPin A0

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  pinMode(LightPin, INPUT);

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);

  ttn.showStatus();
  debugSerial.println("Setup for The Things Network complete");
}

void loop()
{

  uint16_t light = analogRead(LightPin);

  // Split word (16 bits) into 2 bytes of 8
  byte payload[2];
  payload[0] = highByte(light);
  payload[1] = lowByte(light);

  debugSerial.print("Transmitting Light level: ");
  debugSerial.println(light);

  ttn.sendBytes(payload, sizeof(payload));

  delay(20000);
}


================================================
FILE: examples/TheThingsMessage/Receive/Receive.ino
================================================
#include <TheThingsNetwork.h>
#include <TheThingsMessage.h>

// Set your AppEUI and  AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

devicedata_t data = api_DeviceData_init_default;

void setup()
{
  pinMode(LED_BUILTIN, INPUT);

  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);

  ttn.onMessage(message);

  data.has_motion = true;
  data.has_water = true;
}

void loop()
{
  // Read sensors
  data.motion = digitalRead(LED_BUILTIN) == HIGH;
  data.water = 682;

  // Encode data
  byte *buffer;
  size_t size;

  // Send standard message on port 100
  TheThingsMessage::encodeDeviceData(&data, &buffer, &size);
  ttn.sendBytes(buffer, size, 100);

  delay(10000);
}

void message(const uint8_t *payload, size_t length, port_t port)
{
  //standard message always received on port 100 or more
  if (port >= 100)
  {
    appdata_t appData = api_AppData_init_default;
    TheThingsMessage::decodeAppData(&appData, payload, length);
  }
}


================================================
FILE: examples/TheThingsMessage/Send/Send.ino
================================================
#include <TheThingsNetwork.h>
#include <TheThingsMessage.h>

// Set your AppEUI and AppKey
const char *appEui = "0000000000000000";
const char *appKey = "00000000000000000000000000000000";

#define loraSerial Serial1
#define debugSerial Serial

// Replace REPLACE_ME with TTN_FP_EU868 or TTN_FP_US915
#define freqPlan REPLACE_ME

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

devicedata_t data = api_DeviceData_init_default;

void setup()
{
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  debugSerial.println("-- STATUS");
  ttn.showStatus();

  debugSerial.println("-- JOIN");
  ttn.join(appEui, appKey);

  // Select what fields to include in the encoded message
  data.has_motion = true;
  data.has_water = false;
  data.has_temperature_celcius = true;
  data.has_temperature_fahrenheit = true;
  data.has_humidity = true;
}

void loop()
{
  debugSerial.println("-- LOOP");

  // Read the sensors
  data.motion = true;
  data.water = 682;
  data.temperature_celcius = 30;
  data.temperature_fahrenheit = 86;
  data.humidity = 97;

  // Encode the selected fields of the struct as bytes
  byte *buffer;
  size_t size;
  TheThingsMessage::encodeDeviceData(&data, &buffer, &size);

  ttn.sendBytes(buffer, size);

  delay(10000);
}


================================================
FILE: examples/Workshop/Workshop.ino
================================================
#include <TheThingsNetwork.h>

// Before your start, make sure that in the Tools menu, your Board and your
// Port is set to Arduino Leonardo

// After you registered your ABP device, go to The Things Network Dashboard
// and copy the Device Addr, Network Session Key and App Session Key

// Set your Device Address, for example: "1C55B133";
const char *devAddr = "00000000";

// Set your Network Session Key, for example: "0C11F84C5E4315CCDE50AB31C430BBE5";
// This is used by the network to identify your device
const char *nwkSKey = "00000000000000000000000000000000";

// Set your Application Session Key, for example: "6C250A6B559B1BA0A51696ED20E3CF56";
// This is used by the network for encryption
const char *appSKey = "00000000000000000000000000000000";

//Set your frequency plan by replacing REPLACE_ME by TTN_FP_EU868 for Europe or TTN_FP_US915 for the United States
#define freqPlan REPLACE_ME

#define loraSerial Serial1
#define debugSerial Serial

TheThingsNetwork ttn(loraSerial, debugSerial, freqPlan);

void setup()
{
  // Set up the serial interfaces for the debugging serial monitor and LoRa module
  loraSerial.begin(57600);
  debugSerial.begin(9600);

  // Wait a maximum of 10s for Serial Monitor
  while (!debugSerial && millis() < 10000)
    ;

  // Here we activate the device with your address and keys
  ttn.personalize(devAddr, nwkSKey, appSKey);

  // Show the status on the debugging serial monitor
  ttn.showStatus();
}

void loop()
{
  // Create a buffer with three bytes
  byte payload[3] = {0x01, 0x02, 0x03};

  // Send it to the network
  ttn.sendBytes(payload, sizeof(payload));

  // Wait 10 seconds
  delay(10000);
}


================================================
FILE: keywords.txt
================================================
#######################################
# Syntax Coloring Map
#######################################

#######################################
# Class (KEYWORD1)
#######################################

TheThingsNetwork	KEYWORD1
TheThingsMessage	KEYWORD1
TheThingsNode	KEYWORD1

ttn_port_t	KEYWORD1
ttn_response_t	KEYWORD1
ttn_fp_t	KEYWORD1
lorawan_class_t	KEYWORD1

#######################################
# Methods and Functions (KEYWORD2)
#######################################

showStatus	KEYWORD2
onMessage	KEYWORD2
provision	KEYWORD2
join	KEYWORD2
personalize	KEYWORD2
setClass	KEYWORD2
sendBytes	KEYWORD2
poll	KEYWORD2

encodeSensorData	KEYWORD2
decodeAppData	KEYWORD2

getLight	KEYWORD2
configLight	KEYWORD2
getTemperatureAsInt	KEYWORD2
getTemperatureAsFloat	KEYWORD2
configTemperature	KEYWORD2
onTemperatureAlert	KEYWORD2
configTemperatureAlert	KEYWORD2
onMotionStart	KEYWORD2
onMotionStop	KEYWORD2
isMoving	KEYWORD2
configMotion	KEYWORD2
onButtonPress	KEYWORD2
onButtonRelease	KEYWORD2
isButtonPressed	KEYWORD2
getRed	KEYWORD2
getGreen	KEYWORD2
getBlue	KEYWORD2
getColor	KEYWORD2
colorToString	KEYWORD2
setRGB	KEYWORD2
setRed	KEYWORD2
setGreen	KEYWORD2
setBlue	KEYWORD2
setColor	KEYWORD2
getUSB	KEYWORD2
getBattery	KEYWORD2
getVDD	KEYWORD2

encodeDeviceData	KEYWORD2
decodeAppData	KEYWORD2

#######################################
# Constants (LITERAL1)
#######################################

TTN_DEFAULT_SF	LITERAL1
TTN_DEFAULT_FSB	LITERAL1
TTN_RETX	LITERAL1
TTN_PWRIDX_868	LITERAL1
TTN_PWRIDX_915	LITERAL1
TTN_BUFFER_SIZE	LITERAL1
TTN_ERROR_SEND_COMMAND_FAILED	LITERAL1
TTN_ERROR_UNEXPECTED_RESPONSE	LITERAL1
TTN_SUCCESSFUL_TRANSMISSION	LITERAL1
TTN_SUCCESSFUL_RECEIVE	LITERAL1
TTN_FP_EU868	LITERAL1
TTN_FP_US915	LITERAL1
TTN_FP_AS920_923	LITERAL1
TTN_FP_AS923_925	LITERAL1
TTN_FP_KR920_923	LITERAL1

TTN_PIN_LED	LITERAL1

TTN_COLOR	LITERAL1
TTN_RED	LITERAL1
TTN_GREEN	LITERAL1
TTN_BLUE	LITERAL1
TTN_YELLOW	LITERAL1
TTN_CYAN	LITERAL1
TTN_MAGENTA	LITERAL1
TTN_WHITE	LITERAL1
TTN_BLACK	LITERAL1

CLASS_A	LITERAL1
CLASS_B	LITERAL1
CLASS_C	LITERAL1


================================================
FILE: library.properties
================================================
name=TheThingsNetwork
version=2.7.2
author=The Things Network
maintainer=Johan Stokking <johan@thethingsnetwork.org>
sentence=The Things Network Arduino Library.
paragraph=Compatible with any Microchip RN2483 and RN2903 device.
category=Communication
url=https://github.com/TheThingsNetwork/arduino-device-lib
architectures=*
includes=TheThingsNetwork.h


================================================
FILE: src/CayenneLPP.cpp
================================================
// Adapted from https://developer.mbed.org/teams/myDevicesIoT/code/Cayenne-LPP/

// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#include "CayenneLPP.h"

CayenneLPP::CayenneLPP(uint8_t size) : maxsize(size)
{
  buffer = (uint8_t *)malloc(size);
  cursor = 0;
}

CayenneLPP::~CayenneLPP(void)
{
  free(buffer);
}

void CayenneLPP::reset(void)
{
  cursor = 0;
}

uint8_t CayenneLPP::getSize(void)
{
  return cursor;
}

uint8_t *CayenneLPP::getBuffer(void)
{
  //    uint8_t[cursor] result;
  //    memcpy(result, buffer, cursor);
  //    return result;
  return buffer;
}

uint8_t CayenneLPP::copy(uint8_t *dst)
{
  memcpy(dst, buffer, cursor);
  return cursor;
}

uint8_t CayenneLPP::addDigitalInput(uint8_t channel, uint8_t value)
{
  if ((cursor + LPP_DIGITAL_INPUT_SIZE) > maxsize)
  {
    return 0;
  }
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_DIGITAL_INPUT;
  buffer[cursor++] = value;

  return cursor;
}

uint8_t CayenneLPP::addDigitalOutput(uint8_t channel, uint8_t value)
{
  if ((cursor + LPP_DIGITAL_OUTPUT_SIZE) > maxsize)
  {
    return 0;
  }
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_DIGITAL_OUTPUT;
  buffer[cursor++] = value;

  return cursor;
}

uint8_t CayenneLPP::addAnalogInput(uint8_t channel, float value)
{
  if ((cursor + LPP_ANALOG_INPUT_SIZE) > maxsize)
  {
    return 0;
  }

  int16_t val = value * 100;
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_ANALOG_INPUT;
  buffer[cursor++] = val >> 8;
  buffer[cursor++] = val;

  return cursor;
}

uint8_t CayenneLPP::addAnalogOutput(uint8_t channel, float value)
{
  if ((cursor + LPP_ANALOG_OUTPUT_SIZE) > maxsize)
  {
    return 0;
  }
  int16_t val = value * 100;
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_ANALOG_OUTPUT;
  buffer[cursor++] = val >> 8;
  buffer[cursor++] = val;

  return cursor;
}

uint8_t CayenneLPP::addLuminosity(uint8_t channel, uint16_t lux)
{
  if ((cursor + LPP_LUMINOSITY_SIZE) > maxsize)
  {
    return 0;
  }
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_LUMINOSITY;
  buffer[cursor++] = lux >> 8;
  buffer[cursor++] = lux;

  return cursor;
}

uint8_t CayenneLPP::addPresence(uint8_t channel, uint8_t value)
{
  if ((cursor + LPP_PRESENCE_SIZE) > maxsize)
  {
    return 0;
  }
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_PRESENCE;
  buffer[cursor++] = value;

  return cursor;
}

uint8_t CayenneLPP::addTemperature(uint8_t channel, float celsius)
{
  if ((cursor + LPP_TEMPERATURE_SIZE) > maxsize)
  {
    return 0;
  }
  int16_t val = celsius * 10;
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_TEMPERATURE;
  buffer[cursor++] = val >> 8;
  buffer[cursor++] = val;

  return cursor;
}

uint8_t CayenneLPP::addRelativeHumidity(uint8_t channel, float rh)
{
  if ((cursor + LPP_RELATIVE_HUMIDITY_SIZE) > maxsize)
  {
    return 0;
  }
  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_RELATIVE_HUMIDITY;
  buffer[cursor++] = rh * 2;

  return cursor;
}

uint8_t CayenneLPP::addAccelerometer(uint8_t channel, float x, float y, float z)
{
  if ((cursor + LPP_ACCELEROMETER_SIZE) > maxsize)
  {
    return 0;
  }
  int16_t vx = x * 1000;
  int16_t vy = y * 1000;
  int16_t vz = z * 1000;

  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_ACCELEROMETER;
  buffer[cursor++] = vx >> 8;
  buffer[cursor++] = vx;
  buffer[cursor++] = vy >> 8;
  buffer[cursor++] = vy;
  buffer[cursor++] = vz >> 8;
  buffer[cursor++] = vz;

  return cursor;
}

uint8_t CayenneLPP::addBarometricPressure(uint8_t channel, float hpa)
{
  if ((cursor + LPP_BAROMETRIC_PRESSURE_SIZE) > maxsize)
  {
    return 0;
  }
  int16_t val = hpa * 10;

  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_BAROMETRIC_PRESSURE;
  buffer[cursor++] = val >> 8;
  buffer[cursor++] = val;

  return cursor;
}

uint8_t CayenneLPP::addGyrometer(uint8_t channel, float x, float y, float z)
{
  if ((cursor + LPP_GYROMETER_SIZE) > maxsize)
  {
    return 0;
  }
  int16_t vx = x * 100;
  int16_t vy = y * 100;
  int16_t vz = z * 100;

  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_GYROMETER;
  buffer[cursor++] = vx >> 8;
  buffer[cursor++] = vx;
  buffer[cursor++] = vy >> 8;
  buffer[cursor++] = vy;
  buffer[cursor++] = vz >> 8;
  buffer[cursor++] = vz;

  return cursor;
}

uint8_t CayenneLPP::addGPS(uint8_t channel, float latitude, float longitude, float meters)
{
  if ((cursor + LPP_GPS_SIZE) > maxsize)
  {
    return 0;
  }
  int32_t lat = latitude * 10000;
  int32_t lon = longitude * 10000;
  int32_t alt = meters * 100;

  buffer[cursor++] = channel;
  buffer[cursor++] = LPP_GPS;

  buffer[cursor++] = lat >> 16;
  buffer[cursor++] = lat >> 8;
  buffer[cursor++] = lat;
  buffer[cursor++] = lon >> 16;
  buffer[cursor++] = lon >> 8;
  buffer[cursor++] = lon;
  buffer[cursor++] = alt >> 16;
  buffer[cursor++] = alt >> 8;
  buffer[cursor++] = alt;

  return cursor;
}


================================================
FILE: src/CayenneLPP.h
================================================
// Adapted from https://developer.mbed.org/teams/myDevicesIoT/code/Cayenne-LPP/

// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef _CAYENNE_LPP_H_
#define _CAYENNE_LPP_H_

#include <Arduino.h>

//LPP_BATTERY = // TODO Unsupported in IPSO Smart Object
//LPP_PROXIMITY = // TODO Unsupported in IPSO Smart Object

#define LPP_DIGITAL_INPUT 0         // 1 byte
#define LPP_DIGITAL_OUTPUT 1        // 1 byte
#define LPP_ANALOG_INPUT 2          // 2 bytes, 0.01 signed
#define LPP_ANALOG_OUTPUT 3         // 2 bytes, 0.01 signed
#define LPP_LUMINOSITY 101          // 2 bytes, 1 lux unsigned
#define LPP_PRESENCE 102            // 1 byte, 1
#define LPP_TEMPERATURE 103         // 2 bytes, 0.1°C signed
#define LPP_RELATIVE_HUMIDITY 104   // 1 byte, 0.5% unsigned
#define LPP_ACCELEROMETER 113       // 2 bytes per axis, 0.001G
#define LPP_BAROMETRIC_PRESSURE 115 // 2 bytes 0.1 hPa Unsigned
#define LPP_GYROMETER 134           // 2 bytes per axis, 0.01 °/s
#define LPP_GPS 136                 // 3 byte lon/lat 0.0001 °, 3 bytes alt 0.01 meter

// Data ID + Data Type + Data Size
#define LPP_DIGITAL_INPUT_SIZE 3       // 1 byte
#define LPP_DIGITAL_OUTPUT_SIZE 3      // 1 byte
#define LPP_ANALOG_INPUT_SIZE 4        // 2 bytes, 0.01 signed
#define LPP_ANALOG_OUTPUT_SIZE 4       // 2 bytes, 0.01 signed
#define LPP_LUMINOSITY_SIZE 4          // 2 bytes, 1 lux unsigned
#define LPP_PRESENCE_SIZE 3            // 1 byte, 1
#define LPP_TEMPERATURE_SIZE 4         // 2 bytes, 0.1°C signed
#define LPP_RELATIVE_HUMIDITY_SIZE 3   // 1 byte, 0.5% unsigned
#define LPP_ACCELEROMETER_SIZE 8       // 2 bytes per axis, 0.001G
#define LPP_BAROMETRIC_PRESSURE_SIZE 4 // 2 bytes 0.1 hPa Unsigned
#define LPP_GYROMETER_SIZE 8           // 2 bytes per axis, 0.01 °/s
#define LPP_GPS_SIZE 11                // 3 byte lon/lat 0.0001 °, 3 bytes alt 0.01 meter

class CayenneLPP
{
public:
  CayenneLPP(uint8_t size);
  ~CayenneLPP();

  void reset(void);
  uint8_t getSize(void);
  uint8_t *getBuffer(void);
  uint8_t copy(uint8_t *buffer);

  uint8_t addDigitalInput(uint8_t channel, uint8_t value);
  uint8_t addDigitalOutput(uint8_t channel, uint8_t value);

  uint8_t addAnalogInput(uint8_t channel, float value);
  uint8_t addAnalogOutput(uint8_t channel, float value);

  uint8_t addLuminosity(uint8_t channel, uint16_t lux);
  uint8_t addPresence(uint8_t channel, uint8_t value);
  uint8_t addTemperature(uint8_t channel, float celsius);
  uint8_t addRelativeHumidity(uint8_t channel, float rh);
  uint8_t addAccelerometer(uint8_t channel, float x, float y, float z);
  uint8_t addBarometricPressure(uint8_t channel, float hpa);
  uint8_t addGyrometer(uint8_t channel, float x, float y, float z);
  uint8_t addGPS(uint8_t channel, float latitude, float longitude, float meters);

private:
  uint8_t *buffer;
  uint8_t maxsize;
  uint8_t cursor;
};

#endif


================================================
FILE: src/TheThingsMessage.cpp
================================================
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#include "TheThingsMessage.h"

bool TheThingsMessage::decodeAppData(appdata_t *receiveData, const byte *payload, size_t length)
{
  pb_istream_t stream = pb_istream_from_buffer(payload, length);
  if (!pb_decode(&stream, api_AppData_fields, receiveData))
  {
    return false;
  }
#ifdef LED_BUILTIN
  receiveData->light ? digitalWrite(LED_BUILTIN, HIGH) : digitalWrite(LED_BUILTIN, LOW);
#endif
  return true;
}

void TheThingsMessage::encodeDeviceData(devicedata_t *data, byte **buffer, size_t *size)
{
  byte message[TTN_BUFFER_SIZE];

  pb_ostream_t sendStream = pb_ostream_from_buffer(message, sizeof(message));
  pb_encode(&sendStream, api_DeviceData_fields, data);
  *buffer = message;
  *size = sendStream.bytes_written;
}


================================================
FILE: src/TheThingsMessage.h
================================================
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef _THETHINGSMESSAGE_H_
#define _THETHINGSMESSAGE_H_

#include "TheThingsNetwork.h"
#include "pb.h"
#include "pb_encode.h"
#include "pb_decode.h"
#include "deviceData.pb.h"
#include "appData.pb.h"

typedef api_DeviceData devicedata_t;
typedef api_AppData appdata_t;

class TheThingsMessage
{
public:
  static void encodeDeviceData(devicedata_t *data, uint8_t **buffer, size_t *size);
  static bool decodeAppData(appdata_t *receiveData, const uint8_t *payload, size_t size);
};

#endif


================================================
FILE: src/TheThingsNetwork.cpp
================================================
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#include "TheThingsNetwork.h"

#define debugPrintLn(...)                \
  {                                      \
    if (debugStream)                     \
      debugStream->println(__VA_ARGS__); \
  }
#define debugPrint(...)                \
  {                                    \
    if (debugStream)                   \
      debugStream->print(__VA_ARGS__); \
  }

#define TTN_HEX_CHAR_TO_NIBBLE(c) ((c >= 'A') ? (c - 'A' + 0x0A) : (c - '0'))
#define TTN_HEX_PAIR_TO_BYTE(h, l) ((TTN_HEX_CHAR_TO_NIBBLE(h) << 4) + TTN_HEX_CHAR_TO_NIBBLE(l))

const char ok[] PROGMEM = "ok";
const char on[] PROGMEM = "on";
const char off[] PROGMEM = "off";
const char accepted[] PROGMEM = "accepted";
const char mac_tx_ok[] PROGMEM = "mac_tx_ok";
const char mac_rx[] PROGMEM = "mac_rx";
const char mac_err[] PROGMEM = "mac_err";
const char rn2483[] PROGMEM = "RN2483";
const char rn2483a[] PROGMEM = "RN2483A";
const char rn2903[] PROGMEM = "RN2903";
const char rn2903as[] PROGMEM = "RN2903AS";

const char *const compare_table[] PROGMEM = {ok, on, off, accepted, mac_tx_ok, mac_rx, mac_err, rn2483, rn2483a, rn2903, rn2903as};

#define CMP_OK 0
#define CMP_ON 1
#define CMP_OFF 2
#define CMP_ACCEPTED 3
#define CMP_MAC_TX_OK 4
#define CMP_MAC_RX 5
#define CMP_MAC_ERR 6
#define CMP_RN2483 7
#define CMP_RN2483A 8
#define CMP_RN2903 9
#define CMP_RN2903AS 10

// CMP OK
const char busy[] PROGMEM = "busy";
const char fram_counter_err_rejoin_needed[] PROGMEM = "fram_counter_err_rejoin_needed";
const char invalid_class[] PROGMEM = "invalid_class";
const char invalid_data_len[] PROGMEM = "invalid_data_len";
const char invalid_param[] PROGMEM = "invalid_param";
const char keys_not_init[] PROGMEM = "keys_not_init";
const char mac_paused[] PROGMEM = "mac_paused";
const char multicast_keys_not_set[] PROGMEM = "multicast_keys_not_set";
const char no_free_ch[] PROGMEM = "no_free_ch";
const char not_joined[] PROGMEM = "not_joined";
const char silent[] PROGMEM = "silent";
const char err[] PROGMEM = "err";

const 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};

#define CMP_ERR_OK 0
#define CMP_ERR_BUSY 1
#define CMP_ERR_FRMCNT 2
#define CMP_ERR_INVCLS 3
#define CMP_ERR_INVDLEN 4
#define CMP_ERR_INVPAR 5
#define CMP_ERR_NKEYINT 6
#define CMP_ERR_MACPAUSE 7
#define CMP_ERR_NKYMLTCST 8
#define CMP_ERR_NFRCHN 9
#define CMP_ERR_NJOIN 10
#define CMP_ERR_SILENT 11
#define CMP_ERR_ERR 12

#define CMP_ERR_LAST CMP_ERR_ERR

#define SENDING "Sending: "
#define SEND_MSG "\r\n"

const char eui[] PROGMEM = "EUI: ";
const char battery[] PROGMEM = "Battery: ";
const char appEui[] PROGMEM = "AppEUI: ";
const char devEui[] PROGMEM = "DevEUI: ";
const char band[] PROGMEM = "Band: ";
const char data_rate[] PROGMEM = "Data Rate: ";
const char rx_delay_1[] PROGMEM = "RX Delay 1: ";
const char rx_delay_2[] PROGMEM = "RX Delay 2: ";
const char version[] PROGMEM = "Version: ";
const char model[] PROGMEM = "Model: ";
const char devaddr[] PROGMEM = "DevAddr: ";

const char *const show_table[] PROGMEM = {eui, battery, appEui, devEui, band, data_rate, rx_delay_1, rx_delay_2, version, model, devaddr};

#define SHOW_EUI 0
#define SHOW_BATTERY 1
#define SHOW_APPEUI 2
#define SHOW_DEVEUI 3
#define SHOW_BAND 4
#define SHOW_DATA_RATE 5
#define SHOW_RX_DELAY_1 6
#define SHOW_RX_DELAY_2 7
#define SHOW_VERSION 8
#define SHOW_MODEL 9
#define SHOW_DEVADDR 10

const char invalid_sf[] PROGMEM = "Invalid SF";
const char invalid_fp[] PROGMEM = "Invalid frequency plan";
const char unexpected_response[] PROGMEM = "Unexpected response: ";
const char send_command_failed[] PROGMEM = "Send command failed";
const char join_failed[] PROGMEM = "Send join command failed";
const char join_not_accepted[] PROGMEM = "Join not accepted: ";
const char personalize_not_accepted[] PROGMEM = "Personalize not accepted";
const char response_is_not_ok[] PROGMEM = "Response is not OK: ";
const char error_key_length[] PROGMEM = "One or more keys are of invalid length.";
const char check_configuration[] PROGMEM = "Check your coverage, keys and backend status.";
const char no_response[] PROGMEM =  "No response from RN module.";
const char invalid_module[] PROGMEM = "Invalid module (must be RN2xx3[xx]).";

const 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};

#define ERR_INVALID_SF 0
#define ERR_INVALID_FP 1
#define ERR_UNEXPECTED_RESPONSE 2
#define ERR_SEND_COMMAND_FAILED 3
#define ERR_JOIN_FAILED 4
#define ERR_JOIN_NOT_ACCEPTED 5
#define ERR_PERSONALIZE_NOT_ACCEPTED 6
#define ERR_RESPONSE_IS_NOT_OK 7
#define ERR_KEY_LENGTH 8
#define ERR_CHECK_CONFIGURATION 9
#define ERR_NO_RESPONSE 10
#define ERR_INVALID_MODULE 11

const char personalize_accepted[] PROGMEM = "Personalize accepted. Status: ";
const char join_accepted[] PROGMEM = "Join accepted. Status: ";
const char successful_transmission[] PROGMEM = "Successful transmission";
const char successful_transmission_received[] PROGMEM = "Successful transmission. Received ";
const char valid_module[] PROGMEM = "Valid module connected.";

const char *const success_msg[] PROGMEM = {personalize_accepted, join_accepted, successful_transmission, successful_transmission_received, valid_module};

#define SCS_PERSONALIZE_ACCEPTED 0
#define SCS_JOIN_ACCEPTED 1
#define SCS_SUCCESSFUL_TRANSMISSION 2
#define SCS_SUCCESSFUL_TRANSMISSION_RECEIVED 3
#define SCS_VALID_MODULE 4

const char radio_prefix[] PROGMEM = "radio";
const char radio_set[] PROGMEM = "set";
const char radio_get[] PROGMEM = "get";
const char radio_get_bw[] PROGMEM = "bw";
const char radio_get_prlen[] PROGMEM = "prlen";
const char radio_get_crc[] PROGMEM = "crc";
const char radio_get_cr[] PROGMEM = "cr";
const char radio_get_sf[] PROGMEM = "sf";
const char radio_get_freq[] PROGMEM = "freq";
const char radio_get_rxbw[] PROGMEM = "rxbw";
const char radio_get_wdt[] PROGMEM = "wdt";
const char radio_get_pwr[] PROGMEM = "pwr";
const char radio_get_rssi[] PROGMEM = "rssi";
const char radio_get_snr[] PROGMEM = "snr";

const 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};

#define RADIO_PREFIX 0
#define RADIO_SET 1
#define RADIO_GET 2
#define RADIO_GET_BW 3
#define RADIO_GET_PRLEN 4
#define RADIO_GET_CRC 5
#define RADIO_GET_CR 6
#define RADIO_GET_SF 7
#define RADIO_GET_FREQ 8
#define RADIO_GET_RXBW 9
#define RADIO_GET_WDT 10
#define RADIO_GET_PWR 11
#define RADIO_GET_RSSI 12
#define RADIO_GET_SNR 13

const char sys_prefix[] PROGMEM = "sys";
const char sys_sleep[] PROGMEM = "sleep";
const char sys_reset[] PROGMEM = "reset";
const char sys_erase_fw[] PROGMEM = "eraseFW";
const char sys_factory_rst[] PROGMEM = "factoryRESET";
const char sys_set[] PROGMEM = "set";
const char sys_get[] PROGMEM = "get";
const char sys_get_ver[] PROGMEM = "ver";
const char sys_get_vdd[] PROGMEM = "vdd";
const char sys_get_hweui[] PROGMEM = "hweui";
const char sys_set_get_nvm[] PROGMEM = "nvm";
const char sys_set_pindig[] PROGMEM = "pindig";

const 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};

#define SYS_PREFIX 0
#define SYS_SLEEP 1
#define SYS_RESET 2
#define SYS_ERASE_FW 3
#define SYS_FACTORY_RST 4
#define SYS_SET 5
#define SYS_GET 6
#define SYS_GET_VER 7
#define SYS_GET_VDD 8
#define SYS_GET_HWEUI 9
#define SYS_SET_GET_NVM 10
#define SYS_SET_PINDIG 11

const char mac_prefix[] PROGMEM = "mac";
const char mac_reset[] PROGMEM = "reset";
const char mac_tx[] PROGMEM = "tx";
const char mac_join[] PROGMEM = "join";
const char mac_save[] PROGMEM = "save";
const char mac_force_enable[] PROGMEM = "forceENABLE";
const char mac_pause[] PROGMEM = "pause";
const char mac_resume[] PROGMEM = "resume";
const char mac_set[] PROGMEM = "set";
const char mac_get[] PROGMEM = "get";

const 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};

#define MAC_PREFIX 0
#define MAC_RESET 1
#define MAC_TX 2
#define MAC_JOIN 3
#define MAC_SAVE 4
#define MAC_FORCE_ENABLE 5
#define MAC_PAUSE 6
#define MAC_RESUME 7
#define MAC_SET 8
#define MAC_GET 9

const char mac_devaddr[] PROGMEM = "devaddr";
const char mac_deveui[] PROGMEM = "deveui";
const char mac_appeui[] PROGMEM = "appeui";
const char mac_nwkskey[] PROGMEM = "nwkskey";
const char mac_appskey[] PROGMEM = "appskey";
const char mac_appkey[] PROGMEM = "appkey";
const char mac_pwridx[] PROGMEM = "pwridx";
const char mac_dr[] PROGMEM = "dr";
const char mac_adr[] PROGMEM = "adr";
const char mac_bat[] PROGMEM = "bat";
const char mac_retx[] PROGMEM = "retx";
const char mac_linkchk[] PROGMEM = "linkchk";
const char mac_rxdelay1[] PROGMEM = "rxdelay1";
const char mac_rxdelay2[] PROGMEM = "rxdelay2";
const char mac_band[] PROGMEM = "band";
const char mac_ar[] PROGMEM = "ar";
const char mac_rx2[] PROGMEM = "rx2";
const char mac_ch[] PROGMEM = "ch";
const char mac_gwnb[] PROGMEM = "gwnb";
const char mac_mrgn[] PROGMEM = "mrgn";
const char mac_class[] PROGMEM = "class";
const char mac_status[] PROGMEM = "status";
const char mac_upctr[] PROGMEM = "upctr";
const char mac_dnctr[] PROGMEM = "dnctr";

const 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,
			mac_ar, mac_rx2, mac_ch, mac_gwnb, mac_mrgn, mac_class, mac_status, mac_upctr, mac_dnctr};

#define MAC_DEVADDR 0
#define MAC_DEVEUI 1
#define MAC_APPEUI 2
#define MAC_NWKSKEY 3
#define MAC_APPSKEY 4
#define MAC_APPKEY 5
#define MAC_PWRIDX 6
#define MAC_DR 7
#define MAC_ADR 8
#define MAC_BAT 9
#define MAC_RETX 10
#define MAC_LINKCHK 11
#define MAC_RXDELAY1 12
#define MAC_RXDELAY2 13
#define MAC_BAND 14
#define MAC_AR 15
#define MAC_RX2 16
#define MAC_CH 17
#define MAC_GWNB 18
#define MAC_MRGN 19
#define MAC_CLASS 20
#define MAC_STATUS 21
#define MAC_UPCTR 22
#define MAC_DNCTR 23

const char mac_join_mode_otaa[] PROGMEM = "otaa";
const char mac_join_mode_abp[] PROGMEM = "abp";

const char *const mac_join_mode[] PROGMEM = {mac_join_mode_otaa, mac_join_mode_abp};

#define MAC_JOIN_MODE_OTAA 0
#define MAC_JOIN_MODE_ABP 1

const char channel_dcycle[] PROGMEM = "dcycle";
const char channel_drrange[] PROGMEM = "drrange";
const char channel_freq[] PROGMEM = "freq";
const char channel_status[] PROGMEM = "status";

const char *const mac_ch_options[] PROGMEM = {channel_dcycle, channel_drrange, channel_freq, channel_status};

#define MAC_CHANNEL_DCYCLE 0
#define MAC_CHANNEL_DRRANGE 1
#define MAC_CHANNEL_FREQ 2
#define MAC_CHANNEL_STATUS 3

const char mac_tx_type_cnf[] PROGMEM = "cnf";
const char mac_tx_type_ucnf[] PROGMEM = "uncnf";

const char *const mac_tx_table[] PROGMEM = {mac_tx_type_cnf, mac_tx_type_ucnf};

#define MAC_TX_TYPE_CNF 0
#define MAC_TX_TYPE_UCNF 1

#define MAC_TABLE 0
#define MAC_GET_SET_TABLE 1
#define MAC_JOIN_TABLE 2
#define MAC_CH_TABLE 3
#define MAC_TX_TABLE 4
#define SYS_TABLE 5
#define RADIO_TABLE 6
#define ERR_MESSAGE 7
#define SUCCESS_MESSAGE 8
#define CMP_TABLE 9
#define CMP_ERR_TABLE 10

int pgmstrcmp(const char *str1, uint8_t str2Index, uint8_t table = CMP_TABLE)
{
  if (0 == strlen(str1))
	  return -1;

  char str2[128];

  switch (table) {
  case CMP_ERR_TABLE:
    strcpy_P(str2, (char *)pgm_read_word(&(compareerr_table[str2Index])));
    break;

  default:
  case CMP_TABLE:
    strcpy_P(str2, (char *)pgm_read_word(&(compare_table[str2Index])));
  }

  return memcmp(str1, str2, min(strlen(str1), strlen(str2)));
}

uint8_t digits(uint8_t port)
{
  if (port >= 100)
  {
    return 3;
  }
  else if (port >= 10)
  {
    return 2;
  }
  return 1;
}

uint8_t receivedPort(const char *s)
{
  uint8_t port = 0;
  uint8_t i = 0;
  while (s[i] != ' ' && s[i] != '\0')
  {
    port *= 10;
    port += s[i] - 48;
    i++;
  }
  return port;
}

TheThingsNetwork::TheThingsNetwork(Stream &modemStream, Stream &debugStream, ttn_fp_t fp, uint8_t sf, uint8_t fsb)
{
  this->debugStream = &debugStream;
  this->modemStream = &modemStream;
  this->modemStream->setTimeout(TTN_DEFAULT_TIMEOUT);
  this->fp = fp;
  this->sf = sf;
  this->fsb = fsb;
  this->adr = false;
  this->messageCallback = NULL;
}

size_t TheThingsNetwork::getAppEui(char *buffer, size_t size)
{
  return readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_APPEUI, buffer, size);
}

size_t TheThingsNetwork::getHardwareEui(char *buffer, size_t size)
{
  return readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, size);
}

size_t TheThingsNetwork::getVersion(char *buffer, size_t size)
{
  return readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_VER, buffer, size);
}

uint16_t TheThingsNetwork::getVDD()
{
  if (readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_VDD, buffer, sizeof(buffer)) > 0) {
    return atoi(buffer);
  }
  return 0;
}

uint8_t TheThingsNetwork::getBW()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_BW, buffer, sizeof(buffer)) > 0) {
    return atoi(buffer);
  }
  return 0;
}

uint8_t TheThingsNetwork::getCR()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_CR, buffer, sizeof(buffer)) > 2) {
    return atoi(buffer+2); // skip the first two chars "4/"
  }
  return 0;
}

uint32_t TheThingsNetwork::getFrequency()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_FREQ, buffer, sizeof(buffer)) > 0) {
    return atol(buffer);
  }
  return 0;
}

uint32_t TheThingsNetwork::getFCU()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_UPCTR, buffer, sizeof(buffer)) > 0) {
    return strtoul(buffer, NULL, 10);
  }
  return 0;
}

uint32_t TheThingsNetwork::getFCD()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DNCTR, buffer, sizeof(buffer)) > 0) {
    return strtoul(buffer, NULL, 10);
  }
  return 0;
}

uint32_t TheThingsNetwork::getWatchDogTimer()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_WDT, buffer, sizeof(buffer)) > 0) {
    return atol(buffer);
  }
  return 0;
}

enum ttn_modem_status_t TheThingsNetwork::getStatus()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_STATUS, buffer, sizeof(buffer)) > 0) {
	char **endptr = NULL;
	int status = (strtol(buffer, endptr, 16) & 0x0F); // Mask out only active status

	if (endptr == NULL)
		return (enum ttn_modem_status_t)status;
  }
  return TTN_MODEM_READ_ERR; // unable to read status
}

int8_t TheThingsNetwork::getPower()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_PWR, buffer, sizeof(buffer)) > 0) {
    return atoi(buffer);
  }
  return -128;
}

int16_t TheThingsNetwork::getRSSI()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_RSSI, buffer, sizeof(buffer)) > 0) {
    return atoi(buffer);
  }
  return -255;
}

int8_t TheThingsNetwork::getSNR()
{
  if (readResponse(RADIO_TABLE, RADIO_TABLE, RADIO_GET_SNR, buffer, sizeof(buffer)) > 0) {
    return atoi(buffer);
  }
  return -128;
}

int8_t TheThingsNetwork::getDR()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DR, buffer, sizeof(buffer))){
    return atoi(buffer);
  }
  return -1;
}

int8_t TheThingsNetwork::getPowerIndex()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_PWRIDX, buffer, sizeof(buffer)) > 0) {
    return atoi(buffer);
  }
  return -1;
}

bool TheThingsNetwork::getChannelStatus (uint8_t channel)
{
  char str[5];
  if (channel > 9)
  {
	str[0] = ((channel - (channel % 10)) / 10) + 48;
	str[1] = (channel % 10) + 48;
	str[2] = '\0';
  }
  else
  {
	str[0] = channel + 48;
	str[1] = '\0';
  }
  sendCommand(MAC_TABLE, MAC_PREFIX, true, false);
  sendCommand(MAC_TABLE, MAC_GET, true, false); // default "get " in between (same as radio get)
  sendCommand(MAC_GET_SET_TABLE, MAC_CH, true, false);
  sendCommand(MAC_CH_TABLE, MAC_CHANNEL_STATUS, true, false);
  modemStream->write(str);
  modemStream->write(SEND_MSG);

  if (readLine(buffer, sizeof(buffer)))
	  return (pgmstrcmp(buffer, CMP_ON) == 0); // true if on, false if off or an error occurs
  else
	  return false; // error
}

ttn_response_code_t TheThingsNetwork::getLastError(){

	int match, pos;
	for (pos=0; pos <= CMP_ERR_LAST; pos++){
		match = pgmstrcmp(buffer, pos, CMP_ERR_TABLE);
		if (match == 0)
			break;
	}

	return (ttn_response_code_t)(-1* pos); // code order is equal
}

void TheThingsNetwork::debugPrintIndex(uint8_t index, const char *value)
{
  char message[100];
  strcpy_P(message, (char *)pgm_read_word(&(show_table[index])));
  debugPrint(message);
  if (value)
  {
    debugPrintLn(value);
  }
}

void TheThingsNetwork::debugPrintMessage(uint8_t type, uint8_t index, const char *value)
{
  char message[100];
  switch (type)
  {
  case ERR_MESSAGE:
    strcpy_P(message, (char *)pgm_read_word(&(error_msg[index])));
    break;
  case SUCCESS_MESSAGE:
    strcpy_P(message, (char *)pgm_read_word(&(success_msg[index])));
    break;
  }
  debugPrint(message);
  if (value)
  {
    debugPrintLn(value);
  }
  else
  {
    debugPrintLn();
  }
}

void TheThingsNetwork::clearReadBuffer()
{
  while (modemStream->available())
  {
    modemStream->read();
  }
}

size_t TheThingsNetwork::readLine(char *buffer, size_t size, uint8_t attempts)
{
  size_t read = 0;
  while (!read && attempts--)
  {
    read = modemStream->readBytesUntil('\n', buffer, size);
  }
  if (!read)
  { // If attempts is activated return 0 and set RN state marker
    this->needsHardReset = true; // Inform the application about the radio module is not responsive.
    debugPrintMessage(ERR_MESSAGE, ERR_NO_RESPONSE);
    return 0;
  }
  buffer[read - 1] = '\0'; // set \r to \0
  return read;
}

size_t TheThingsNetwork::readResponse(uint8_t prefixTable, uint8_t index, char *buffer, size_t size)
{
  clearReadBuffer();
  sendCommand(prefixTable, 0, true, false);
  sendCommand(prefixTable, index, false, false);
  modemStream->write(SEND_MSG);
  return readLine(buffer, size);
}

size_t TheThingsNetwork::readResponse(uint8_t prefixTable, uint8_t indexTable, uint8_t index, char *buffer, size_t size)
{
  clearReadBuffer();
  sendCommand(prefixTable, 0, true, false);
  sendCommand(MAC_TABLE, MAC_GET, true, false);
  sendCommand(indexTable, index, false, false);
  modemStream->write(SEND_MSG);
  return readLine(buffer, size);
}

void TheThingsNetwork::autoBaud()
{
  // Courtesy of @jpmeijers
  modemStream->setTimeout(2000);
  uint8_t attempts = 10;
  size_t length = 0;
  while (attempts-- && length == 0)
  {
    delay(100);
    modemStream->write((byte)0x00);
    modemStream->write(0x55);
    modemStream->write(SEND_MSG);
    sendCommand(SYS_TABLE, 0, true, false);
    sendCommand(SYS_TABLE, SYS_GET, true, false);
    sendCommand(SYS_TABLE, SYS_GET_VER, false, false);
    modemStream->write(SEND_MSG);
    length = modemStream->readBytesUntil('\n', buffer, sizeof(buffer));
  }
  delay(100);
  clearReadBuffer();
  modemStream->setTimeout(TTN_DEFAULT_TIMEOUT);
  baudDetermined = true;
}

void TheThingsNetwork::reset(bool adr)
{
  // autobaud and send "sys reset"
  autoBaud();
  readResponse(SYS_TABLE, SYS_RESET, buffer, sizeof(buffer));

  // autobaud (again, because baudrate was reset with "sys reset") and get HW model and SW version
  autoBaud();
  getVersion(buffer, sizeof(buffer));

  // buffer contains "RN2xx3[xx] x.x.x ...", splitting model from version
  char *model = strtok(buffer, " ");
  debugPrintIndex(SHOW_MODEL, model);
  char *version = strtok(NULL, " ");
  debugPrintIndex(SHOW_VERSION, version);

  // set DEVEUI as HWEUI
  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, sizeof(buffer));
  sendMacSet(MAC_DEVEUI, buffer);
  // set ADR
  setADR(adr);
}

void TheThingsNetwork::resetHard(uint8_t resetPin){
  digitalWrite(resetPin, LOW);
  delay(1000);
  digitalWrite(resetPin, HIGH);
}

void TheThingsNetwork::saveState()
{
  debugPrint(SENDING);
  sendCommand(MAC_TABLE, MAC_PREFIX, true);
  sendCommand(MAC_TABLE, MAC_SAVE, false);
  modemStream->write(SEND_MSG);
  debugPrintLn();
  waitForOk();
}

void TheThingsNetwork::onMessage(void (*cb)(const uint8_t *payload, size_t size, port_t port))
{
  messageCallback = cb;
}

bool TheThingsNetwork::personalize(const char *devAddr, const char *nwkSKey, const char *appSKey, bool resetFirst)
{
  if(resetFirst) {
    reset(adr);
  }
  if (strlen(devAddr) != 8 || strlen(appSKey) != 32 || strlen(nwkSKey) != 32)
  {
    debugPrintMessage(ERR_MESSAGE, ERR_KEY_LENGTH);
    return false;
  }
  sendMacSet(MAC_DEVADDR, devAddr);
  sendMacSet(MAC_NWKSKEY, nwkSKey);
  sendMacSet(MAC_APPSKEY, appSKey);
  return personalize();
}

bool TheThingsNetwork::personalize()
{
  configureChannels(fsb);
  setSF(sf);
  sendJoinSet(MAC_JOIN_MODE_ABP);
  readLine(buffer, sizeof(buffer));
  if (pgmstrcmp(buffer, CMP_ACCEPTED) != 0)
  {
    debugPrintMessage(ERR_MESSAGE, ERR_PERSONALIZE_NOT_ACCEPTED, buffer);
    debugPrintMessage(ERR_MESSAGE, ERR_CHECK_CONFIGURATION);
    return false;
  }

  readResponse(MAC_TABLE, MAC_CH_TABLE, MAC_CHANNEL_STATUS, buffer, sizeof(buffer));
  debugPrintMessage(SUCCESS_MESSAGE, SCS_PERSONALIZE_ACCEPTED, buffer);
  return true;
}

bool TheThingsNetwork::provision(const char *appEui, const char *appKey, bool resetFirst)
{
  if(resetFirst) {
    reset(adr);
  }
  if (strlen(appEui) != 16 || strlen(appKey) != 32)
  {
    debugPrintMessage(ERR_MESSAGE, ERR_KEY_LENGTH);
    return false;
  }
  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, sizeof(buffer));
  sendMacSet(MAC_DEVEUI, buffer);
  sendMacSet(MAC_APPEUI, appEui);
  sendMacSet(MAC_APPKEY, appKey);
  saveState();
  return true;
}

bool TheThingsNetwork::join(int8_t retries, uint32_t retryDelay)
{
  int8_t attempts = 0;
  configureChannels(fsb);
  setSF(sf);
  while (retries == -1 || attempts <= retries)
  {
    attempts++;
    if (!sendJoinSet(MAC_JOIN_MODE_OTAA))
    {
      debugPrintMessage(ERR_MESSAGE, ERR_JOIN_FAILED);
      delay(retryDelay);
      continue;
    }
    readLine(buffer, sizeof(buffer));
    if (pgmstrcmp(buffer, CMP_ACCEPTED) != 0)
    {
      debugPrintMessage(ERR_MESSAGE, ERR_JOIN_NOT_ACCEPTED, buffer);
      debugPrintMessage(ERR_MESSAGE, ERR_CHECK_CONFIGURATION);
      delay(retryDelay);
      continue;
    }
    readResponse(MAC_TABLE, MAC_CH_TABLE, MAC_CHANNEL_STATUS, buffer, sizeof(buffer));
    debugPrintMessage(SUCCESS_MESSAGE, SCS_JOIN_ACCEPTED, buffer);
    readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DEVADDR, buffer, sizeof(buffer));
    debugPrintIndex(SHOW_DEVADDR, buffer);
    return true;
  }
  return false;
}

bool TheThingsNetwork::setClass(lorawan_class_t p_lw_class)
{
  switch(p_lw_class)
  {

  case CLASS_A:
    {
      lw_class = p_lw_class;
      return sendMacSet(MAC_CLASS, "a");
    }

  // case CLASS_B: // Not yet supported. Use default case.

  case CLASS_C:
    {
      bool result = sendMacSet(MAC_CLASS, "c");
      // Older firmware does not support Class C. If setting change fails, keep on using Class A.
      if(result) lw_class = p_lw_class;
      return result;
    }

  default:
    return false;

  }
}

bool TheThingsNetwork::join(const char *appEui, const char *appKey, int8_t retries, uint32_t retryDelay, lorawan_class_t p_lw_class)
{
  return provision(appEui, appKey) && join(retries, retryDelay) && setClass(p_lw_class);
}

ttn_response_t TheThingsNetwork::parseBytes(){
    if (buffer[0]=='\0')
  	  return TTN_UNSUCCESSFUL_RECEIVE;

	if (pgmstrcmp(buffer, CMP_MAC_RX) == 0)
    {
		port_t downlinkPort = receivedPort(buffer + 7);
		char *data = buffer + 7 + digits(downlinkPort) + 1;
		size_t downlinkLength = strlen(data) / 2;
		if (downlinkLength > 0)
		{
		  uint8_t downlink[downlinkLength];
		  for (size_t i = 0, d = 0; i < downlinkLength; i++, d += 2)
		  {
			downlink[i] = TTN_HEX_PAIR_TO_BYTE(data[d], data[d + 1]);
		  }
		  debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION_RECEIVED, data);
		  if (messageCallback)
		  {
			messageCallback(downlink, downlinkLength, downlinkPort);
		  }
		}
		else
		{
		  debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION);
		}
		return TTN_SUCCESSFUL_RECEIVE;
	}
    // not REC but buffer FULL
    debugPrintMessage(ERR_MESSAGE, ERR_UNEXPECTED_RESPONSE, buffer);
    return TTN_ERROR_UNEXPECTED_RESPONSE;
}

ttn_response_t TheThingsNetwork::sendBytes(const uint8_t *payload, size_t length, port_t port, bool confirm, uint8_t sf)
{
  if (sf != 0)
  {
    setSF(sf);
  }

  uint8_t mode = confirm ? MAC_TX_TYPE_CNF : MAC_TX_TYPE_UCNF;
  if (!sendPayload(mode, port, (uint8_t *)payload, length))
  {
    debugPrintMessage(ERR_MESSAGE, ERR_SEND_COMMAND_FAILED);
    return TTN_ERROR_SEND_COMMAND_FAILED;
  }

  // read modem response
  if (!readLine(buffer, sizeof(buffer)) && confirm) // Read response
	  // confirmed and RX timeout -> ask to poll if necessary
	  return TTN_UNSUCCESSFUL_RECEIVE;

  // TX only?
  if (pgmstrcmp(buffer, CMP_MAC_TX_OK) == 0)
  {
    debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION);
    return TTN_SUCCESSFUL_TRANSMISSION;
  }
  else if (pgmstrcmp(buffer, CMP_MAC_ERR) == 0)
	return TTN_UNSUCCESSFUL_RECEIVE;

  // Received downlink message?
  return parseBytes();
}

ttn_response_t TheThingsNetwork::poll(port_t port, bool confirm, bool modem_only)
{
  switch(lw_class)
  {

  case CLASS_A:
	  if (!modem_only)
		{
		  // Class A: send uplink and wait for rx windows
		  uint8_t payload[] = {0x00};
		  return sendBytes(payload, 1, port, confirm);
		}
	  else
	  {
		  if (!readLine(buffer, sizeof(buffer)) && confirm) // Read response
			  // confirmed and RX timeout -> ask to poll if necessary
			  return TTN_UNSUCCESSFUL_RECEIVE;

		  // Here we can have the result of pending TX, or pending RX (for confirmed messages)
		  if (pgmstrcmp(buffer, CMP_MAC_TX_OK) == 0)
		  {
		    debugPrintMessage(SUCCESS_MESSAGE, SCS_SUCCESSFUL_TRANSMISSION);
		    return TTN_SUCCESSFUL_TRANSMISSION;
		  }
		  else if (pgmstrcmp(buffer, CMP_MAC_ERR) == 0)
			return TTN_UNSUCCESSFUL_RECEIVE;

		  // Receive Message
		  return parseBytes();
	  }


  case CLASS_C:
	  {
		  // Class C: check rx buffer for any received data
		  memset(buffer, 0, sizeof(buffer));

		  uint32_t timeout = this->modemStream->getTimeout();
		  this->modemStream->setTimeout(100);
		  this->modemStream->readBytesUntil('\n', buffer, sizeof(buffer));
		  this->modemStream->setTimeout(timeout);

		  return parseBytes();
	  }

  default:
  case CLASS_B: // Not yet supported. Use default case.
	  return TTN_UNSUCCESSFUL_RECEIVE;

  }
}

void TheThingsNetwork::showStatus()
{
  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_HWEUI, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_EUI, buffer);
  readResponse(SYS_TABLE, SYS_TABLE, SYS_GET_VDD, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_BATTERY, buffer);
  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_APPEUI, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_APPEUI, buffer);
  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DEVEUI, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_DEVEUI, buffer);
  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_DR, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_DATA_RATE, buffer);
  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_RXDELAY1, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_RX_DELAY_1, buffer);
  readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_RXDELAY2, buffer, sizeof(buffer));
  debugPrintIndex(SHOW_RX_DELAY_2, buffer);
}

bool TheThingsNetwork::checkValidModuleConnected(bool autoBaudFirst)
{
  // check if we want to autobaud first
  if(autoBaudFirst)
  {
    autoBaud();
  }
  // send "sys get ver" to check if (and what) module is connected
  getVersion(buffer, sizeof(buffer));
  // check if we got a response (whatever it might be)
  // needsHardReset flag is set by readLine() (called at some point down the line by getVersion())
  if(this->needsHardReset)
  {
    return false;                                               // no response
  }
  // buffer contains "RN2xx3[xx] x.x.x ...", getting only model (RN2xx3[xx])
  char *model = strtok(buffer, " ");
  debugPrintIndex(SHOW_MODEL, model);
  // check if module is valid (must be RN2483, RN2483A, RN2903 or RN2903AS)
  if(pgmstrcmp(model, CMP_RN2483) == 0 || pgmstrcmp(model, CMP_RN2483A) == 0 || pgmstrcmp(model, CMP_RN2903) == 0 || pgmstrcmp(model, CMP_RN2903AS) == 0)
  {
    debugPrintMessage(SUCCESS_MESSAGE, SCS_VALID_MODULE);
    return true;                                                // module responded and is valid (recognized/supported)
  }
  debugPrintMessage(ERR_MESSAGE, ERR_INVALID_MODULE);
  return false;                                                 // module responded but is invalid (unrecognized/unsupported)
}

void TheThingsNetwork::configureEU868()
{
  sendMacSet(MAC_RX2, 3, 869525000);
  sendChSet(MAC_CHANNEL_DRRANGE, 1, "0 6");

  char buf[10];
  uint32_t freq = 867100000;
  uint8_t ch;
  for (ch = 0; ch < 8; ch++)
  {
    if (ch > 2)
    {
      sprintf(buf, "%lu", freq);
      sendChSet(MAC_CHANNEL_FREQ, ch, buf);
      sendChSet(MAC_CHANNEL_DRRANGE, ch, "0 5");
      sendChSet(MAC_CHANNEL_DCYCLE, ch, 499); // 5*0.2% ETSI band G1, total 1%
      setChannelStatus(ch, true);;
      freq = freq + 200000;
    }
    else
    	sendChSet(MAC_CHANNEL_DCYCLE, ch, 299); // 3*0.33% ETSI band G, total 1%
  }
  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_EU868);
}

void TheThingsNetwork::configureUS915(uint8_t fsb)
{
  uint8_t ch;
  uint8_t chLow = fsb > 0 ? (fsb - 1) * 8 : 0;
  uint8_t chHigh = fsb > 0 ? chLow + 7 : 71;
  uint8_t ch500 = fsb + 63;
  for (ch = 0; ch < 72; ch++)
  {
    if (ch == ch500 || (ch <= chHigh && ch >= chLow))
    {
      setChannelStatus(ch, true);
      if (ch < 63)
      {
        sendChSet(MAC_CHANNEL_DRRANGE, ch, "0 3");
      }
    }
    else
    {
    	setChannelStatus(ch, false);
    }
  }
  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_US915);
}

void TheThingsNetwork::configureAU915(uint8_t fsb)
{
  uint8_t ch;
  uint8_t chLow = fsb > 0 ? (fsb - 1) * 8 : 0;
  uint8_t chHigh = fsb > 0 ? chLow + 7 : 71;
  uint8_t ch500 = fsb + 63;
  for (ch = 0; ch < 72; ch++)
  {
    if (ch == ch500 || (ch <= chHigh && ch >= chLow))
    {
      setChannelStatus(ch, true);
      if (ch < 63)
      {
        sendChSet(MAC_CHANNEL_DRRANGE, ch, "0 3");
      }
    }
    else
    {
    	setChannelStatus(ch, false);
    }
  }
  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_AU915);
}

void TheThingsNetwork::configureAS920_923()
{
  /* RN2903AS 1.0.3rc9 defaults
   * CH0 = 923.2MHz
   * CH1 = 923.4MHz
   */
  setADR(false); // TODO: remove when ADR is implemented for this plan
  sendMacSet(MAC_RX2, 2, 923200000);

  char buf[10];
  uint32_t freq = 922000000;
  uint8_t ch;
  for (ch = 0; ch < 8; ch++)
  {
    sendChSet(MAC_CHANNEL_DCYCLE, ch, 799);
    if (ch > 1)
    {
      sprintf(buf, "%lu", freq);
      sendChSet(MAC_CHANNEL_FREQ, ch, buf);
      sendChSet(MAC_CHANNEL_DRRANGE, ch, "0 5");
      setChannelStatus(ch, true);
      freq = freq + 200000;
    }
  }
  // TODO: SF7BW250/DR6 channel, not properly supported by RN2903AS yet
  //sendChSet(MAC_CHANNEL_DCYCLE, 8, 799);
  //sendChSet(MAC_CHANNEL_FREQ, 8, 922100000);
  //sendChSet(MAC_CHANNEL_DRRANGE, 8, "6 6");
  //setChannelStatus(8, true);
  // TODO: Add FSK channel on 921800000
  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_AS920_923);
}

void TheThingsNetwork::configureAS923_925()
{
  /* RN2903AS 1.0.3rc9 defaults
   * CH0 = 923.2MHz
   * CH1 = 923.4MHz
   */
  setADR(false); // TODO: remove when ADR is implemented for this plan
  sendMacSet(MAC_RX2, 2, 923200000);

  char buf[10];
  uint32_t freq = 923600000;
  uint8_t ch;
  for (ch = 0; ch < 8; ch++)
  {
    sendChSet(MAC_CHANNEL_DCYCLE, ch, 799);
    if (ch > 1)
    {
      sprintf(buf, "%lu", freq);
      sendChSet(MAC_CHANNEL_FREQ, ch, buf);
      sendChSet(MAC_CHANNEL_DRRANGE, ch, "0 5");
      setChannelStatus(ch, true);
      freq = freq + 200000;
    }
  }
  // TODO: SF7BW250/DR6 channel, not properly supported by RN2903AS yet
  //sendChSet(MAC_CHANNEL_DCYCLE, 8, 799);
  //sendChSet(MAC_CHANNEL_FREQ, 8, 924500000);
  //sendChSet(MAC_CHANNEL_DRRANGE, 8, "6 6");
  //setChannelStatus(8, true);
  // TODO: Add FSK channel on 924800000
  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_AS923_925);
}

void TheThingsNetwork::configureKR920_923()
{
  setADR(false); // TODO: remove when ADR is implemented for this plan
  sendMacSet(MAC_RX2, 0, 921900000); // KR still uses SF12 for now. Might change to SF9 later.

  //disable two default LoRaWAN channels
  setChannelStatus(0, false);
  setChannelStatus(1, false);

  char buf[10];
  uint32_t freq = 922100000;
  uint8_t ch;
  for (ch = 2; ch < 9; ch++)
  {
    sendChSet(MAC_CHANNEL_DCYCLE, ch, 799);
    sprintf(buf, "%lu", freq);
    sendChSet(MAC_CHANNEL_FREQ, ch, buf);
    sendChSet(MAC_CHANNEL_DRRANGE, ch, "0 5");
    setChannelStatus(ch, true);
    freq = freq + 200000;
  }
  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_KR920_923);
}

void TheThingsNetwork::configureIN865_867()
{
  setADR(false); // TODO: remove when ADR is implemented for this plan
  sendMacSet(MAC_RX2, 2, 866550000); // SF10

  // Disable the three default LoRaWAN channels
  setChannelStatus(0, false);
  setChannelStatus(1, false);
  setChannelStatus(2, false);

  // Channel 3
  sendChSet(MAC_CHANNEL_DCYCLE, 3, 299);
  sendChSet(MAC_CHANNEL_FREQ, 3, 865062500);
  sendChSet(MAC_CHANNEL_DRRANGE, 3, "0 5");
  setChannelStatus(3, true);

  // Channel 4
  sendChSet(MAC_CHANNEL_DCYCLE, 4, 299);
  sendChSet(MAC_CHANNEL_FREQ, 4, 865402500);
  sendChSet(MAC_CHANNEL_DRRANGE, 4, "0 5");
  setChannelStatus(4, true);

  // Channel 5
  sendChSet(MAC_CHANNEL_DCYCLE, 5, 299);
  sendChSet(MAC_CHANNEL_FREQ, 5, 865985000);
  sendChSet(MAC_CHANNEL_DRRANGE, 5, "0 5");
  setChannelStatus(5, true);

  sendMacSet(MAC_PWRIDX, TTN_PWRIDX_IN865_867);
}

void TheThingsNetwork::configureChannels(uint8_t fsb)
{
  switch (fp)
  {
  case TTN_FP_EU868:
    configureEU868();
    break;
  case TTN_FP_US915:
    configureUS915(fsb);
    break;
  case TTN_FP_AU915:
    configureAU915(fsb);
    break;
  case TTN_FP_AS920_923:
    configureAS920_923();
    break;
  case TTN_FP_AS923_925:
    configureAS923_925();
    break;
  case TTN_FP_KR920_923:
    configureKR920_923();
    break;
  case TTN_FP_IN865_867:
    configureIN865_867();
    break;
  default:
    debugPrintMessage(ERR_MESSAGE, ERR_INVALID_FP);
    break;
  }
  sendMacSet(MAC_RETX, TTN_RETX);
}

bool TheThingsNetwork::setChannel(uint8_t channel, uint32_t frequency, uint8_t dr_min, uint8_t dr_max){

  bool done = true;

  if (channel > 15)
	  return false;

  if (frequency){
	char buf[11];
	sprintf(buf, "%lu", frequency);
	done &= sendChSet(MAC_CHANNEL_FREQ, channel, buf);
  }

  if (done && (dr_min < 16) && (dr_max < 16)){
	char buf[11];
	sprintf(buf, "%u %u", dr_min, dr_max);
	done &= sendChSet(MAC_CHANNEL_DRRANGE, channel, buf);
  }
  else
	done &= (dr_min == 255) && (dr_max == 255);

  return done;
}

bool TheThingsNetwork::setRx2Channel(uint32_t frequency, uint8_t dr){

  char buf[15];
  sprintf(buf, "%u %lu", dr, frequency);
  return sendMacSet(MAC_RX2, buf);
}

bool TheThingsNetwork::setChannelStatus (uint8_t channel, bool status){
  if (status)
    return sendChSet(MAC_CHANNEL_STATUS, channel, "on");
  else
    return sendChSet(MAC_CHANNEL_STATUS, channel, "off");
}

bool TheThingsNetwork::setChannelDCycle (uint8_t channel, float duty_cycle){ // in percent
  if (channel > 15 || duty_cycle > 100.0 || duty_cycle < 0.0)
	return false;

  char buf[6]; // number 99999
  if (0.0 == duty_cycle)
	  (void)sprintf(buf, "%u", 65535u);
  else
	  (void)sprintf(buf, "%u", (uint16_t)((100.0/duty_cycle) - 1));

  return sendChSet(MAC_CHANNEL_DCYCLE, channel, buf);
}

bool TheThingsNetwork::setPowerIndex(uint8_t index){
  char buf[4];
  sprintf(buf, "%u",index);
  return sendMacSet(MAC_PWRIDX, buf);
}

bool TheThingsNetwork::setDR(uint8_t dr){
  char buf[4];
  sprintf(buf, "%u",dr);
  return sendMacSet(MAC_DR, buf);
}

bool TheThingsNetwork::setADR(bool adr){
	bool ret;
	if (adr)
	{
		ret = sendMacSet(MAC_ADR, "on");
	}
	else
	{
		ret = sendMacSet(MAC_ADR, "off");
	}
	this->adr = adr;
	return ret;
}

bool TheThingsNetwork::setSF(uint8_t sf)
{
  uint8_t dr;
  switch (fp)
  {
  case TTN_FP_EU868:
  case TTN_FP_IN865_867:
  case TTN_FP_AS920_923:
  case TTN_FP_AS923_925:
  case TTN_FP_KR920_923:
  default:
    dr = 12 - sf;
    break;
  case TTN_FP_US915:
  case TTN_FP_AU915:
    dr = 10 - sf;
    break;
  }
  char s[2];
  s[0] = '0' + dr;
  s[1] = '\0';
  return sendMacSet(MAC_DR, s);
}

bool TheThingsNetwork::setRX1Delay(uint16_t delay){
	  char buf[6];
	  sprintf(buf, "%u",delay);
	  return sendMacSet(MAC_RXDELAY1, buf);
}

bool TheThingsNetwork::setFCU(uint32_t fcu){
  char buf[10];
  sprintf(buf, "%lu", fcu);
  return sendMacSet(MAC_UPCTR, buf);
}

bool TheThingsNetwork::setFCD(uint32_t fcd){
  char buf[10];
  sprintf(buf, "%lu", fcd);
  return sendMacSet(MAC_DNCTR, buf);
}

void TheThingsNetwork::sendCommand(uint8_t table, uint8_t index, bool appendSpace, bool print)
{
  char command[100];
  switch (table)
  {
  case MAC_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(mac_table[index])));
    break;
  case MAC_GET_SET_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(mac_options[index])));
    break;
  case MAC_JOIN_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(mac_join_mode[index])));
    break;
  case MAC_CH_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(mac_ch_options[index])));
    break;
  case MAC_TX_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(mac_tx_table[index])));
    break;
  case SYS_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(sys_table[index])));
    break;
  case RADIO_TABLE:
    strcpy_P(command, (char *)pgm_read_word(&(radio_table[index])));
    break;
  default:
    return;
  }
  modemStream->write(command);
  if (appendSpace)
  {
    modemStream->write(" ");
  }
  if (print)
  {
    debugPrint(command);
    debugPrint(F(" "));
  }
}

bool TheThingsNetwork::sendMacSet(uint8_t index, uint8_t value1, unsigned long value2)
{
	char buf[15];
	sprintf(buf, "%u %lu", value1, value2);
	return sendMacSet(index, buf);
}

bool TheThingsNetwork::sendMacSet(uint8_t index, const char *value)
{
  clearReadBuffer();
  debugPrint(SENDING);
  sendCommand(MAC_TABLE, MAC_PREFIX, true);
  sendCommand(MAC_TABLE, MAC_SET, true);
  sendCommand(MAC_GET_SET_TABLE, index, true);
  modemStream->write(value);
  modemStream->write(SEND_MSG);
  debugPrintLn(value);
  return waitForOk();
}

bool TheThingsNetwork::waitForOk()
{
  readLine(buffer, sizeof(buffer));
  if (pgmstrcmp(buffer, CMP_OK) != 0)
  {
    debugPrintMessage(ERR_MESSAGE, ERR_RESPONSE_IS_NOT_OK, buffer);
    return false;
  }
  return true;
}

bool TheThingsNetwork::sendChSet(uint8_t index, uint8_t channel, unsigned long value)
{
	char buf[11];
	sprintf(buf, "%lu", value);
	return sendChSet(index, channel, buf);
}

bool TheThingsNetwork::sendChSet(uint8_t index, uint8_t channel, const char *value)
{
  clearReadBuffer();
  char ch[5];
  if (channel > 9)
  {
    ch[0] = ((channel - (channel % 10)) / 10) + 48;
    ch[1] = (channel % 10) + 48;
    ch[2] = '\0';
  }
  else
  {
    ch[0] = channel + 48;
    ch[1] = '\0';
  }
  debugPrint(F(SENDING));
  sendCommand(MAC_TABLE, MAC_PREFIX, true);
  sendCommand(MAC_TABLE, MAC_SET, true);
  sendCommand(MAC_GET_SET_TABLE, MAC_CH, true);
  sendCommand(MAC_CH_TABLE, index, true);
  modemStream->write(ch);
  modemStream->write(" ");
  modemStream->write(value);
  modemStream->write(SEND_MSG);
  debugPrint(channel);
  debugPrint(F(" "));
  debugPrintLn(value);
  return waitForOk();
}

bool TheThingsNetwork::sendJoinSet(uint8_t type)
{
  clearReadBuffer();
  debugPrint(F(SENDING));
  sendCommand(MAC_TABLE, MAC_PREFIX, true);
  sendCommand(MAC_TABLE, MAC_JOIN, true);
  sendCommand(MAC_JOIN_TABLE, type, false);
  modemStream->write(SEND_MSG);
  debugPrintLn();
  return waitForOk();
}

bool TheThingsNetwork::sendPayload(uint8_t mode, uint8_t port, uint8_t *payload, size_t length)
{
  clearReadBuffer();
  debugPrint(F(SENDING));
  sendCommand(MAC_TABLE, MAC_PREFIX, true);
  sendCommand(MAC_TABLE, MAC_TX, true);
  sendCommand(MAC_TX_TABLE, mode, true);
  char sport[4];
  if (port > 99)
  {
    sport[0] = ((port - (port % 100)) / 100) + 48;
    sport[1] = (((port % 100) - (port % 10)) / 10) + 48;
    sport[2] = (port % 10) + 48;
    sport[3] = '\0';
  }
  else if (port > 9)
  {
    sport[0] = ((port - (port % 10)) / 10) + 48;
    sport[1] = (port % 10) + 48;
    sport[2] = '\0';
  }
  else
  {
    sport[0] = port + 48;
    sport[1] = '\0';
  }
  modemStream->write(sport);
  modemStream->print(" ");
  debugPrint(sport);
  debugPrint(F(" "));
  uint8_t i = 0;
  for (i = 0; i < length; i++)
  {
    if (payload[i] < 16)
    {
      modemStream->print("0");
      modemStream->print(payload[i], HEX);
      debugPrint(F("0"));
      debugPrint(payload[i], HEX);
    }
    else
    {
      modemStream->print(payload[i], HEX);
      debugPrint(payload[i], HEX);
    }
  }
  modemStream->write(SEND_MSG);
  debugPrintLn();
  return waitForOk();
}

void TheThingsNetwork::sleep(uint32_t mseconds)
{
  if (mseconds < 100)
  {
    return;
  }

  debugPrint(F(SENDING));
  sendCommand(SYS_TABLE, SYS_PREFIX, true);
  sendCommand(SYS_TABLE, SYS_SLEEP, true);

  sprintf(buffer, "%lu", mseconds);
  modemStream->write(buffer);
  modemStream->write(SEND_MSG);
  debugPrintLn(buffer);
}

void TheThingsNetwork::wake()
{
  autoBaud();
}

void TheThingsNetwork::linkCheck(uint16_t seconds)
{
  clearReadBuffer();
  debugPrint(SENDING);
  sendCommand(MAC_TABLE, MAC_PREFIX, true);
  sendCommand(MAC_TABLE, MAC_SET, true);
  sendCommand(MAC_GET_SET_TABLE, MAC_LINKCHK, true);

  sprintf(buffer, "%u", seconds);
  modemStream->write(buffer);
  modemStream->write(SEND_MSG);
  debugPrintLn(buffer);
  waitForOk();
}

uint8_t TheThingsNetwork::getLinkCheckGateways()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_GWNB, buffer, sizeof(buffer))){
	  char **endptr = NULL;
	  uint8_t gwnb = strtol(buffer, endptr, 10);
	  if (endptr == NULL)
		  return gwnb;
  }
  return 0; // Gateway number defaults to 0
}

uint8_t TheThingsNetwork::getLinkCheckMargin()
{
  if (readResponse(MAC_TABLE, MAC_GET_SET_TABLE, MAC_MRGN, buffer, sizeof(buffer))){
	  char **endptr = NULL;
	  uint8_t mgn = strtol(buffer, endptr, 10);
	  if (endptr == NULL)
		  return mgn;
  }
  return 255; // Signal margin defaults to 255
}


================================================
FILE: src/TheThingsNetwork.h
================================================
// Copyright © 2017 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

#ifndef _THETHINGSNETWORK_H_
#define _THETHINGSNETWORK_H_

#include <Arduino.h>
#include <Stream.h>
#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_SAMD)
#include <avr/pgmspace.h>
#else
#include <pgmspace.h>
#endif

#define TTN_DEFAULT_SF 7
#define TTN_DEFAULT_FSB 2
#define TTN_RETX "7"

#define TTN_PWRIDX_EU868 "1"
#define TTN_PWRIDX_US915 "5"
#define TTN_PWRIDX_AU915 "5"
#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)
#define TTN_PWRIDX_AS923_925 "1" // TODO: should be 0
#define TTN_PWRIDX_KR920_923 "1" // TODO: should be 0
#define TTN_PWRIDX_IN865_867 "1" // TODO: should be 0

#define TTN_BUFFER_SIZE 300
#define TTN_DEFAULT_TIMEOUT 10000	// Default modem timeout in ms

typedef uint8_t port_t;

enum ttn_response_t
{
  TTN_ERROR_SEND_COMMAND_FAILED = (-1),
  TTN_ERROR_UNEXPECTED_RESPONSE = (-10),
  TTN_SUCCESSFUL_TRANSMISSION = 1,
  TTN_SUCCESSFUL_RECEIVE = 2,
  TTN_UNSUCCESSFUL_RECEIVE = 3
};

enum ttn_fp_t
{
  TTN_FP_EU868,
  TTN_FP_US915,
  TTN_FP_AU915,
  TTN_FP_AS920_923,
  TTN_FP_AS923_925,
  TTN_FP_KR920_923,
  TTN_FP_IN865_867
};

enum lorawan_class_t
{
  CLASS_A,
  CLASS_B,
  CLASS_C
};

enum ttn_response_code_t
{
	TTN_OK,
	TTN_ERROR_BUSY = (-1),
	TTN_ERROR_FRAME_COUNTER_ERROR = (-2),
	TTN_ERROR_INVALID_CLASS = (-3),
	TTN_ERROR_INVALID_LENGTH = (-4),
	TTN_ERROR_INVALID_PARAMETER = (-5),
	TTN_ERROR_NO_KEY_INTITIALIZED = (-6),
	TTN_ERROR_MAC_PAUSE = (-7),
	TTN_ERROR_NO_KEY_MULTICAST = (-8),
	TTN_ERROR_NO_FREE_CHANNEL = (-9),
	TTN_ERROR_NOT_JOINED = (-10),
	TTN_ERROR_SILENT = (-11),
	TTN_ERROR_ERR = (-12),
};

enum ttn_modem_status_t
{
	TTN_MODEM_READ_ERR = -1,
	TTN_MODEM_IDLE = 0,
	TTN_MODEM_TX,
	TTN_MODEM_BEFORE_RX,
	TTN_MODEM_RX1,
	TTN_MODEM_BEFORE_RX2,
	TTN_MODEM_RETX_DELAY,
	TTN_MODEM_APB_DELAY,
	TTN_MODEM_C_RX1,
	TTN_MODEM_C_RX2
};

class TheThingsNetwork
{
private:
  Stream *modemStream;
  Stream *debugStream = NULL;
  ttn_fp_t fp;
  uint8_t sf;
  uint8_t fsb;
  bool adr;
  char buffer[512];
  bool baudDetermined = false;
  void (*messageCallback)(const uint8_t *payload, size_t size, port_t port);
  lorawan_class_t lw_class = CLASS_A;

  void clearReadBuffer();
  size_t readLine(char *buffer, size_t size, uint8_t attempts = 3);
  size_t readResponse(uint8_t prefixTable, uint8_t indexTable, uint8_t index, char *buffer, size_t size);
  size_t readResponse(uint8_t table, uint8_t index, char *buffer, size_t size);

  void debugPrintIndex(uint8_t index, const char *value = NULL);
  void debugPrintMessage(uint8_t type, uint8_t index, const char *value = NULL);

  void autoBaud();
  void configureEU868();
  void configureUS915(uint8_t fsb);
  void configureAU915(uint8_t fsb);
  void configureAS920_923();
  void configureAS923_925();
  void configureKR920_923();
  void configureIN865_867();
  void configureChannels(uint8_t fsb);
  bool setSF(uint8_t sf);
  bool waitForOk();

  ttn_response_t parseBytes();
  void sendCommand(uint8_t table, uint8_t index, bool appendSpace, bool print = true);
  bool sendMacSet(uint8_t index, uint8_t value1, unsigned long value2);
  bool sendMacSet(uint8_t index, const char *value);
  bool sendChSet(uint8_t index, uint8_t channel, unsigned long value);
  bool sendChSet(uint8_t index, uint8_t channel, const char *value);
  bool sendJoinSet(uint8_t type);
  bool sendPayload(uint8_t mode, uint8_t port, uint8_t *payload, size_t len);
  void sendGetValue(uint8_t table, uint8_t prefix, uint8_t index);

public:
  bool needsHardReset = false;

  TheThingsNetwork(Stream &modemStream, Stream &debugStream, ttn_fp_t fp, uint8_t sf = TTN_DEFAULT_SF, uint8_t fsb = TTN_DEFAULT_FSB);
  void reset(bool adr = true);
  void resetHard(uint8_t resetPin);
  void showStatus();
  size_t getHardwareEui(char *buffer, size_t size);
  size_t getAppEui(char *buffer, size_t size);
  size_t getVersion(char *buffer, size_t size);
  enum ttn_modem_status_t getStatus();
  uint16_t getVDD();
  int16_t getRSSI();
  uint32_t getFrequency();
  uint32_t getWatchDogTimer();
  uint32_t getFCU();
  uint32_t getFCD();
  uint8_t getBW();
  uint8_t getCR();
  int8_t getPower();
  int8_t getSNR();
  int8_t getDR();
  int8_t getPowerIndex();
  bool getChannelStatus (uint8_t channel);
  ttn_response_code_t getLastError();
  void onMessage(void (*cb)(const uint8_t *payload, size_t size, port_t port));
  bool provision(const char *appEui, const char *appKey, bool resetFirst = true);
  bool join(const char *appEui, const char *appKey, int8_t retries = -1, uint32_t retryDelay = 10000, lorawan_class_t = CLASS_A);
  bool join(int8_t retries = -1, uint32_t retryDelay = 10000);
  bool personalize(const char *devAddr, const char *nwkSKey, const char *appSKey, bool resetFirst = true);
  bool personalize();
  bool setClass(lorawan_class_t p_lw_class);
  ttn_response_t sendBytes(const uint8_t *payload, size_t length, port_t port = 1, bool confirm = false, uint8_t sf = 0);
  ttn_response_t poll(port_t port = 1, bool confirm = false, bool modem_only = false);
  void sleep(uint32_t mseconds);
  void wake();
  void saveState();
  void linkCheck(uint16_t seconds);
  uint8_t getLinkCheckGateways();
  uint8_t getLinkCheckMargin();
  bool setChannel(uint8_t channel, uint32_t frequency = 0l, uint8_t dr_min = 255, uint8_t dr_max = 255);
  bool setRx2Channel(uint32_t frequency, uint8_t dr);
  bool setChannelDCycle (uint8_t channel, float duty_cycle);
  bool setChannelStatus (uint8_t channel, bool status);
  bool setPowerIndex(uint8_t index);
  bool setDR(uint8_t dr);
  bool setADR(bool adr);
  bool setRX1Delay(uint16_t delay);
  bool setFCU(uint32_t fcu);
  bool setFCD(uint32_t fcd);
  bool checkValidModuleConnected(bool autoBaudFirst = false);
};

#endif


================================================
FILE: src/api/appData.proto
================================================
syntax = "proto2";

package api;

message AppData {
        optional bool light = 1;
        optional bool activate = 2;
}


================================================
FILE: src/api/deviceData.proto
================================================
syntax = "proto2";

package api;

message Location {
        optional float longitude = 1;
        optional float latitude = 2;
        optional int32 altitude = 3;
}

message DeviceData {
        optional bool motion = 1;
        optional uint32 water = 2;
        optional float temperature_celcius = 3;
        optional float temperature_fahrenheit = 4;
        optional float humidity = 5;

        optional Location location = 6;
        optional float level = 7;
        optional bool triggered = 8;
        optional bool actuator_active = 9;
        optional float actuator_time = 10;

        repeated uint32 analog_readings = 110;
}


================================================
FILE: src/appData.pb.c
================================================
/* Automatically generated nanopb constant definitions */
/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */

#include "appData.pb.h"

/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif



const pb_field_t api_AppData_fields[3] = {
    PB_FIELD(  1, BOOL    , OPTIONAL, STATIC  , FIRST, api_AppData, light, light, 0),
    PB_FIELD(  2, BOOL    , OPTIONAL, STATIC  , OTHER, api_AppData, activate, light, 0),
    PB_LAST_FIELD
};


/* @@protoc_insertion_point(eof) */


================================================
FILE: src/appData.pb.h
================================================
/* Automatically generated nanopb header */
/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */

#ifndef PB_API_APPDATA_PB_H_INCLUDED
#define PB_API_APPDATA_PB_H_INCLUDED
#include "pb.h"

/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif

#ifdef __cplusplus
extern "C" {
#endif

/* Struct definitions */
typedef struct _api_AppData {
    bool has_light;
    bool light;
    bool has_activate;
    bool activate;
/* @@protoc_insertion_point(struct:api_AppData) */
} api_AppData;

/* Default values for struct fields */

/* Initializer values for message structs */
#define api_AppData_init_default                 {false, 0, false, 0}
#define api_AppData_init_zero                    {false, 0, false, 0}

/* Field tags (for use in manual encoding/decoding) */
#define api_AppData_light_tag                    1
#define api_AppData_activate_tag                 2

/* Struct field encoding specification for nanopb */
extern const pb_field_t api_AppData_fields[3];

/* Maximum encoded size of messages (where known) */
#define api_AppData_size                         4

/* Message IDs (where set with "msgid" option) */
#ifdef PB_MSGID

#define APPDATA_MESSAGES \


#endif

#ifdef __cplusplus
} /* extern "C" */
#endif
/* @@protoc_insertion_point(eof) */

#endif


================================================
FILE: src/deviceData.pb.c
================================================
/* Automatically generated nanopb constant definitions */
/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */

#include "deviceData.pb.h"

/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif



const pb_field_t api_Location_fields[4] = {
    PB_FIELD(  1, FLOAT   , OPTIONAL, STATIC  , FIRST, api_Location, longitude, longitude, 0),
    PB_FIELD(  2, FLOAT   , OPTIONAL, STATIC  , OTHER, api_Location, latitude, longitude, 0),
    PB_FIELD(  3, INT32   , OPTIONAL, STATIC  , OTHER, api_Location, altitude, latitude, 0),
    PB_LAST_FIELD
};

const pb_field_t api_DeviceData_fields[12] = {
    PB_FIELD(  1, BOOL    , OPTIONAL, STATIC  , FIRST, api_DeviceData, motion, motion, 0),
    PB_FIELD(  2, UINT32  , OPTIONAL, STATIC  , OTHER, api_DeviceData, water, motion, 0),
    PB_FIELD(  3, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, temperature_celcius, water, 0),
    PB_FIELD(  4, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, temperature_fahrenheit, temperature_celcius, 0),
    PB_FIELD(  5, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, humidity, temperature_fahrenheit, 0),
    PB_FIELD(  6, MESSAGE , OPTIONAL, STATIC  , OTHER, api_DeviceData, location, humidity, &api_Location_fields),
    PB_FIELD(  7, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, level, location, 0),
    PB_FIELD(  8, BOOL    , OPTIONAL, STATIC  , OTHER, api_DeviceData, triggered, level, 0),
    PB_FIELD(  9, BOOL    , OPTIONAL, STATIC  , OTHER, api_DeviceData, actuator_active, triggered, 0),
    PB_FIELD( 10, FLOAT   , OPTIONAL, STATIC  , OTHER, api_DeviceData, actuator_time, actuator_active, 0),
    PB_FIELD(110, UINT32  , REPEATED, CALLBACK, OTHER, api_DeviceData, analog_readings, actuator_time, 0),
    PB_LAST_FIELD
};


/* Check that field information fits in pb_field_t */
#if !defined(PB_FIELD_32BIT)
/* If you get an error here, it means that you need to define PB_FIELD_32BIT
 * compile-time option. You can do that in pb.h or on compiler command line.
 * 
 * The reason you need to do this is that some of your messages contain tag
 * numbers or field sizes that are larger than what can fit in 8 or 16 bit
 * field descriptors.
 */
PB_STATIC_ASSERT((pb_membersize(api_DeviceData, location) < 65536), YOU_MUST_DEFINE_PB_FIELD_32BIT_FOR_MESSAGES_api_Location_api_DeviceData)
#endif

#if !defined(PB_FIELD_16BIT) && !defined(PB_FIELD_32BIT)
/* If you get an error here, it means that you need to define PB_FIELD_16BIT
 * compile-time option. You can do that in pb.h or on compiler command line.
 * 
 * The reason you need to do this is that some of your messages contain tag
 * numbers or field sizes that are larger than what can fit in the default
 * 8 bit descriptors.
 */
PB_STATIC_ASSERT((pb_membersize(api_DeviceData, location) < 256), YOU_MUST_DEFINE_PB_FIELD_16BIT_FOR_MESSAGES_api_Location_api_DeviceData)
#endif


/* @@protoc_insertion_point(eof) */


================================================
FILE: src/deviceData.pb.h
================================================
/* Automatically generated nanopb header */
/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */

#ifndef PB_API_DEVICEDATA_PB_H_INCLUDED
#define PB_API_DEVICEDATA_PB_H_INCLUDED
#include "pb.h"

/* @@protoc_insertion_point(includes) */
#if PB_PROTO_HEADER_VERSION != 30
#error Regenerate this file with the current version of nanopb generator.
#endif

#ifdef __cplusplus
extern "C" {
#endif

/* Struct definitions */
typedef struct _api_Location {
    bool has_longitude;
    float longitude;
    bool has_latitude;
    float latitude;
    bool has_altitude;
    int32_t altitude;
/* @@protoc_insertion_point(struct:api_Location) */
} api_Location;

typedef struct _api_DeviceData {
    bool has_motion;
    bool motion;
    bool has_water;
    uint32_t water;
    bool has_temperature_celcius;
    float temperature_celcius;
    bool has_temperature_fahrenheit;
    float temperature_fahrenheit;
    bool has_humidity;
    float humidity;
    bool has_location;
    api_Location location;
    bool has_level;
    float level;
    bool has_triggered;
    bool triggered;
    bool has_actuator_active;
    bool actuator_active;
    bool has_actuator_time;
    float actuator_time;
    pb_callback_t analog_readings;
/* @@protoc_insertion_point(struct:api_DeviceData) */
} api_DeviceData;

/* Default values for struct fields */

/* Initializer values for message structs */
#define api_Location_init_default                {false, 0, false, 0, false, 0}
#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}}
#define api_Location_init_zero                   {false, 0, false, 0, false, 0}
#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}}

/* Field tags (for use in manual encoding/decoding) */
#define api_Location_longitude_tag               1
#define api_Location_latitude_tag                2
#define api_Location_altitude_tag                3
#define api_DeviceData_motion_tag                1
#define api_DeviceData_water_tag                 2
#define api_DeviceData_temperature_celcius_tag   3
#define api_DeviceData_temperature_fahrenheit_tag 4
#define api_DeviceData_humidity_tag              5
#define api_DeviceData_location_tag              6
#define api_DeviceData_level_tag                 7
#define api_DeviceData_triggered_tag             8
#define api_DeviceData_actuator_active_tag       9
#define api_DeviceData_actuator_time_tag         10
#define api_DeviceData_analog_readings_tag       110

/* Struct field encoding specification for nanopb */
extern const pb_field_t api_Location_fields[4];
extern const pb_field_t api_DeviceData_fields[12];

/* Maximum encoded size of messages (where known) */
#define api_Location_size                        21
/* api_DeviceData_size depends on runtime parameters */

/* Message IDs (where set with "msgid" option) */
#ifdef PB_MSGID

#define DEVICEDATA_MESSAGES \


#endif

#ifdef __cplusplus
} /* extern "C" */
#endif
/* @@protoc_insertion_point(eof) */

#endif


================================================
FILE: src/pb.h
================================================
/* Common parts of the nanopb library. Most of these are quite low-level
 * stuff. For the high-level interface, see pb_encode.h and pb_decode.h.
 */

#ifndef PB_H_INCLUDED
#define PB_H_INCLUDED

/*****************************************************************
 * Nanopb compilation time options. You can change these here by *
 * uncommenting the lines, or on the compiler command line.      *
 *****************************************************************/

/* Enable support for dynamically allocated fields */
/* #define PB_ENABLE_MALLOC 1 */

/* Define this if your CPU / compiler combination does not support
 * unaligned memory access to packed structures. */
/* #define PB_NO_PACKED_STRUCTS 1 */

/* Increase the number of required fields that are tracked.
 * A compiler warning will tell if you need this. */
/* #define PB_MAX_REQUIRED_FIELDS 256 */

/* Add support for tag numbers > 255 and fields larger than 255 bytes. */
/* #define PB_FIELD_16BIT 1 */

/* Add support for tag numbers > 65536 and fields larger than 65536 bytes. */
/* #define PB_FIELD_32BIT 1 */

/* Disable support for error messages in order to save some code space. */
/* #define PB_NO_ERRMSG 1 */

/* Disable support for custom streams (support only memory buffers). */
/* #define PB_BUFFER_ONLY 1 */

/* Switch back to the old-style callback function signature.
 * This was the default until nanopb-0.2.1. */
/* #define PB_OLD_CALLBACK_STYLE */


/******************************************************************
 * You usually don't need to change anything below this line.     *
 * Feel free to look around and use the defined macros, though.   *
 ******************************************************************/


/* Version of the nanopb library. Just in case you want to check it in
 * your own program. */
#define NANOPB_VERSION nanopb-0.3.6

/* Include all the system headers needed by nanopb. You will need the
 * definitions of the following:
 * - strlen, memcpy, memset functions
 * - [u]int_least8_t, uint_fast8_t, [u]int_least16_t, [u]int32_t, [u]int64_t
 * - size_t
 * - bool
 *
 * If you don't have the standard header files, you can instead provide
 * a custom header that defines or includes all this. In that case,
 * define PB_SYSTEM_HEADER to the path of this file.
 */
#ifdef PB_SYSTEM_HEADER
#include PB_SYSTEM_HEADER
#else
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
#include <string.h>

#ifdef PB_ENABLE_MALLOC
#include <stdlib.h>
#endif
#endif

/* Macro for defining packed structures (compiler dependent).
 * This just reduces memory requirements, but is not required.
 */
#if defined(PB_NO_PACKED_STRUCTS)
    /* Disable struct packing */
#   define PB_PACKED_STRUCT_START
#   define PB_PACKED_STRUCT_END
#   define pb_packed
#elif defined(__GNUC__) || defined(__clang__)
    /* For GCC and clang */
#   define PB_PACKED_STRUCT_START
#   define PB_PACKED_STRUCT_END
#   define pb_packed __attribute__((packed))
#elif defined(__ICCARM__) || defined(__CC_ARM)
    /* For IAR ARM and Keil MDK-ARM compilers */
#   define PB_PACKED_STRUCT_START _Pragma("pack(push, 1)")
#   define PB_PACKED_STRUCT_END _Pragma("pack(pop)")
#   define pb_packed
#elif defined(_MSC_VER) && (_MSC_VER >= 1500)
    /* For Microsoft Visual C++ */
#   define PB_PACKED_STRUCT_START __pragma(pack(push, 1))
#   define PB_PACKED_STRUCT_END __pragma(pack(pop))
#   define pb_packed
#else
    /* Unknown compiler */
#   define PB_PACKED_STRUCT_START
#   define PB_PACKED_STRUCT_END
#   define pb_packed
#endif

/* Handly macro for suppressing unreferenced-parameter compiler warnings. */
#ifndef PB_UNUSED
#define PB_UNUSED(x) (void)(x)
#endif

/* Compile-time assertion, used for checking compatible compilation options.
 * If this does not work properly on your compiler, use
 * #define PB_NO_STATIC_ASSERT to disable it.
 *
 * But before doing that, check carefully the error message / place where it
 * comes from to see if the error has a real cause. Unfortunately the error
 * message is not always very clear to read, but you can see the reason better
 * in the place where the PB_STATIC_ASSERT macro was called.
 */
#ifndef PB_NO_STATIC_ASSERT
#ifndef PB_STATIC_ASSERT
#define PB_STATIC_ASSERT(COND,MSG) typedef char PB_STATIC_ASSERT_MSG(MSG, __LINE__, __COUNTER__)[(COND)?1:-1];
#define PB_STATIC_ASSERT_MSG(MSG, LINE, COUNTER) PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER)
#define PB_STATIC_ASSERT_MSG_(MSG, LINE, COUNTER) pb_static_assertion_##MSG##LINE##COUNTER
#endif
#else
#define PB_STATIC_ASSERT(COND,MSG)
#endif

/* Number of required fields to keep track of. */
#ifndef PB_MAX_REQUIRED_FIELDS
#define PB_MAX_REQUIRED_FIELDS 64
#endif

#if PB_MAX_REQUIRED_FIELDS < 64
#error You should not lower PB_MAX_REQUIRED_FIELDS from the default value (64).
#endif

/* List of possible field types. These are used in the autogenerated code.
 * Least-significant 4 bits tell the scalar type
 * Most-significant 4 bits specify repeated/required/packed etc.
 */

typedef uint_least8_t pb_type_t;

/**** Field data types ****/

/* Numeric types */
#define PB_LTYPE_VARINT  0x00 /* int32, int64, enum, bool */
#define PB_LTYPE_UVARINT 0x01 /* uint32, uint64 */
#define PB_LTYPE_SVARINT 0x02 /* sint32, sint64 */
#define PB_LTYPE_FIXED32 0x03 /* fixed32, sfixed32, float */
#define PB_LTYPE_FIXED64 0x04 /* fixed64, sfixed64, double */

/* Marker for last packable field type. */
#define PB_LTYPE_LAST_PACKABLE 0x04

/* Byte array with pre-allocated buffer.
 * data_size is the length of the allocated PB_BYTES_ARRAY structure. */
#define PB_LTYPE_BYTES 0x05

/* String with pre-allocated buffer.
 * data_size is the maximum length. */
#define PB_LTYPE_STRING 0x06

/* Submessage
 * submsg_fields is pointer to field descriptions */
#define PB_LTYPE_SUBMESSAGE 0x07

/* Extension pseudo-field
 * The field contains a pointer to pb_extension_t */
#define PB_LTYPE_EXTENSION 0x08

/* Number of declared LTYPES */
#define PB_LTYPES_COUNT 9
#define PB_LTYPE_MASK 0x0F

/**** Field repetition rules ****/

#define PB_HTYPE_REQUIRED 0x00
#define PB_HTYPE_OPTIONAL 0x10
#define PB_HTYPE_REPEATED 0x20
#define PB_HTYPE_ONEOF    0x30
#define PB_HTYPE_MASK     0x30

/**** Field allocation types ****/
 
#define PB_ATYPE_STATIC   0x00
#define PB_ATYPE_POINTER  0x80
#define PB_ATYPE_CALLBACK 0x40
#define PB_ATYPE_MASK     0xC0

#define PB_ATYPE(x) ((x) & PB_ATYPE_MASK)
#define PB_HTYPE(x) ((x) & PB_HTYPE_MASK)
#define PB_LTYPE(x) ((x) & PB_LTYPE_MASK)

/* Data type used for storing sizes of struct fields
 * and array counts.
 */
#if defined(PB_FIELD_32BIT)
    typedef uint32_t pb_size_t;
    typedef int32_t pb_ssize_t;
#elif defined(PB_FIELD_16BIT)
    typedef uint_least16_t pb_size_t;
    typedef int_least16_t pb_ssize_t;
#else
    typedef uint_least8_t pb_size_t;
    typedef int_least8_t pb_ssize_t;
#endif
#define PB_SIZE_MAX ((pb_size_t)-1)

/* Data type for storing encoded data and other byte streams.
 * This typedef exists to support platforms where uint8_t does not exist.
 * You can regard it as equivalent on uint8_t on other platforms.
 */
typedef uint_least8_t pb_byte_t;

/* This structure is used in auto-generated constants
 * to specify struct fields.
 * You can change field sizes if you need structures
 * larger than 256 bytes or field tags larger than 256.
 * The compiler should complain if your .proto has such
 * structures. Fix that by defining PB_FIELD_16BIT or
 * PB_FIELD_32BIT.
 */
PB_PACKED_STRUCT_START
typedef struct pb_field_s pb_field_t;
struct pb_field_s {
    pb_size_t tag;
    pb_type_t type;
    pb_size_t data_offset; /* Offset of field data, relative to previous field. */
    pb_ssize_t size_offset; /* Offset of array size or has-boolean, relative to data */
    pb_size_t data_size; /* Data size in bytes for a single item */
    pb_size_t array_size; /* Maximum number of entries in array */
    
    /* Field definitions for submessage
     * OR default value for all other non-array, non-callback types
     * If null, then field will zeroed. */
    const void *ptr;
} pb_packed;
PB_PACKED_STRUCT_END

/* Make sure that the standard integer types are of the expected sizes.
 * Otherwise fixed32/fixed64 fields can break.
 *
 * If you get errors here, it probably means that your stdint.h is not
 * correct for your platform.
 */
PB_STATIC_ASSERT(sizeof(int64_t) == 2 * sizeof(int32_t), INT64_T_WRONG_SIZE)
PB_STATIC_ASSERT(sizeof(uint64_t) == 2 * sizeof(uint32_t), UINT64_T_WRONG_SIZE)

/* This structure is used for 'bytes' arrays.
 * It has the number of bytes in the beginning, and after that an array.
 * Note that actual structs used will have a different length of bytes array.
 */
#define PB_BYTES_ARRAY_T(n) struct { pb_size_t size; pb_byte_t bytes[n]; }
#define PB_BYTES_ARRAY_T_ALLOCSIZE(n) ((size_t)n + offsetof(pb_bytes_array_t, bytes))

struct pb_bytes_array_s {
    pb_size_t size;
    pb_byte_t bytes[1];
};
typedef struct pb_bytes_array_s pb_bytes_array_t;

/* This structure is used for giving the callback function.
 * It is stored in the message structure and filled in by the method that
 * calls pb_decode.
 *
 * The decoding callback will be given a limited-length stream
 * If the wire type was string, the length is the length of the string.
 * If the wire type was a varint/fixed32/fixed64, the length is the length
 * of the actual value.
 * The function may be called multiple times (especially for repeated types,
 * but also otherwise if the message happens to contain the field multiple
 * times.)
 *
 * The encoding callback will receive the actual output stream.
 * It should write all the data in one call, including the field tag and
 * wire type. It can write multiple fields.
 *
 * The callback can be null if you want to skip a field.
 */
typedef struct pb_istream_s pb_istream_t;
typedef struct pb_ostream_s pb_ostream_t;
typedef struct pb_callback_s pb_callback_t;
struct pb_callback_s {
#ifdef PB_OLD_CALLBACK_STYLE
    /* Deprecated since nanopb-0.2.1 */
    union {
        bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void *arg);
        bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, const void *arg);
    } funcs;
#else
    /* New function signature, which allows modifying arg contents in callback. */
    union {
        bool (*decode)(pb_istream_t *stream, const pb_field_t *field, void **arg);
        bool (*encode)(pb_ostream_t *stream, const pb_field_t *field, void * const *arg);
    } funcs;
#endif    
    
    /* Free arg for use by callback */
    void *arg;
};

/* Wire types. Library user needs these only in encoder callbacks. */
typedef enum {
    PB_WT_VARINT = 0,
    PB_WT_64BIT  = 1,
    PB_WT_STRING = 2,
    PB_WT_32BIT  = 5
} pb_wire_type_t;

/* Structure for defining the handling of unknown/extension fields.
 * Usually the pb_extension_type_t structure is automatically generated,
 * while the pb_extension_t structure is created by the user. However,
 * if you want to catch all unknown fields, you can also create a custom
 * pb_extension_type_t with your own callback.
 */
typedef struct pb_extension_type_s pb_extension_type_t;
typedef struct pb_extension_s pb_extension_t;
struct pb_extension_type_s {
    /* Called for each unknown field in the message.
     * If you handle the field, read off all of its data and return true.
     * If you do not handle the field, do not read anything and return true.
     * If you run into an error, return false.
     * Set to NULL for default handler.
     */
    bool (*decode)(pb_istream_t *stream, pb_extension_t *extension,
                   uint32_t tag, pb_wire_type_t wire_type);
    
    /* Called once after all regular fields have been encoded.
     * If you have something to write, do so and return true.
     * If you do not have anything to write, just return true.
     * If you run into an error, return false.
     * Set to NULL for default handler.
     */
    bool (*encode)(pb_ostream_t *stream, const pb_extension_t *extension);
    
    /* Free field for use by the callback. */
    const void *arg;
};

struct pb_extension_s {
    /* Type describing the extension field. Usually you'll initialize
     * this to a pointer to the automatically generated structure. */
    const pb_extension_type_t *type;
    
    /* Destination for the decoded data. This must match the datatype
     * of the extension field. */
    void *dest;
    
    /* Pointer to the next extension handler, or NULL.
     * If this extension does not match a field, the next handler is
     * automatically called. */
    pb_extension_t *next;

    /* The decoder sets this to true if the extension was found.
     * Ignored for encoding. */
    bool found;
};

/* Memory allocation functions to use. You can define pb_realloc and
 * pb_free to custom functions if you want. */
#ifdef PB_ENABLE_MALLOC
#   ifndef pb_realloc
#       define pb_realloc(ptr, size) realloc(ptr, size)
#   endif
#   ifndef pb_free
#       define pb_free(ptr) free(ptr)
#   endif
#endif

/* This is used to inform about need to regenerate .pb.h/.pb.c files. */
#define PB_PROTO_HEADER_VERSION 30

/* These macros are used to declare pb_field_t's in the constant array. */
/* Size of a structure member, in bytes. */
#define pb_membersize(st, m) (sizeof ((st*)0)->m)
/* Number of entries in an array. */
#define pb_arraysize(st, m) (pb_membersize(st, m) / pb_membersize(st, m[0]))
/* Delta from start of one member to the start of another member. */
#define pb_delta(st, m1, m2) ((int)offsetof(st, m1) - (int)offsetof(st, m2))
/* Marks the end of the field list */
#define PB_LAST_FIELD {0,(pb_type_t) 0,0,0,0,0,0}

/* Macros for filling in the data_offset field */
/* data_offset for first field in a message */
#define PB_DATAOFFSET_FIRST(st, m1, m2) (offsetof(st, m1))
/* data_offset for subsequent fields */
#define PB_DATAOFFSET_OTHER(st, m1, m2) (offsetof(st, m1) - offsetof(st, m2) - pb_membersize(st, m2))
/* Choose first/other based on m1 == m2 (deprecated, remains for backwards compatibility) */
#define PB_DATAOFFSET_CHOOSE(st, m1, m2) (int)(offsetof(st, m1) == offsetof(st, m2) \
                                  ? PB_DATAOFFSET_FIRST(st, m1, m2) \
                                  : PB_DATAOFFSET_OTHER(st, m1, m2))

/* Required fields are the simplest. They just have delta (padding) from
 * previous field end, and the size of the field. Pointer is used for
 * submessages and default values.
 */
#define PB_REQUIRED_STATIC(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_STATIC | PB_HTYPE_REQUIRED | ltype, \
    fd, 0, pb_membersize(st, m), 0, ptr}

/* Optional fields add the delta to the has_ variable. */
#define PB_OPTIONAL_STATIC(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \
    fd, \
    pb_delta(st, has_ ## m, m), \
    pb_membersize(st, m), 0, ptr}

/* Repeated fields have a _count field and also the maximum number of entries. */
#define PB_REPEATED_STATIC(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_STATIC | PB_HTYPE_REPEATED | ltype, \
    fd, \
    pb_delta(st, m ## _count, m), \
    pb_membersize(st, m[0]), \
    pb_arraysize(st, m), ptr}

/* Allocated fields carry the size of the actual data, not the pointer */
#define PB_REQUIRED_POINTER(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_POINTER | PB_HTYPE_REQUIRED | ltype, \
    fd, 0, pb_membersize(st, m[0]), 0, ptr}

/* Optional fields don't need a has_ variable, as information would be redundant */
#define PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_POINTER | PB_HTYPE_OPTIONAL | ltype, \
    fd, 0, pb_membersize(st, m[0]), 0, ptr}

/* Repeated fields have a _count field and a pointer to array of pointers */
#define PB_REPEATED_POINTER(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_POINTER | PB_HTYPE_REPEATED | ltype, \
    fd, pb_delta(st, m ## _count, m), \
    pb_membersize(st, m[0]), 0, ptr}

/* Callbacks are much like required fields except with special datatype. */
#define PB_REQUIRED_CALLBACK(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REQUIRED | ltype, \
    fd, 0, pb_membersize(st, m), 0, ptr}

#define PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_CALLBACK | PB_HTYPE_OPTIONAL | ltype, \
    fd, 0, pb_membersize(st, m), 0, ptr}
    
#define PB_REPEATED_CALLBACK(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_CALLBACK | PB_HTYPE_REPEATED | ltype, \
    fd, 0, pb_membersize(st, m), 0, ptr}

/* Optional extensions don't have the has_ field, as that would be redundant. */
#define PB_OPTEXT_STATIC(tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_STATIC | PB_HTYPE_OPTIONAL | ltype, \
    0, \
    0, \
    pb_membersize(st, m), 0, ptr}

#define PB_OPTEXT_POINTER(tag, st, m, fd, ltype, ptr) \
    PB_OPTIONAL_POINTER(tag, st, m, fd, ltype, ptr)

#define PB_OPTEXT_CALLBACK(tag, st, m, fd, ltype, ptr) \
    PB_OPTIONAL_CALLBACK(tag, st, m, fd, ltype, ptr)

/* The mapping from protobuf types to LTYPEs is done using these macros. */
#define PB_LTYPE_MAP_BOOL       PB_LTYPE_VARINT
#define PB_LTYPE_MAP_BYTES      PB_LTYPE_BYTES
#define PB_LTYPE_MAP_DOUBLE     PB_LTYPE_FIXED64
#define PB_LTYPE_MAP_ENUM       PB_LTYPE_VARINT
#define PB_LTYPE_MAP_UENUM      PB_LTYPE_UVARINT
#define PB_LTYPE_MAP_FIXED32    PB_LTYPE_FIXED32
#define PB_LTYPE_MAP_FIXED64    PB_LTYPE_FIXED64
#define PB_LTYPE_MAP_FLOAT      PB_LTYPE_FIXED32
#define PB_LTYPE_MAP_INT32      PB_LTYPE_VARINT
#define PB_LTYPE_MAP_INT64      PB_LTYPE_VARINT
#define PB_LTYPE_MAP_MESSAGE    PB_LTYPE_SUBMESSAGE
#define PB_LTYPE_MAP_SFIXED32   PB_LTYPE_FIXED32
#define PB_LTYPE_MAP_SFIXED64   PB_LTYPE_FIXED64
#define PB_LTYPE_MAP_SINT32     PB_LTYPE_SVARINT
#define PB_LTYPE_MAP_SINT64     PB_LTYPE_SVARINT
#define PB_LTYPE_MAP_STRING     PB_LTYPE_STRING
#define PB_LTYPE_MAP_UINT32     PB_LTYPE_UVARINT
#define PB_LTYPE_MAP_UINT64     PB_LTYPE_UVARINT
#define PB_LTYPE_MAP_EXTENSION  PB_LTYPE_EXTENSION

/* This is the actual macro used in field descriptions.
 * It takes these arguments:
 * - Field tag number
 * - Field type:   BOOL, BYTES, DOUBLE, ENUM, UENUM, FIXED32, FIXED64,
 *                 FLOAT, INT32, INT64, MESSAGE, SFIXED32, SFIXED64
 *                 SINT32, SINT64, STRING, UINT32, UINT64 or EXTENSION
 * - Field rules:  REQUIRED, OPTIONAL or REPEATED
 * - Allocation:   STATIC or CALLBACK
 * - Placement: FIRST or OTHER, depending on if this is the first field in structure.
 * - Message name
 * - Field name
 * - Previous field name (or field name again for first field)
 * - Pointer to default value or submsg fields.
 */

#define PB_FIELD(tag, type, rules, allocation, placement, message, field, prevfield, ptr) \
        PB_ ## rules ## _ ## allocation(tag, message, field, \
        PB_DATAOFFSET_ ## placement(message, field, prevfield), \
        PB_LTYPE_MAP_ ## type, ptr)

/* Field description for oneof fields. This requires taking into account the
 * union name also, that's why a separate set of macros is needed.
 */
#define PB_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \
    fd, pb_delta(st, which_ ## u, u.m), \
    pb_membersize(st, u.m), 0, ptr}

#define PB_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \
    fd, pb_delta(st, which_ ## u, u.m), \
    pb_membersize(st, u.m[0]), 0, ptr}

#define PB_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \
        PB_ONEOF_ ## allocation(union_name, tag, message, field, \
        PB_DATAOFFSET_ ## placement(message, union_name.field, prevfield), \
        PB_LTYPE_MAP_ ## type, ptr)

#define PB_ANONYMOUS_ONEOF_STATIC(u, tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_STATIC | PB_HTYPE_ONEOF | ltype, \
    fd, pb_delta(st, which_ ## u, m), \
    pb_membersize(st, m), 0, ptr}

#define PB_ANONYMOUS_ONEOF_POINTER(u, tag, st, m, fd, ltype, ptr) \
    {tag, PB_ATYPE_POINTER | PB_HTYPE_ONEOF | ltype, \
    fd, pb_delta(st, which_ ## u, m), \
    pb_membersize(st, m[0]), 0, ptr}

#define PB_ANONYMOUS_ONEOF_FIELD(union_name, tag, type, rules, allocation, placement, message, field, prevfield, ptr) \
        PB_ANONYMOUS_ONEOF_ ## allocation(union_name, tag, message, field, \
        PB_DATAOFFSET_ ## placement(message, field, prevfield), \
        PB_LTYPE_MAP_ ## type, ptr)

/* These macros are used for giving out error messages.
 * They are mostly a debugging aid; the main error information
 * is the true/false return value from functions.
 * Some code space can be saved by disabling the error
 * messages if not used.
 *
 * PB_SET_ERROR() sets the error message if none has been set yet.
 *                msg must be a constant string literal.
 * PB_GET_ERROR() always returns a pointer to a string.
 * PB_RETURN_ERROR() sets the error and returns false from current
 *                   function.
 */
#ifdef PB_NO_ERRMSG
#define PB_SET_ERROR(stream, msg) PB_UNUSED(stream)
#define PB_GET_ERROR(stream) "(errmsg disabled)"
#else
#define PB_SET_ERROR(stream, msg) (stream->errmsg = (stream)->errmsg ? (stream)->errmsg : (msg))
#define PB_GET_ERROR(stream) ((stream)->errmsg ? (stream)->errmsg : "(none)")
#endif

#define PB_RETURN_ERROR(stream, msg) return PB_SET_ERROR(stream, msg), false

#endif


================================================
FILE: src/pb_common.c
================================================
/* pb_common.c: Common support functions for pb_encode.c and pb_decode.c.
 *
 * 2014 Petteri Aimonen <jpa@kapsi.fi>
 */

#include "pb_common.h"

bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct)
{
    iter->start = fields;
    iter->pos = fields;
    iter->required_field_index = 0;
    iter->dest_struct = dest_struct;
    iter->pData = (char*)dest_struct + iter->pos->data_offset;
    iter->pSize = (char*)iter->pData + iter->pos->size_offset;
    
    return (iter->pos->tag != 0);
}

bool pb_field_iter_next(pb_field_iter_t *iter)
{
    const pb_field_t *prev_field = iter->pos;

    if (prev_field->tag == 0)
    {
        /* Handle empty message types, where the first field is already the terminator.
         * In other cases, the iter->pos never points to the terminator. */
        return false;
    }
    
    iter->pos++;
    
    if (iter->pos->tag == 0)
    {
        /* Wrapped back to beginning, reinitialize */
        (void)pb_field_iter_begin(iter, iter->start, iter->dest_struct);
        return false;
    }
    else
    {
        /* Increment the pointers based on previous field size */
        size_t prev_size = prev_field->data_size;
    
        if (PB_HTYPE(prev_field->type) == PB_HTYPE_ONEOF &&
            PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)
        {
            /* Don't advance pointers inside unions */
            prev_size = 0;
            iter->pData = (char*)iter->pData - prev_field->data_offset;
        }
        else if (PB_ATYPE(prev_field->type) == PB_ATYPE_STATIC &&
                 PB_HTYPE(prev_field->type) == PB_HTYPE_REPEATED)
        {
            /* In static arrays, the data_size tells the size of a single entry and
             * array_size is the number of entries */
            prev_size *= prev_field->array_size;
        }
        else if (PB_ATYPE(prev_field->type) == PB_ATYPE_POINTER)
        {
            /* Pointer fields always have a constant size in the main structure.
             * The data_size only applies to the dynamically allocated area. */
            prev_size = sizeof(void*);
        }

        if (PB_HTYPE(prev_field->type) == PB_HTYPE_REQUIRED)
        {
            /* Count the required fields, in order to check their presence in the
             * decoder. */
            iter->required_field_index++;
        }
    
        iter->pData = (char*)iter->pData + prev_size + iter->pos->data_offset;
        iter->pSize = (char*)iter->pData + iter->pos->size_offset;
        return true;
    }
}

bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag)
{
    const pb_field_t *start = iter->pos;
    
    do {
        if (iter->pos->tag == tag &&
            PB_LTYPE(iter->pos->type) != PB_LTYPE_EXTENSION)
        {
            /* Found the wanted field */
            return true;
        }
        
        (void)pb_field_iter_next(iter);
    } while (iter->pos != start);
    
    /* Searched all the way back to start, and found nothing. */
    return false;
}




================================================
FILE: src/pb_common.h
================================================
/* pb_common.h: Common support functions for pb_encode.c and pb_decode.c.
 * These functions are rarely needed by applications directly.
 */

#ifndef PB_COMMON_H_INCLUDED
#define PB_COMMON_H_INCLUDED

#include "pb.h"

#ifdef __cplusplus
extern "C" {
#endif

/* Iterator for pb_field_t list */
struct pb_field_iter_s {
    const pb_field_t *start;       /* Start of the pb_field_t array */
    const pb_field_t *pos;         /* Current position of the iterator */
    unsigned required_field_index; /* Zero-based index that counts only the required fields */
    void *dest_struct;             /* Pointer to start of the structure */
    void *pData;                   /* Pointer to current field value */
    void *pSize;                   /* Pointer to count/has field */
};
typedef struct pb_field_iter_s pb_field_iter_t;

/* Initialize the field iterator structure to beginning.
 * Returns false if the message type is empty. */
bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields, void *dest_struct);

/* Advance the iterator to the next field.
 * Returns false when the iterator wraps back to the first field. */
bool pb_field_iter_next(pb_field_iter_t *iter);

/* Advance the iterator until it points at a field with the given tag.
 * Returns false if no such field exists. */
bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag);

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif



================================================
FILE: src/pb_decode.c
================================================
/* pb_decode.c -- decode a protobuf using minimal resources
 *
 * 2011 Petteri Aimonen <jpa@kapsi.fi>
 */

/* Use the GCC warn_unused_result attribute to check that all return values
 * are propagated correctly. On other compilers and gcc before 3.4.0 just
 * ignore the annotation.
 */
#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
    #define checkreturn
#else
    #define checkreturn __attribute__((warn_unused_result))
#endif

#include "pb.h"
#include "pb_decode.h"
#include "pb_common.h"

/**************************************
 * Declarations internal to this file *
 **************************************/

typedef bool (*pb_decoder_t)(pb_istream_t *stream, const pb_field_t *field, void *dest) checkreturn;

static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);
static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest);
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size);
static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension);
static bool checkreturn default_extension_decoder(pb_istream_t *stream, pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type);
static bool checkreturn decode_extension(pb_istream_t *stream, uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter);
static bool checkreturn find_extension_field(pb_field_iter_t *iter);
static void pb_field_set_to_default(pb_field_iter_t *iter);
static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct);
static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest);
static bool checkreturn pb_skip_varint(pb_istream_t *stream);
static bool checkreturn pb_skip_string(pb_istream_t *stream);

#ifdef PB_ENABLE_MALLOC
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size);
static bool checkreturn pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter);
static void pb_release_single_field(const pb_field_iter_t *iter);
#endif

/* --- Function pointers to field decoders ---
 * Order in the array must match pb_action_t LTYPE numbering.
 */
static const pb_decoder_t PB_DECODERS[PB_LTYPES_COUNT] = {
    &pb_dec_varint,
    &pb_dec_uvarint,
    &pb_dec_svarint,
    &pb_dec_fixed32,
    &pb_dec_fixed64,
    
    &pb_dec_bytes,
    &pb_dec_string,
    &pb_dec_submessage,
    NULL /* extensions */
};

/*******************************
 * pb_istream_t implementation *
 *******************************/

static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
{
    const pb_byte_t *source = (const pb_byte_t*)stream->state;
    stream->state = (pb_byte_t*)stream->state + count;
    
    if (buf != NULL)
    {
        while (count--)
            *buf++ = *source++;
    }
    
    return true;
}

bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count)
{
#ifndef PB_BUFFER_ONLY
	if (buf == NULL && stream->callback != buf_read)
	{
		/* Skip input bytes */
		pb_byte_t tmp[16];
		while (count > 16)
		{
			if (!pb_read(stream, tmp, 16))
				return false;
			
			count -= 16;
		}
		
		return pb_read(stream, tmp, count);
	}
#endif

    if (stream->bytes_left < count)
        PB_RETURN_ERROR(stream, "end-of-stream");
    
#ifndef PB_BUFFER_ONLY
    if (!stream->callback(stream, buf, count))
        PB_RETURN_ERROR(stream, "io error");
#else
    if (!buf_read(stream, buf, count))
        return false;
#endif
    
    stream->bytes_left -= count;
    return true;
}

/* Read a single byte from input stream. buf may not be NULL.
 * This is an optimization for the varint decoding. */
static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf)
{
    if (stream->bytes_left == 0)
        PB_RETURN_ERROR(stream, "end-of-stream");

#ifndef PB_BUFFER_ONLY
    if (!stream->callback(stream, buf, 1))
        PB_RETURN_ERROR(stream, "io error");
#else
    *buf = *(const pb_byte_t*)stream->state;
    stream->state = (pb_byte_t*)stream->state + 1;
#endif

    stream->bytes_left--;
    
    return true;    
}

pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize)
{
    pb_istream_t stream;
    /* Cast away the const from buf without a compiler error.  We are
     * careful to use it only in a const manner in the callbacks.
     */
    union {
        void *state;
        const void *c_state;
    } state;
#ifdef PB_BUFFER_ONLY
    stream.callback = NULL;
#else
    stream.callback = &buf_read;
#endif
    state.c_state = buf;
    stream.state = state.state;
    stream.bytes_left = bufsize;
#ifndef PB_NO_ERRMSG
    stream.errmsg = NULL;
#endif
    return stream;
}

/********************
 * Helper functions *
 ********************/

static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_t *dest)
{
    pb_byte_t byte;
    uint32_t result;
    
    if (!pb_readbyte(stream, &byte))
        return false;
    
    if ((byte & 0x80) == 0)
    {
        /* Quick case, 1 byte value */
        result = byte;
    }
    else
    {
        /* Multibyte case */
        uint_fast8_t bitpos = 7;
        result = byte & 0x7F;
        
        do
        {
            if (bitpos >= 32)
                PB_RETURN_ERROR(stream, "varint overflow");
            
            if (!pb_readbyte(stream, &byte))
                return false;
            
            result |= (uint32_t)(byte & 0x7F) << bitpos;
            bitpos = (uint_fast8_t)(bitpos + 7);
        } while (byte & 0x80);
   }
   
   *dest = result;
   return true;
}

bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
{
    pb_byte_t byte;
    uint_fast8_t bitpos = 0;
    uint64_t result = 0;
    
    do
    {
        if (bitpos >= 64)
            PB_RETURN_ERROR(stream, "varint overflow");
        
        if (!pb_readbyte(stream, &byte))
            return false;

        result |= (uint64_t)(byte & 0x7F) << bitpos;
        bitpos = (uint_fast8_t)(bitpos + 7);
    } while (byte & 0x80);
    
    *dest = result;
    return true;
}

bool checkreturn pb_skip_varint(pb_istream_t *stream)
{
    pb_byte_t byte;
    do
    {
        if (!pb_read(stream, &byte, 1))
            return false;
    } while (byte & 0x80);
    return true;
}

bool checkreturn pb_skip_string(pb_istream_t *stream)
{
    uint32_t length;
    if (!pb_decode_varint32(stream, &length))
        return false;
    
    return pb_read(stream, NULL, length);
}

bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof)
{
    uint32_t temp;
    *eof = false;
    *wire_type = (pb_wire_type_t) 0;
    *tag = 0;
    
    if (!pb_decode_varint32(stream, &temp))
    {
        if (stream->bytes_left == 0)
            *eof = true;

        return false;
    }
    
    if (temp == 0)
    {
        *eof = true; /* Special feature: allow 0-terminated messages. */
        return false;
    }
    
    *tag = temp >> 3;
    *wire_type = (pb_wire_type_t)(temp & 7);
    return true;
}

bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type)
{
    switch (wire_type)
    {
        case PB_WT_VARINT: return pb_skip_varint(stream);
        case PB_WT_64BIT: return pb_read(stream, NULL, 8);
        case PB_WT_STRING: return pb_skip_string(stream);
        case PB_WT_32BIT: return pb_read(stream, NULL, 4);
        default: PB_RETURN_ERROR(stream, "invalid wire_type");
    }
}

/* Read a raw value to buffer, for the purpose of passing it to callback as
 * a substream. Size is maximum size on call, and actual size on return.
 */
static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_type_t wire_type, pb_byte_t *buf, size_t *size)
{
    size_t max_size = *size;
    switch (wire_type)
    {
        case PB_WT_VARINT:
            *size = 0;
            do
            {
                (*size)++;
                if (*size > max_size) return false;
                if (!pb_read(stream, buf, 1)) return false;
            } while (*buf++ & 0x80);
            return true;
            
        case PB_WT_64BIT:
            *size = 8;
            return pb_read(stream, buf, 8);
        
        case PB_WT_32BIT:
            *size = 4;
            return pb_read(stream, buf, 4);
        
        default: PB_RETURN_ERROR(stream, "invalid wire_type");
    }
}

/* Decode string length from stream and return a substream with limited length.
 * Remember to close the substream using pb_close_string_substream().
 */
bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
    uint32_t size;
    if (!pb_decode_varint32(stream, &size))
        return false;
    
    *substream = *stream;
    if (substream->bytes_left < size)
        PB_RETURN_ERROR(stream, "parent stream too short");
    
    substream->bytes_left = size;
    stream->bytes_left -= size;
    return true;
}

void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream)
{
    stream->state = substream->state;

#ifndef PB_NO_ERRMSG
    stream->errmsg = substream->errmsg;
#endif
}

/*************************
 * Decode a single field *
 *************************/

static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
    pb_type_t type;
    pb_decoder_t func;
    
    type = iter->pos->type;
    func = PB_DECODERS[PB_LTYPE(type)];

    switch (PB_HTYPE(type))
    {
        case PB_HTYPE_REQUIRED:
            return func(stream, iter->pos, iter->pData);
            
        case PB_HTYPE_OPTIONAL:
            *(bool*)iter->pSize = true;
            return func(stream, iter->pos, iter->pData);
    
        case PB_HTYPE_REPEATED:
            if (wire_type == PB_WT_STRING
                && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
            {
                /* Packed array */
                bool status = true;
                pb_size_t *size = (pb_size_t*)iter->pSize;
                pb_istream_t substream;
                if (!pb_make_string_substream(stream, &substream))
                    return false;
                
                while (substream.bytes_left > 0 && *size < iter->pos->array_size)
                {
                    void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
                    if (!func(&substream, iter->pos, pItem))
                    {
                        status = false;
                        break;
                    }
                    (*size)++;
                }
                pb_close_string_substream(stream, &substream);
                
                if (substream.bytes_left != 0)
                    PB_RETURN_ERROR(stream, "array overflow");
                
                return status;
            }
            else
            {
                /* Repeated field */
                pb_size_t *size = (pb_size_t*)iter->pSize;
                void *pItem = (char*)iter->pData + iter->pos->data_size * (*size);
                if (*size >= iter->pos->array_size)
                    PB_RETURN_ERROR(stream, "array overflow");
                
                (*size)++;
                return func(stream, iter->pos, pItem);
            }

        case PB_HTYPE_ONEOF:
            *(pb_size_t*)iter->pSize = iter->pos->tag;
            if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
            {
                /* We memset to zero so that any callbacks are set to NULL.
                 * Then set any default values. */
                memset(iter->pData, 0, iter->pos->data_size);
                pb_message_set_to_defaults((const pb_field_t*)iter->pos->ptr, iter->pData);
            }
            return func(stream, iter->pos, iter->pData);

        default:
            PB_RETURN_ERROR(stream, "invalid field type");
    }
}

#ifdef PB_ENABLE_MALLOC
/* Allocate storage for the field and store the pointer at iter->pData.
 * array_size is the number of entries to reserve in an array.
 * Zero size is not allowed, use pb_free() for releasing.
 */
static bool checkreturn allocate_field(pb_istream_t *stream, void *pData, size_t data_size, size_t array_size)
{    
    void *ptr = *(void**)pData;
    
    if (data_size == 0 || array_size == 0)
        PB_RETURN_ERROR(stream, "invalid size");
    
    /* Check for multiplication overflows.
     * This code avoids the costly division if the sizes are small enough.
     * Multiplication is safe as long as only half of bits are set
     * in either multiplicand.
     */
    {
        const size_t check_limit = (size_t)1 << (sizeof(size_t) * 4);
        if (data_size >= check_limit || array_size >= check_limit)
        {
            const size_t size_max = (size_t)-1;
            if (size_max / array_size < data_size)
            {
                PB_RETURN_ERROR(stream, "size too large");
            }
        }
    }
    
    /* Allocate new or expand previous allocation */
    /* Note: on failure the old pointer will remain in the structure,
     * the message must be freed by caller also on error return. */
    ptr = pb_realloc(ptr, array_size * data_size);
    if (ptr == NULL)
        PB_RETURN_ERROR(stream, "realloc failed");
    
    *(void**)pData = ptr;
    return true;
}

/* Clear a newly allocated item in case it contains a pointer, or is a submessage. */
static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)
{
    if (PB_LTYPE(iter->pos->type) == PB_LTYPE_STRING ||
        PB_LTYPE(iter->pos->type) == PB_LTYPE_BYTES)
    {
        *(void**)pItem = NULL;
    }
    else if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
    {
        pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, pItem);
    }
}
#endif

static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
#ifndef PB_ENABLE_MALLOC
    PB_UNUSED(wire_type);
    PB_UNUSED(iter);
    PB_RETURN_ERROR(stream, "no malloc support");
#else
    pb_type_t type;
    pb_decoder_t func;
    
    type = iter->pos->type;
    func = PB_DECODERS[PB_LTYPE(type)];
    
    switch (PB_HTYPE(type))
    {
        case PB_HTYPE_REQUIRED:
        case PB_HTYPE_OPTIONAL:
        case PB_HTYPE_ONEOF:
            if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE &&
                *(void**)iter->pData != NULL)
            {
                /* Duplicate field, have to release the old allocation first. */
                pb_release_single_field(iter);
            }
        
            if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
            {
                *(pb_size_t*)iter->pSize = iter->pos->tag;
            }

            if (PB_LTYPE(type) == PB_LTYPE_STRING ||
                PB_LTYPE(type) == PB_LTYPE_BYTES)
            {
                return func(stream, iter->pos, iter->pData);
            }
            else
            {
                if (!allocate_field(stream, iter->pData, iter->pos->data_size, 1))
                    return false;
                
                initialize_pointer_field(*(void**)iter->pData, iter);
                return func(stream, iter->pos, *(void**)iter->pData);
            }
    
        case PB_HTYPE_REPEATED:
            if (wire_type == PB_WT_STRING
                && PB_LTYPE(type) <= PB_LTYPE_LAST_PACKABLE)
            {
                /* Packed array, multiple items come in at once. */
                bool status = true;
                pb_size_t *size = (pb_size_t*)iter->pSize;
                size_t allocated_size = *size;
                void *pItem;
                pb_istream_t substream;
                
                if (!pb_make_string_substream(stream, &substream))
                    return false;
                
                while (substream.bytes_left)
                {
                    if ((size_t)*size + 1 > allocated_size)
                    {
                        /* Allocate more storage. This tries to guess the
                         * number of remaining entries. Round the division
                         * upwards. */
                        allocated_size += (substream.bytes_left - 1) / iter->pos->data_size + 1;
                        
                        if (!allocate_field(&substream, iter->pData, iter->pos->data_size, allocated_size))
                        {
                            status = false;
                            break;
                        }
                    }

                    /* Decode the array entry */
                    pItem = *(char**)iter->pData + iter->pos->data_size * (*size);
                    initialize_pointer_field(pItem, iter);
                    if (!func(&substream, iter->pos, pItem))
                    {
                        status = false;
                        break;
                    }
                    
                    if (*size == PB_SIZE_MAX)
                    {
#ifndef PB_NO_ERRMSG
                        stream->errmsg = "too many array entries";
#endif
                        status = false;
                        break;
                    }
                    
                    (*size)++;
                }
                pb_close_string_substream(stream, &substream);
                
                return status;
            }
            else
            {
                /* Normal repeated field, i.e. only one item at a time. */
                pb_size_t *size = (pb_size_t*)iter->pSize;
                void *pItem;
                
                if (*size == PB_SIZE_MAX)
                    PB_RETURN_ERROR(stream, "too many array entries");
                
                (*size)++;
                if (!allocate_field(stream, iter->pData, iter->pos->data_size, *size))
                    return false;
            
                pItem = *(char**)iter->pData + iter->pos->data_size * (*size - 1);
                initialize_pointer_field(pItem, iter);
                return func(stream, iter->pos, pItem);
            }

        default:
            PB_RETURN_ERROR(stream, "invalid field type");
    }
#endif
}

static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
    pb_callback_t *pCallback = (pb_callback_t*)iter->pData;
    
#ifdef PB_OLD_CALLBACK_STYLE
    void *arg = pCallback->arg;
#else
    void **arg = &(pCallback->arg);
#endif
    
    if (pCallback->funcs.decode == NULL)
        return pb_skip_field(stream, wire_type);
    
    if (wire_type == PB_WT_STRING)
    {
        pb_istream_t substream;
        
        if (!pb_make_string_substream(stream, &substream))
            return false;
        
        do
        {
            if (!pCallback->funcs.decode(&substream, iter->pos, arg))
                PB_RETURN_ERROR(stream, "callback failed");
        } while (substream.bytes_left);
        
        pb_close_string_substream(stream, &substream);
        return true;
    }
    else
    {
        /* Copy the single scalar value to stack.
         * This is required so that we can limit the stream length,
         * which in turn allows to use same callback for packed and
         * not-packed fields. */
        pb_istream_t substream;
        pb_byte_t buffer[10];
        size_t size = sizeof(buffer);
        
        if (!read_raw_value(stream, wire_type, buffer, &size))
            return false;
        substream = pb_istream_from_buffer(buffer, size);
        
        return pCallback->funcs.decode(&substream, iter->pos, arg);
    }
}

static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
#ifdef PB_ENABLE_MALLOC
    /* When decoding an oneof field, check if there is old data that must be
     * released first. */
    if (PB_HTYPE(iter->pos->type) == PB_HTYPE_ONEOF)
    {
        if (!pb_release_union_field(stream, iter))
            return false;
    }
#endif

    switch (PB_ATYPE(iter->pos->type))
    {
        case PB_ATYPE_STATIC:
            return decode_static_field(stream, wire_type, iter);
        
        case PB_ATYPE_POINTER:
            return decode_pointer_field(stream, wire_type, iter);
        
        case PB_ATYPE_CALLBACK:
            return decode_callback_field(stream, wire_type, iter);
        
        default:
            PB_RETURN_ERROR(stream, "invalid field type");
    }
}

static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *extension)
{
    /* Fake a field iterator for the extension field.
     * It is not actually safe to advance this iterator, but decode_field
     * will not even try to. */
    const pb_field_t *field = (const pb_field_t*)extension->type->arg;
    (void)pb_field_iter_begin(iter, field, extension->dest);
    iter->pData = extension->dest;
    iter->pSize = &extension->found;
    
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
    {
        /* For pointer extensions, the pointer is stored directly
         * in the extension structure. This avoids having an extra
         * indirection. */
        iter->pData = &extension->dest;
    }
}

/* Default handler for extension fields. Expects a pb_field_t structure
 * in extension->type->arg. */
static bool checkreturn default_extension_decoder(pb_istream_t *stream,
    pb_extension_t *extension, uint32_t tag, pb_wire_type_t wire_type)
{
    const pb_field_t *field = (const pb_field_t*)extension->type->arg;
    pb_field_iter_t iter;
    
    if (field->tag != tag)
        return true;
    
    iter_from_extension(&iter, extension);
    extension->found = true;
    return decode_field(stream, wire_type, &iter);
}

/* Try to decode an unknown field as an extension field. Tries each extension
 * decoder in turn, until one of them handles the field or loop ends. */
static bool checkreturn decode_extension(pb_istream_t *stream,
    uint32_t tag, pb_wire_type_t wire_type, pb_field_iter_t *iter)
{
    pb_extension_t *extension = *(pb_extension_t* const *)iter->pData;
    size_t pos = stream->bytes_left;
    
    while (extension != NULL && pos == stream->bytes_left)
    {
        bool status;
        if (extension->type->decode)
            status = extension->type->decode(stream, extension, tag, wire_type);
        else
            status = default_extension_decoder(stream, extension, tag, wire_type);

        if (!status)
            return false;
        
        extension = extension->next;
    }
    
    return true;
}

/* Step through the iterator until an extension field is found or until all
 * entries have been checked. There can be only one extension field per
 * message. Returns false if no extension field is found. */
static bool checkreturn find_extension_field(pb_field_iter_t *iter)
{
    const pb_field_t *start = iter->pos;
    
    do {
        if (PB_LTYPE(iter->pos->type) == PB_LTYPE_EXTENSION)
            return true;
        (void)pb_field_iter_next(iter);
    } while (iter->pos != start);
    
    return false;
}

/* Initialize message fields to default values, recursively */
static void pb_field_set_to_default(pb_field_iter_t *iter)
{
    pb_type_t type;
    type = iter->pos->type;
    
    if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
    {
        pb_extension_t *ext = *(pb_extension_t* const *)iter->pData;
        while (ext != NULL)
        {
            pb_field_iter_t ext_iter;
            ext->found = false;
            iter_from_extension(&ext_iter, ext);
            pb_field_set_to_default(&ext_iter);
            ext = ext->next;
        }
    }
    else if (PB_ATYPE(type) == PB_ATYPE_STATIC)
    {
        bool init_data = true;
        if (PB_HTYPE(type) == PB_HTYPE_OPTIONAL)
        {
            /* Set has_field to false. Still initialize the optional field
             * itself also. */
            *(bool*)iter->pSize = false;
        }
        else if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
                 PB_HTYPE(type) == PB_HTYPE_ONEOF)
        {
            /* REPEATED: Set array count to 0, no need to initialize contents.
               ONEOF: Set which_field to 0. */
            *(pb_size_t*)iter->pSize = 0;
            init_data = false;
        }

        if (init_data)
        {
            if (PB_LTYPE(iter->pos->type) == PB_LTYPE_SUBMESSAGE)
            {
                /* Initialize submessage to defaults */
                pb_message_set_to_defaults((const pb_field_t *) iter->pos->ptr, iter->pData);
            }
            else if (iter->pos->ptr != NULL)
            {
                /* Initialize to default value */
                memcpy(iter->pData, iter->pos->ptr, iter->pos->data_size);
            }
            else
            {
                /* Initialize to zeros */
                memset(iter->pData, 0, iter->pos->data_size);
            }
        }
    }
    else if (PB_ATYPE(type) == PB_ATYPE_POINTER)
    {
        /* Initialize the pointer to NULL. */
        *(void**)iter->pData = NULL;
        
        /* Initialize array count to 0. */
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED ||
            PB_HTYPE(type) == PB_HTYPE_ONEOF)
        {
            *(pb_size_t*)iter->pSize = 0;
        }
    }
    else if (PB_ATYPE(type) == PB_ATYPE_CALLBACK)
    {
        /* Don't overwrite callback */
    }
}

static void pb_message_set_to_defaults(const pb_field_t fields[], void *dest_struct)
{
    pb_field_iter_t iter;

    if (!pb_field_iter_begin(&iter, fields, dest_struct))
        return; /* Empty message type */
    
    do
    {
        pb_field_set_to_default(&iter);
    } while (pb_field_iter_next(&iter));
}

/*********************
 * Decode all fields *
 *********************/

bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
    uint32_t fields_seen[(PB_MAX_REQUIRED_FIELDS + 31) / 32] = {0, 0};
    const uint32_t allbits = ~(uint32_t)0;
    uint32_t extension_range_start = 0;
    pb_field_iter_t iter;
    
    /* Return value ignored, as empty message types will be correctly handled by
     * pb_field_iter_find() anyway. */
    (void)pb_field_iter_begin(&iter, fields, dest_struct);
    
    while (stream->bytes_left)
    {
        uint32_t tag;
        pb_wire_type_t wire_type;
        bool eof;
        
        if (!pb_decode_tag(stream, &wire_type, &tag, &eof))
        {
            if (eof)
                break;
            else
                return false;
        }
        
        if (!pb_field_iter_find(&iter, tag))
        {
            /* No match found, check if it matches an extension. */
            if (tag >= extension_range_start)
            {
                if (!find_extension_field(&iter))
                    extension_range_start = (uint32_t)-1;
                else
                    extension_range_start = iter.pos->tag;
                
                if (tag >= extension_range_start)
                {
                    size_t pos = stream->bytes_left;
                
                    if (!decode_extension(stream, tag, wire_type, &iter))
                        return false;
                    
                    if (pos != stream->bytes_left)
                    {
                        /* The field was handled */
                        continue;                    
                    }
                }
            }
        
            /* No match found, skip data */
            if (!pb_skip_field(stream, wire_type))
                return false;
            continue;
        }
        
        if (PB_HTYPE(iter.pos->type) == PB_HTYPE_REQUIRED
            && iter.required_field_index < PB_MAX_REQUIRED_FIELDS)
        {
            uint32_t tmp = ((uint32_t)1 << (iter.required_field_index & 31));
            fields_seen[iter.required_field_index >> 5] |= tmp;
        }
            
        if (!decode_field(stream, wire_type, &iter))
            return false;
    }
    
    /* Check that all required fields were present. */
    {
        /* First figure out the number of required fields by
         * seeking to the end of the field array. Usually we
         * are already close to end after decoding.
         */
        unsigned req_field_count;
        pb_type_t last_type;
        unsigned i;
        do {
            req_field_count = iter.required_field_index;
            last_type = iter.pos->type;
        } while (pb_field_iter_next(&iter));
        
        /* Fixup if last field was also required. */
        if (PB_HTYPE(last_type) == PB_HTYPE_REQUIRED && iter.pos->tag != 0)
            req_field_count++;
        
        if (req_field_count > 0)
        {
            /* Check the whole words */
            for (i = 0; i < (req_field_count >> 5); i++)
            {
                if (fields_seen[i] != allbits)
                    PB_RETURN_ERROR(stream, "missing required field");
            }
            
            /* Check the remaining bits */
            if (fields_seen[req_field_count >> 5] != (allbits >> (32 - (req_field_count & 31))))
                PB_RETURN_ERROR(stream, "missing required field");
        }
    }
    
    return true;
}

bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
    bool status;
    pb_message_set_to_defaults(fields, dest_struct);
    status = pb_decode_noinit(stream, fields, dest_struct);
    
#ifdef PB_ENABLE_MALLOC
    if (!status)
        pb_release(fields, dest_struct);
#endif
    
    return status;
}

bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct)
{
    pb_istream_t substream;
    bool status;
    
    if (!pb_make_string_substream(stream, &substream))
        return false;
    
    status = pb_decode(&substream, fields, dest_struct);
    pb_close_string_substream(stream, &substream);
    return status;
}

#ifdef PB_ENABLE_MALLOC
/* Given an oneof field, if there has already been a field inside this oneof,
 * release it before overwriting with a different one. */
static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t *iter)
{
    pb_size_t old_tag = *(pb_size_t*)iter->pSize; /* Previous which_ value */
    pb_size_t new_tag = iter->pos->tag; /* New which_ value */

    if (old_tag == 0)
        return true; /* Ok, no old data in union */

    if (old_tag == new_tag)
        return true; /* Ok, old data is of same type => merge */

    /* Release old data. The find can fail if the message struct contains
     * invalid data. */
    if (!pb_field_iter_find(iter, old_tag))
        PB_RETURN_ERROR(stream, "invalid union tag");

    pb_release_single_field(iter);

    /* Restore iterator to where it should be.
     * This shouldn't fail unless the pb_field_t structure is corrupted. */
    if (!pb_field_iter_find(iter, new_tag))
        PB_RETURN_ERROR(stream, "iterator error");
    
    return true;
}

static void pb_release_single_field(const pb_field_iter_t *iter)
{
    pb_type_t type;
    type = iter->pos->type;

    if (PB_HTYPE(type) == PB_HTYPE_ONEOF)
    {
        if (*(pb_size_t*)iter->pSize != iter->pos->tag)
            return; /* This is not the current field in the union */
    }

    /* Release anything contained inside an extension or submsg.
     * This has to be done even if the submsg itself is statically
     * allocated. */
    if (PB_LTYPE(type) == PB_LTYPE_EXTENSION)
    {
        /* Release fields from all extensions in the linked list */
        pb_extension_t *ext = *(pb_extension_t**)iter->pData;
        while (ext != NULL)
        {
            pb_field_iter_t ext_iter;
            iter_from_extension(&ext_iter, ext);
            pb_release_single_field(&ext_iter);
            ext = ext->next;
        }
    }
    else if (PB_LTYPE(type) == PB_LTYPE_SUBMESSAGE)
    {
        /* Release fields in submessage or submsg array */
        void *pItem = iter->pData;
        pb_size_t count = 1;
        
        if (PB_ATYPE(type) == PB_ATYPE_POINTER)
        {
            pItem = *(void**)iter->pData;
        }
        
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
        {
            count = *(pb_size_t*)iter->pSize;

            if (PB_ATYPE(type) == PB_ATYPE_STATIC && count > iter->pos->array_size)
            {
                /* Protect against corrupted _count fields */
                count = iter->pos->array_size;
            }
        }
        
        if (pItem)
        {
            while (count--)
            {
                pb_release((const pb_field_t*)iter->pos->ptr, pItem);
                pItem = (char*)pItem + iter->pos->data_size;
            }
        }
    }
    
    if (PB_ATYPE(type) == PB_ATYPE_POINTER)
    {
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED &&
            (PB_LTYPE(type) == PB_LTYPE_STRING ||
             PB_LTYPE(type) == PB_LTYPE_BYTES))
        {
            /* Release entries in repeated string or bytes array */
            void **pItem = *(void***)iter->pData;
            pb_size_t count = *(pb_size_t*)iter->pSize;
            while (count--)
            {
                pb_free(*pItem);
                *pItem++ = NULL;
            }
        }
        
        if (PB_HTYPE(type) == PB_HTYPE_REPEATED)
        {
            /* We are going to release the array, so set the size to 0 */
            *(pb_size_t*)iter->pSize = 0;
        }
        
        /* Release main item */
        pb_free(*(void**)iter->pData);
        *(void**)iter->pData = NULL;
    }
}

void pb_release(const pb_field_t fields[], void *dest_struct)
{
    pb_field_iter_t iter;
    
    if (!dest_struct)
        return; /* Ignore NULL pointers, similar to free() */

    if (!pb_field_iter_begin(&iter, fields, dest_struct))
        return; /* Empty message type */
    
    do
    {
        pb_release_single_field(&iter);
    } while (pb_field_iter_next(&iter));
}
#endif

/* Field decoders */

bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
{
    uint64_t value;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    if (value & 1)
        *dest = (int64_t)(~(value >> 1));
    else
        *dest = (int64_t)(value >> 1);
    
    return true;
}

bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
{
    pb_byte_t bytes[4];

    if (!pb_read(stream, bytes, 4))
        return false;
    
    *(uint32_t*)dest = ((uint32_t)bytes[0] << 0) |
                       ((uint32_t)bytes[1] << 8) |
                       ((uint32_t)bytes[2] << 16) |
                       ((uint32_t)bytes[3] << 24);
    return true;
}

bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
{
    pb_byte_t bytes[8];

    if (!pb_read(stream, bytes, 8))
        return false;
    
    *(uint64_t*)dest = ((uint64_t)bytes[0] << 0) |
                       ((uint64_t)bytes[1] << 8) |
                       ((uint64_t)bytes[2] << 16) |
                       ((uint64_t)bytes[3] << 24) |
                       ((uint64_t)bytes[4] << 32) |
                       ((uint64_t)bytes[5] << 40) |
                       ((uint64_t)bytes[6] << 48) |
                       ((uint64_t)bytes[7] << 56);
    
    return true;
}

static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    uint64_t value;
    int64_t svalue;
    int64_t clamped;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    /* See issue 97: Google's C++ protobuf allows negative varint values to
     * be cast as int32_t, instead of the int64_t that should be used when
     * encoding. Previous nanopb versions had a bug in encoding. In order to
     * not break decoding of such messages, we cast <=32 bit fields to
     * int32_t first to get the sign correct.
     */
    if (field->data_size == sizeof(int64_t))
        svalue = (int64_t)value;
    else
        svalue = (int32_t)value;

    /* Cast to the proper field size, while checking for overflows */
    if (field->data_size == sizeof(int64_t))
        clamped = *(int64_t*)dest = svalue;
    else if (field->data_size == sizeof(int32_t))
        clamped = *(int32_t*)dest = (int32_t)svalue;
    else if (field->data_size == sizeof(int_least16_t))
        clamped = *(int_least16_t*)dest = (int_least16_t)svalue;
    else if (field->data_size == sizeof(int_least8_t))
        clamped = *(int_least8_t*)dest = (int_least8_t)svalue;
    else
        PB_RETURN_ERROR(stream, "invalid data_size");

    if (clamped != svalue)
        PB_RETURN_ERROR(stream, "integer too large");
    
    return true;
}

static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    uint64_t value, clamped;
    if (!pb_decode_varint(stream, &value))
        return false;
    
    /* Cast to the proper field size, while checking for overflows */
    if (field->data_size == sizeof(uint64_t))
        clamped = *(uint64_t*)dest = value;
    else if (field->data_size == sizeof(uint32_t))
        clamped = *(uint32_t*)dest = (uint32_t)value;
    else if (field->data_size == sizeof(uint_least16_t))
        clamped = *(uint_least16_t*)dest = (uint_least16_t)value;
    else if (field->data_size == sizeof(uint_least8_t))
        clamped = *(uint_least8_t*)dest = (uint_least8_t)value;
    else
        PB_RETURN_ERROR(stream, "invalid data_size");
    
    if (clamped != value)
        PB_RETURN_ERROR(stream, "integer too large");

    return true;
}

static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    int64_t value, clamped;
    if (!pb_decode_svarint(stream, &value))
        return false;
    
    /* Cast to the proper field size, while checking for overflows */
    if (field->data_size == sizeof(int64_t))
        clamped = *(int64_t*)dest = value;
    else if (field->data_size == sizeof(int32_t))
        clamped = *(int32_t*)dest = (int32_t)value;
    else if (field->data_size == sizeof(int_least16_t))
        clamped = *(int_least16_t*)dest = (int_least16_t)value;
    else if (field->data_size == sizeof(int_least8_t))
        clamped = *(int_least8_t*)dest = (int_least8_t)value;
    else
        PB_RETURN_ERROR(stream, "invalid data_size");

    if (clamped != value)
        PB_RETURN_ERROR(stream, "integer too large");
    
    return true;
}

static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    PB_UNUSED(field);
    return pb_decode_fixed32(stream, dest);
}

static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    PB_UNUSED(field);
    return pb_decode_fixed64(stream, dest);
}

static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    uint32_t size;
    size_t alloc_size;
    pb_bytes_array_t *bdest;
    
    if (!pb_decode_varint32(stream, &size))
        return false;
    
    if (size > PB_SIZE_MAX)
        PB_RETURN_ERROR(stream, "bytes overflow");
    
    alloc_size = PB_BYTES_ARRAY_T_ALLOCSIZE(size);
    if (size > alloc_size)
        PB_RETURN_ERROR(stream, "size too large");
    
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
    {
#ifndef PB_ENABLE_MALLOC
        PB_RETURN_ERROR(stream, "no malloc support");
#else
        if (!allocate_field(stream, dest, alloc_size, 1))
            return false;
        bdest = *(pb_bytes_array_t**)dest;
#endif
    }
    else
    {
        if (alloc_size > field->data_size)
            PB_RETURN_ERROR(stream, "bytes overflow");
        bdest = (pb_bytes_array_t*)dest;
    }

    bdest->size = (pb_size_t)size;
    return pb_read(stream, bdest->bytes, size);
}

static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    uint32_t size;
    size_t alloc_size;
    bool status;
    if (!pb_decode_varint32(stream, &size))
        return false;
    
    /* Space for null terminator */
    alloc_size = size + 1;
    
    if (alloc_size < size)
        PB_RETURN_ERROR(stream, "size too large");
    
    if (PB_ATYPE(field->type) == PB_ATYPE_POINTER)
    {
#ifndef PB_ENABLE_MALLOC
        PB_RETURN_ERROR(stream, "no malloc support");
#else
        if (!allocate_field(stream, dest, alloc_size, 1))
            return false;
        dest = *(void**)dest;
#endif
    }
    else
    {
        if (alloc_size > field->data_size)
            PB_RETURN_ERROR(stream, "string overflow");
    }
    
    status = pb_read(stream, (pb_byte_t*)dest, size);
    *((pb_byte_t*)dest + size) = 0;
    return status;
}

static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb_field_t *field, void *dest)
{
    bool status;
    pb_istream_t substream;
    const pb_field_t* submsg_fields = (const pb_field_t*)field->ptr;
    
    if (!pb_make_string_substream(stream, &substream))
        return false;
    
    if (field->ptr == NULL)
        PB_RETURN_ERROR(stream, "invalid field descriptor");
    
    /* New array entries need to be initialized, while required and optional
     * submessages have already been initialized in the top-level pb_decode. */
    if (PB_HTYPE(field->type) == PB_HTYPE_REPEATED)
        status = pb_decode(&substream, submsg_fields, dest);
    else
        status = pb_decode_noinit(&substream, submsg_fields, dest);
    
    pb_close_string_substream(stream, &substream);
    return status;
}


================================================
FILE: src/pb_decode.h
================================================
/* pb_decode.h: Functions to decode protocol buffers. Depends on pb_decode.c.
 * The main function is pb_decode. You also need an input stream, and the
 * field descriptions created by nanopb_generator.py.
 */

#ifndef PB_DECODE_H_INCLUDED
#define PB_DECODE_H_INCLUDED

#include "pb.h"

#ifdef __cplusplus
extern "C" {
#endif

/* Structure for defining custom input streams. You will need to provide
 * a callback function to read the bytes from your storage, which can be
 * for example a file or a network socket.
 * 
 * The callback must conform to these rules:
 *
 * 1) Return false on IO errors. This will cause decoding to abort.
 * 2) You can use state to store your own data (e.g. buffer pointer),
 *    and rely on pb_read to verify that no-body reads past bytes_left.
 * 3) Your callback may be used with substreams, in which case bytes_left
 *    is different than from the main stream. Don't use bytes_left to compute
 *    any pointers.
 */
struct pb_istream_s
{
#ifdef PB_BUFFER_ONLY
    /* Callback pointer is not used in buffer-only configuration.
     * Having an int pointer here allows binary compatibility but
     * gives an error if someone tries to assign callback function.
     */
    int *callback;
#else
    bool (*callback)(pb_istream_t *stream, pb_byte_t *buf, size_t count);
#endif

    void *state; /* Free field for use by callback implementation */
    size_t bytes_left;
    
#ifndef PB_NO_ERRMSG
    const char *errmsg;
#endif
};

/***************************
 * Main decoding functions *
 ***************************/
 
/* Decode a single protocol buffers message from input stream into a C structure.
 * Returns true on success, false on any failure.
 * The actual struct pointed to by dest must match the description in fields.
 * Callback fields of the destination structure must be initialized by caller.
 * All other fields will be initialized by this function.
 *
 * Example usage:
 *    MyMessage msg = {};
 *    uint8_t buffer[64];
 *    pb_istream_t stream;
 *    
 *    // ... read some data into buffer ...
 *
 *    stream = pb_istream_from_buffer(buffer, count);
 *    pb_decode(&stream, MyMessage_fields, &msg);
 */
bool pb_decode(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);

/* Same as pb_decode, except does not initialize the destination structure
 * to default values. This is slightly faster if you need no default values
 * and just do memset(struct, 0, sizeof(struct)) yourself.
 *
 * This can also be used for 'merging' two messages, i.e. update only the
 * fields that exist in the new message.
 *
 * Note: If this function returns with an error, it will not release any
 * dynamically allocated fields. You will need to call pb_release() yourself.
 */
bool pb_decode_noinit(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);

/* Same as pb_decode, except expects the stream to start with the message size
 * encoded as varint. Corresponds to parseDelimitedFrom() in Google's
 * protobuf API.
 */
bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[], void *dest_struct);

#ifdef PB_ENABLE_MALLOC
/* Release any allocated pointer fields. If you use dynamic allocation, you should
 * call this for any successfully decoded message when you are done with it. If
 * pb_decode() returns with an error, the message is already released.
 */
void pb_release(const pb_field_t fields[], void *dest_struct);
#endif


/**************************************
 * Functions for manipulating streams *
 **************************************/

/* Create an input stream for reading from a memory buffer.
 *
 * Alternatively, you can use a custom stream that reads directly from e.g.
 * a file or a network socket.
 */
pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize);

/* Function to read from a pb_istream_t. You can use this if you need to
 * read some custom header data, or to read data in field callbacks.
 */
bool pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t count);


/************************************************
 * Helper functions for writing field callbacks *
 ************************************************/

/* Decode the tag for the next field in the stream. Gives the wire type and
 * field tag. At end of the message, returns false and sets eof to true. */
bool pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wire_type, uint32_t *tag, bool *eof);

/* Skip the field payload data, given the wire type. */
bool pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire_type);

/* Decode an integer in the varint format. This works for bool, enum, int32,
 * int64, uint32 and uint64 field types. */
bool pb_decode_varint(pb_istream_t *stream, uint64_t *dest);

/* Decode an integer in the zig-zagged svarint format. This works for sint32
 * and sint64. */
bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest);

/* Decode a fixed32, sfixed32 or float value. You need to pass a pointer to
 * a 4-byte wide C variable. */
bool pb_decode_fixed32(pb_istream_t *stream, void *dest);

/* Decode a fixed64, sfixed64 or double value. You need to pass a pointer to
 * a 8-byte wide C variable. */
bool pb_decode_fixed64(pb_istream_t *stream, void *dest);

/* Make a limited-length substream for reading a PB_WT_STRING field. */
bool pb_make_string_substream(pb_istream_t *stream, pb_istream_t *substream);
void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *substream);

#ifdef __cplusplus
} /* extern "C" */
#endif

#endif


================================================
FILE: src/pb_encode.c
================================================
/* pb_encode.c -- encode a protobuf using minimal resources
 *
 * 2011 Petteri Aimonen <jpa@kapsi.fi>
 */

#include "pb.h"
#include "pb_encode.h"
#include "pb_common.h"

/* Use the GCC warn_unused_result attribute to check that all return values
 * are propagated correctly. On other compilers and gcc before 3.4.0 just
 * ignore the annotation.
 */
#if !defined(__GNUC__) || ( __GNUC__ < 3) || (__GNUC__ == 3 && __GNUC_MINOR__ < 4)
    #define checkreturn
#else
    #define checkreturn __attribute__((warn_unused_result))
#endif

/**************************************
 * Declarations internal to this file *
 **************************************/
typedef bool (*pb_encoder_t)(pb_ostream_t *stream, const pb_field_t *field, const void *src) checkreturn;

static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t *buf, size_t count);
static bool checkreturn encode_array(pb_ostream_t *stream, const pb_field_t *field, const void *pData, size_t count, pb_encoder_t func);
static bool checkreturn encode_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData);
static bool checkreturn default_extension_encoder(pb_ostream_t *stream, const pb_extension_t *extension);
static bool checkreturn encode_extension_field(pb_ostream_t *stream, const pb_field_t *field, const void *pData);
static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_field_t *field, const void *src);
static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb_field_t *field, const void *src);

/* --- Function pointers to field encoders ---
 * Order in the array must match pb_action_t LTYPE numbering.
 */
static const pb_encoder_t PB_ENCODERS[PB_LTYPES_COUNT] = {
    &pb_enc_varint,
    &pb_enc_uvarint,
    &pb_enc_svarint,
    &pb_enc_fixed32,
    &pb_enc_fixed64,

    &pb_enc_bytes,
    &pb_enc_string,
    &pb_enc_submessage,
    NULL /* extensions */
};

/*******************************
 * pb_ostream_t implementation *
 *******************************/

static bool checkreturn buf_write(pb_ostream_t *st
Download .txt
gitextract_010a_2wt/

├── .editorconfig
├── .gitignore
├── .travis.yml
├── AUTHORS
├── CONTRIBUTING.md
├── LICENSE
├── Makefile
├── README.md
├── docs/
│   ├── CayenneLPP.md
│   ├── RN2903A-programming.docx
│   ├── RN2903A-uart-bootloader.docx
│   ├── TheThingsMessage.md
│   └── TheThingsNetwork.md
├── examples/
│   ├── CayenneLPP/
│   │   └── CayenneLPP.ino
│   ├── CheckModule/
│   │   └── CheckModule.ino
│   ├── DeviceInfo/
│   │   └── DeviceInfo.ino
│   ├── PassThrough/
│   │   └── PassThrough.ino
│   ├── QuickStart/
│   │   ├── Converter.js
│   │   ├── Decoder.js
│   │   ├── Encoder.js
│   │   ├── QuickStart.ino
│   │   └── Validator.js
│   ├── Receive/
│   │   └── Receive.ino
│   ├── ReceiveClassC/
│   │   └── ReceiveClassC.ino
│   ├── SendABP/
│   │   └── SendABP.ino
│   ├── SendOTAA/
│   │   └── SendOTAA.ino
│   ├── Sensors/
│   │   ├── DHT/
│   │   │   └── DHT.ino
│   │   └── LightSensor/
│   │       └── LightSensor.ino
│   ├── TheThingsMessage/
│   │   ├── Receive/
│   │   │   └── Receive.ino
│   │   └── Send/
│   │       └── Send.ino
│   └── Workshop/
│       └── Workshop.ino
├── keywords.txt
├── library.properties
├── src/
│   ├── CayenneLPP.cpp
│   ├── CayenneLPP.h
│   ├── TheThingsMessage.cpp
│   ├── TheThingsMessage.h
│   ├── TheThingsNetwork.cpp
│   ├── TheThingsNetwork.h
│   ├── api/
│   │   ├── appData.proto
│   │   └── deviceData.proto
│   ├── appData.pb.c
│   ├── appData.pb.h
│   ├── deviceData.pb.c
│   ├── deviceData.pb.h
│   ├── pb.h
│   ├── pb_common.c
│   ├── pb_common.h
│   ├── pb_decode.c
│   ├── pb_decode.h
│   ├── pb_encode.c
│   └── pb_encode.h
└── test/
    ├── TheThingsMessage/
    │   └── TheThingsMessage.ino
    ├── TheThingsNetwork/
    │   └── TheThingsNetwork.ino
    └── verify
Download .txt
SYMBOL INDEX (126 symbols across 17 files)

FILE: examples/QuickStart/Converter.js
  function Converter (line 1) | function Converter(decoded, port) {

FILE: examples/QuickStart/Decoder.js
  function Decoder (line 1) | function Decoder(bytes, port) {

FILE: examples/QuickStart/Encoder.js
  function Encoder (line 1) | function Encoder(object, port) {

FILE: examples/QuickStart/Validator.js
  function Validator (line 1) | function Validator(converted, port) {

FILE: src/CayenneLPP.h
  function class (line 41) | class CayenneLPP

FILE: src/TheThingsMessage.h
  type api_DeviceData (line 14) | typedef api_DeviceData devicedata_t;
  type api_AppData (line 15) | typedef api_AppData appdata_t;
  function class (line 17) | class TheThingsMessage

FILE: src/TheThingsNetwork.cpp
  function pgmstrcmp (line 326) | int pgmstrcmp(const char *str1, uint8_t str2Index, uint8_t table = CMP_T...
  function digits (line 346) | uint8_t digits(uint8_t port)
  function receivedPort (line 359) | uint8_t receivedPort(const char *s)
  type ttn_modem_status_t (line 455) | enum ttn_modem_status_t
  type ttn_modem_status_t (line 462) | enum ttn_modem_status_t
  function ttn_response_code_t (line 534) | ttn_response_code_t TheThingsNetwork::getLastError(){
  function ttn_response_t (line 807) | ttn_response_t TheThingsNetwork::parseBytes(){
  function ttn_response_t (line 840) | ttn_response_t TheThingsNetwork::sendBytes(const uint8_t *payload, size_...
  function ttn_response_t (line 872) | ttn_response_t TheThingsNetwork::poll(port_t port, bool confirm, bool mo...

FILE: src/TheThingsNetwork.h
  type port_t (line 30) | typedef uint8_t port_t;
  type ttn_response_t (line 32) | enum ttn_response_t
  type ttn_fp_t (line 41) | enum ttn_fp_t
  type lorawan_class_t (line 52) | enum lorawan_class_t
  type ttn_response_code_t (line 59) | enum ttn_response_code_t
  type ttn_modem_status_t (line 76) | enum ttn_modem_status_t
  function class (line 90) | class TheThingsNetwork

FILE: src/appData.pb.h
  type api_AppData (line 18) | typedef struct _api_AppData {

FILE: src/deviceData.pb.h
  type api_Location (line 18) | typedef struct _api_Location {
  type api_DeviceData (line 28) | typedef struct _api_DeviceData {

FILE: src/pb.h
  type uint_least8_t (line 143) | typedef uint_least8_t pb_type_t;
  type pb_size_t (line 200) | typedef uint32_t pb_size_t;
  type pb_ssize_t (line 201) | typedef int32_t pb_ssize_t;
  type uint_least16_t (line 203) | typedef uint_least16_t pb_size_t;
  type int_least16_t (line 204) | typedef int_least16_t pb_ssize_t;
  type uint_least8_t (line 206) | typedef uint_least8_t pb_size_t;
  type int_least8_t (line 207) | typedef int_least8_t pb_ssize_t;
  type uint_least8_t (line 215) | typedef uint_least8_t pb_byte_t;
  type pb_field_s (line 226) | struct pb_field_s
  type pb_field_s (line 227) | struct pb_field_s {
  function PB_PACKED_STRUCT_END (line 240) | PB_PACKED_STRUCT_END
  type pb_bytes_array_s (line 258) | struct pb_bytes_array_s {
  type pb_bytes_array_t (line 262) | typedef struct pb_bytes_array_s pb_bytes_array_t;
  type pb_istream_t (line 282) | typedef struct pb_istream_s pb_istream_t;
  type pb_ostream_t (line 283) | typedef struct pb_ostream_s pb_ostream_t;
  type pb_callback_t (line 284) | typedef struct pb_callback_s pb_callback_t;
  type pb_callback_s (line 285) | struct pb_callback_s {
  type pb_wire_type_t (line 305) | typedef enum {
  type pb_extension_type_t (line 318) | typedef struct pb_extension_type_s pb_extension_type_t;
  type pb_extension_t (line 319) | typedef struct pb_extension_s pb_extension_t;
  type pb_extension_type_s (line 320) | struct pb_extension_type_s {
  type pb_extension_s (line 342) | struct pb_extension_s {

FILE: src/pb_common.c
  function pb_field_iter_begin (line 8) | bool pb_field_iter_begin(pb_field_iter_t *iter, const pb_field_t *fields...
  function pb_field_iter_next (line 20) | bool pb_field_iter_next(pb_field_iter_t *iter)
  function pb_field_iter_find (line 78) | bool pb_field_iter_find(pb_field_iter_t *iter, uint32_t tag)

FILE: src/pb_common.h
  type pb_field_iter_s (line 15) | struct pb_field_iter_s {
  type pb_field_iter_t (line 23) | typedef struct pb_field_iter_s pb_field_iter_t;

FILE: src/pb_decode.c
  function buf_read (line 75) | static bool checkreturn buf_read(pb_istream_t *stream, pb_byte_t *buf, s...
  function pb_read (line 89) | bool checkreturn pb_read(pb_istream_t *stream, pb_byte_t *buf, size_t co...
  function pb_readbyte (line 125) | static bool checkreturn pb_readbyte(pb_istream_t *stream, pb_byte_t *buf)
  function pb_istream_t (line 143) | pb_istream_t pb_istream_from_buffer(const pb_byte_t *buf, size_t bufsize)
  function pb_decode_varint32 (line 171) | static bool checkreturn pb_decode_varint32(pb_istream_t *stream, uint32_...
  function pb_decode_varint (line 207) | bool checkreturn pb_decode_varint(pb_istream_t *stream, uint64_t *dest)
  function pb_skip_varint (line 229) | bool checkreturn pb_skip_varint(pb_istream_t *stream)
  function pb_skip_string (line 240) | bool checkreturn pb_skip_string(pb_istream_t *stream)
  function pb_decode_tag (line 249) | bool checkreturn pb_decode_tag(pb_istream_t *stream, pb_wire_type_t *wir...
  function pb_skip_field (line 275) | bool checkreturn pb_skip_field(pb_istream_t *stream, pb_wire_type_t wire...
  function read_raw_value (line 290) | static bool checkreturn read_raw_value(pb_istream_t *stream, pb_wire_typ...
  function pb_make_string_substream (line 320) | bool checkreturn pb_make_string_substream(pb_istream_t *stream, pb_istre...
  function pb_close_string_substream (line 335) | void pb_close_string_substream(pb_istream_t *stream, pb_istream_t *subst...
  function decode_static_field (line 348) | static bool checkreturn decode_static_field(pb_istream_t *stream, pb_wir...
  function allocate_field (line 426) | static bool checkreturn allocate_field(pb_istream_t *stream, void *pData...
  function initialize_pointer_field (line 462) | static void initialize_pointer_field(void *pItem, pb_field_iter_t *iter)
  function decode_pointer_field (line 476) | static bool checkreturn decode_pointer_field(pb_istream_t *stream, pb_wi...
  function decode_callback_field (line 598) | static bool checkreturn decode_callback_field(pb_istream_t *stream, pb_w...
  function decode_field (line 645) | static bool checkreturn decode_field(pb_istream_t *stream, pb_wire_type_...
  function iter_from_extension (line 673) | static void iter_from_extension(pb_field_iter_t *iter, pb_extension_t *e...
  function default_extension_decoder (line 694) | static bool checkreturn default_extension_decoder(pb_istream_t *stream,
  function decode_extension (line 710) | static bool checkreturn decode_extension(pb_istream_t *stream,
  function find_extension_field (line 736) | static bool checkreturn find_extension_field(pb_field_iter_t *iter)
  function pb_field_set_to_default (line 750) | static void pb_field_set_to_default(pb_field_iter_t *iter)
  function pb_message_set_to_defaults (line 822) | static void pb_message_set_to_defaults(const pb_field_t fields[], void *...
  function pb_decode_noinit (line 839) | bool checkreturn pb_decode_noinit(pb_istream_t *stream, const pb_field_t...
  function pb_decode (line 942) | bool checkreturn pb_decode(pb_istream_t *stream, const pb_field_t fields...
  function pb_decode_delimited (line 956) | bool pb_decode_delimited(pb_istream_t *stream, const pb_field_t fields[]...
  function pb_release_union_field (line 972) | static bool pb_release_union_field(pb_istream_t *stream, pb_field_iter_t...
  function pb_release_single_field (line 998) | static void pb_release_single_field(const pb_field_iter_t *iter)
  function pb_release (line 1084) | void pb_release(const pb_field_t fields[], void *dest_struct)
  function pb_decode_svarint (line 1103) | bool pb_decode_svarint(pb_istream_t *stream, int64_t *dest)
  function pb_decode_fixed32 (line 1117) | bool pb_decode_fixed32(pb_istream_t *stream, void *dest)
  function pb_decode_fixed64 (line 1131) | bool pb_decode_fixed64(pb_istream_t *stream, void *dest)
  function pb_dec_varint (line 1150) | static bool checkreturn pb_dec_varint(pb_istream_t *stream, const pb_fie...
  function pb_dec_uvarint (line 1187) | static bool checkreturn pb_dec_uvarint(pb_istream_t *stream, const pb_fi...
  function pb_dec_svarint (line 1211) | static bool checkreturn pb_dec_svarint(pb_istream_t *stream, const pb_fi...
  function pb_dec_fixed32 (line 1235) | static bool checkreturn pb_dec_fixed32(pb_istream_t *stream, const pb_fi...
  function pb_dec_fixed64 (line 1241) | static bool checkreturn pb_dec_fixed64(pb_istream_t *stream, const pb_fi...
  function pb_dec_bytes (line 1247) | static bool checkreturn pb_dec_bytes(pb_istream_t *stream, const pb_fiel...
  function pb_dec_string (line 1284) | static bool checkreturn pb_dec_string(pb_istream_t *stream, const pb_fie...
  function pb_dec_submessage (line 1319) | static bool checkreturn pb_dec_submessage(pb_istream_t *stream, const pb...

FILE: src/pb_decode.h
  type pb_istream_s (line 28) | struct pb_istream_s

FILE: src/pb_encode.c
  function buf_write (line 59) | static bool checkreturn buf_write(pb_ostream_t *stream, const pb_byte_t ...
  function pb_ostream_t (line 70) | pb_ostream_t pb_ostream_from_buffer(pb_byte_t *buf, size_t bufsize)
  function pb_write (line 87) | bool checkreturn pb_write(pb_ostream_t *stream, const pb_byte_t *buf, si...
  function encode_array (line 112) | static bool checkreturn encode_array(pb_ostream_t *stream, const pb_fiel...
  function encode_basic_field (line 201) | static bool checkreturn encode_basic_field(pb_ostream_t *stream,
  function encode_callback_field (line 273) | static bool checkreturn encode_callback_field(pb_ostream_t *stream,
  function encode_field (line 293) | static bool checkreturn encode_field(pb_ostream_t *stream,
  function default_extension_encoder (line 312) | static bool checkreturn default_extension_encoder(pb_ostream_t *stream,
  function encode_extension_field (line 332) | static bool checkreturn encode_extension_field(pb_ostream_t *stream,
  function pb_encode (line 371) | bool checkreturn pb_encode(pb_ostream_t *stream, const pb_field_t fields...
  function pb_encode_delimited (line 395) | bool pb_encode_delimited(pb_ostream_t *stream, const pb_field_t fields[]...
  function pb_get_encoded_size (line 400) | bool pb_get_encoded_size(size_t *size, const pb_field_t fields[], const ...
  function pb_encode_varint (line 414) | bool checkreturn pb_encode_varint(pb_ostream_t *stream, uint64_t value)
  function pb_encode_svarint (line 436) | bool checkreturn pb_encode_svarint(pb_ostream_t *stream, int64_t value)
  function pb_encode_fixed32 (line 447) | bool checkreturn pb_encode_fixed32(pb_ostream_t *stream, const void *value)
  function pb_encode_fixed64 (line 458) | bool checkreturn pb_encode_fixed64(pb_ostream_t *stream, const void *value)
  function pb_encode_tag (line 473) | bool checkreturn pb_encode_tag(pb_ostream_t *stream, pb_wire_type_t wire...
  function pb_encode_tag_for_field (line 479) | bool checkreturn pb_encode_tag_for_field(pb_ostream_t *stream, const pb_...
  function pb_encode_string (line 511) | bool checkreturn pb_encode_string(pb_ostream_t *stream, const pb_byte_t ...
  function pb_encode_submessage (line 519) | bool checkreturn pb_encode_submessage(pb_ostream_t *stream, const pb_fie...
  function pb_enc_varint (line 571) | static bool checkreturn pb_enc_varint(pb_ostream_t *stream, const pb_fie...
  function pb_enc_uvarint (line 589) | static bool checkreturn pb_enc_uvarint(pb_ostream_t *stream, const pb_fi...
  function pb_enc_svarint (line 607) | static bool checkreturn pb_enc_svarint(pb_ostream_t *stream, const pb_fi...
  function pb_enc_fixed64 (line 625) | static bool checkreturn pb_enc_fixed64(pb_ostream_t *stream, const pb_fi...
  function pb_enc_fixed32 (line 631) | static bool checkreturn pb_enc_fixed32(pb_ostream_t *stream, const pb_fi...
  function pb_enc_bytes (line 637) | static bool checkreturn pb_enc_bytes(pb_ostream_t *stream, const pb_fiel...
  function pb_enc_string (line 656) | static bool checkreturn pb_enc_string(pb_ostream_t *stream, const pb_fie...
  function pb_enc_submessage (line 682) | static bool checkreturn pb_enc_submessage(pb_ostream_t *stream, const pb...

FILE: src/pb_encode.h
  type pb_ostream_s (line 27) | struct pb_ostream_s
Condensed preview — 55 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (231K chars).
[
  {
    "path": ".editorconfig",
    "chars": 101,
    "preview": "# editorconfig.org\nroot = true\n\n[*]\nindent_style = space\nindent_size = 2\ninsert_final_newline = true\n"
  },
  {
    "path": ".gitignore",
    "chars": 18,
    "preview": ".DS_Store\n.vscode\n"
  },
  {
    "path": ".travis.yml",
    "chars": 1978,
    "preview": "language: c\nenv:\n  - ARDUINO_VERSION=1.6.13\nbefore_install:\n  - \"/sbin/start-stop-daemon --start --quiet --pidfile /tmp/"
  },
  {
    "path": "AUTHORS",
    "chars": 149,
    "preview": "Johan Stokking <johan@thethingsnetwork.org>\nFokke Zandbergen <mail@fokkezb.nl>\nAlessandro Blason <mrblason@gmail.com>\nJP"
  },
  {
    "path": "CONTRIBUTING.md",
    "chars": 311,
    "preview": "## Contributing\n\nWe'd ❤️ to welcome your contribution. Please make sure your changes include:\n\n1.  Examples: [examples]("
  },
  {
    "path": "LICENSE",
    "chars": 1085,
    "preview": "The MIT License (MIT)\n\nCopyright (c) 2016 The Things Network\n\nPermission is hereby granted, free of charge, to any perso"
  },
  {
    "path": "Makefile",
    "chars": 133,
    "preview": "PROTOC = $(NANOPB)/generator-bin/protoc --proto_path=src/api --nanopb_out=\"-v:src\"\n\n.PHONY: proto\n\nproto:\n\t$(PROTOC) src"
  },
  {
    "path": "README.md",
    "chars": 1518,
    "preview": "# The Things Network Arduino Library\n[![Build Status](https://travis-ci.org/TheThingsNetwork/arduino-device-lib.svg?bran"
  },
  {
    "path": "docs/CayenneLPP.md",
    "chars": 2335,
    "preview": "# API Reference\n\nThe `CayenneLPP` class enables Arduino devices to encode data with the Cayenne Low Power Payload (LPP)."
  },
  {
    "path": "docs/TheThingsMessage.md",
    "chars": 1847,
    "preview": "# API Reference\n\n## Class: `TheThingsMessage`\nThe `TheThingsMessage` class provides structs for sensor and application d"
  },
  {
    "path": "docs/TheThingsNetwork.md",
    "chars": 20643,
    "preview": "# API Reference\n\nThe `TheThingsNetwork` class enables Arduino devices with supported LoRaWAN modules to communicate via "
  },
  {
    "path": "examples/CayenneLPP/CayenneLPP.ino",
    "chars": 951,
    "preview": "#include <TheThingsNetwork.h>\n#include <CayenneLPP.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000"
  },
  {
    "path": "examples/CheckModule/CheckModule.ino",
    "chars": 2039,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your DevAddr, NwkSKey, AppSKey and the frequency plan\nconst char *devAddr = \"00000"
  },
  {
    "path": "examples/DeviceInfo/DeviceInfo.ino",
    "chars": 614,
    "preview": "#include <TheThingsNetwork.h>\n\n#define loraSerial Serial1\n#define debugSerial Serial\n\n// Replace REPLACE_ME with TTN_FP_"
  },
  {
    "path": "examples/PassThrough/PassThrough.ino",
    "chars": 604,
    "preview": "/**\n * Use this sketch to talk directly to the LoRa module.\n * \n * In Serial Monitor, select \"Both NL & CR\" and \"115200 "
  },
  {
    "path": "examples/QuickStart/Converter.js",
    "chars": 270,
    "preview": "function Converter(decoded, port) {\n  // Merge, split or otherwise\n  // mutate decoded fields.\n  var converted = decoded"
  },
  {
    "path": "examples/QuickStart/Decoder.js",
    "chars": 224,
    "preview": "function Decoder(bytes, port) {\n  // Decode an uplink message from a buffer\n  // (array) of bytes to an object of fields"
  },
  {
    "path": "examples/QuickStart/Encoder.js",
    "chars": 220,
    "preview": "function Encoder(object, port) {\n  // Encode downlink messages sent as\n  // object to an array or buffer of bytes.\n  var"
  },
  {
    "path": "examples/QuickStart/QuickStart.ino",
    "chars": 1375,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey"
  },
  {
    "path": "examples/QuickStart/Validator.js",
    "chars": 236,
    "preview": "function Validator(converted, port) {\n  // Return false if the decoded, converted\n  // message is invalid and should be "
  },
  {
    "path": "examples/Receive/Receive.ino",
    "chars": 1159,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey"
  },
  {
    "path": "examples/ReceiveClassC/ReceiveClassC.ino",
    "chars": 1357,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey"
  },
  {
    "path": "examples/SendABP/SendABP.ino",
    "chars": 1015,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your DevAddr, NwkSKey, AppSKey and the frequency plan\nconst char *devAddr = \"00000"
  },
  {
    "path": "examples/SendOTAA/SendOTAA.ino",
    "chars": 907,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey"
  },
  {
    "path": "examples/Sensors/DHT/DHT.ino",
    "chars": 1598,
    "preview": "#include <TheThingsNetwork.h>\n\n// First install \"DHT sensor library\" via the Library Manager\n#include <DHT.h>\n\n// Set yo"
  },
  {
    "path": "examples/Sensors/LightSensor/LightSensor.ino",
    "chars": 1139,
    "preview": "#include <TheThingsNetwork.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000000000000\";\nconst char *appKey"
  },
  {
    "path": "examples/TheThingsMessage/Receive/Receive.ino",
    "chars": 1413,
    "preview": "#include <TheThingsNetwork.h>\n#include <TheThingsMessage.h>\n\n// Set your AppEUI and  AppKey\nconst char *appEui = \"000000"
  },
  {
    "path": "examples/TheThingsMessage/Send/Send.ino",
    "chars": 1349,
    "preview": "#include <TheThingsNetwork.h>\n#include <TheThingsMessage.h>\n\n// Set your AppEUI and AppKey\nconst char *appEui = \"0000000"
  },
  {
    "path": "examples/Workshop/Workshop.ino",
    "chars": 1657,
    "preview": "#include <TheThingsNetwork.h>\n\n// Before your start, make sure that in the Tools menu, your Board and your\n// Port is se"
  },
  {
    "path": "keywords.txt",
    "chars": 2060,
    "preview": "#######################################\n# Syntax Coloring Map\n#######################################\n\n#################"
  },
  {
    "path": "library.properties",
    "chars": 354,
    "preview": "name=TheThingsNetwork\nversion=2.7.2\nauthor=The Things Network\nmaintainer=Johan Stokking <johan@thethingsnetwork.org>\nsen"
  },
  {
    "path": "src/CayenneLPP.cpp",
    "chars": 4926,
    "preview": "// Adapted from https://developer.mbed.org/teams/myDevicesIoT/code/Cayenne-LPP/\n\n// Copyright © 2017 The Things Network\n"
  },
  {
    "path": "src/CayenneLPP.h",
    "chars": 2934,
    "preview": "// Adapted from https://developer.mbed.org/teams/myDevicesIoT/code/Cayenne-LPP/\n\n// Copyright © 2017 The Things Network\n"
  },
  {
    "path": "src/TheThingsMessage.cpp",
    "chars": 868,
    "preview": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in th"
  },
  {
    "path": "src/TheThingsMessage.h",
    "chars": 627,
    "preview": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in th"
  },
  {
    "path": "src/TheThingsNetwork.cpp",
    "chars": 42803,
    "preview": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in th"
  },
  {
    "path": "src/TheThingsNetwork.h",
    "chars": 5876,
    "preview": "// Copyright © 2017 The Things Network\n// Use of this source code is governed by the MIT license that can be found in th"
  },
  {
    "path": "src/api/appData.proto",
    "chars": 123,
    "preview": "syntax = \"proto2\";\n\npackage api;\n\nmessage AppData {\n        optional bool light = 1;\n        optional bool activate = 2;"
  },
  {
    "path": "src/api/deviceData.proto",
    "chars": 642,
    "preview": "syntax = \"proto2\";\n\npackage api;\n\nmessage Location {\n        optional float longitude = 1;\n        optional float latitu"
  },
  {
    "path": "src/appData.pb.c",
    "chars": 581,
    "preview": "/* Automatically generated nanopb constant definitions */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n"
  },
  {
    "path": "src/appData.pb.h",
    "chars": 1377,
    "preview": "/* Automatically generated nanopb header */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n#ifndef PB_API"
  },
  {
    "path": "src/deviceData.pb.c",
    "chars": 2997,
    "preview": "/* Automatically generated nanopb constant definitions */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n"
  },
  {
    "path": "src/deviceData.pb.h",
    "chars": 3204,
    "preview": "/* Automatically generated nanopb header */\n/* Generated by nanopb-0.3.7 at Fri Dec 16 16:49:49 2016. */\n\n#ifndef PB_API"
  },
  {
    "path": "src/pb.h",
    "chars": 21230,
    "preview": "/* Common parts of the nanopb library. Most of these are quite low-level\n * stuff. For the high-level interface, see pb_"
  },
  {
    "path": "src/pb_common.c",
    "chars": 3014,
    "preview": "/* pb_common.c: Common support functions for pb_encode.c and pb_decode.c.\n *\n * 2014 Petteri Aimonen <jpa@kapsi.fi>\n */\n"
  },
  {
    "path": "src/pb_common.h",
    "chars": 1421,
    "preview": "/* pb_common.h: Common support functions for pb_encode.c and pb_decode.c.\n * These functions are rarely needed by applic"
  },
  {
    "path": "src/pb_decode.c",
    "chars": 42205,
    "preview": "/* pb_decode.c -- decode a protobuf using minimal resources\n *\n * 2011 Petteri Aimonen <jpa@kapsi.fi>\n */\n\n/* Use the GC"
  },
  {
    "path": "src/pb_decode.h",
    "chars": 5496,
    "preview": "/* pb_decode.h: Functions to decode protocol buffers. Depends on pb_decode.c.\n * The main function is pb_decode. You als"
  },
  {
    "path": "src/pb_encode.c",
    "chars": 20951,
    "preview": "/* pb_encode.c -- encode a protobuf using minimal resources\n *\n * 2011 Petteri Aimonen <jpa@kapsi.fi>\n */\n\n#include \"pb."
  },
  {
    "path": "src/pb_encode.h",
    "chars": 5727,
    "preview": "/* pb_encode.h: Functions to encode protocol buffers. Depends on pb_encode.c.\n * The main function is pb_encode. You als"
  },
  {
    "path": "test/TheThingsMessage/TheThingsMessage.ino",
    "chars": 503,
    "preview": "#include <TheThingsMessage.h>\n\ndevicedata_t data = api_DeviceData_init_default;\n\nvoid setup() {\n  data.has_motion = true"
  },
  {
    "path": "test/TheThingsNetwork/TheThingsNetwork.ino",
    "chars": 1226,
    "preview": "#include <TheThingsNetwork.h>\n\nconst char *appEui = \"0000000000000000\";\nconst char *appKey = \"00000000000000000000000000"
  },
  {
    "path": "test/verify",
    "chars": 168,
    "preview": "#!/bin/bash\nBOARD=$1\nINO=$2\nSTD=`arduino --verify --board ${BOARD} ${INO} 2>&1`\nEXIT=$?\necho \"${STD}\"\nif [[ $EXIT != 0 |"
  }
]

// ... and 2 more files (download for full content)

About this extraction

This page contains the full source code of the TheThingsNetwork/arduino-device-lib GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 55 files (214.4 KB), approximately 60.4k tokens, and a symbol index with 126 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.

Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.

Copied to clipboard!