# Lecture notes, recorded lectures ## TTN UBIDOTS lecture - Show code - Structure - LoRa connect. - key - sensor - Online cloud, for building dashboard - UBIDOT, STEM - TTN Integrations - Build dashboard - Event triggers - Share ## Practical, basic setup The Things Network - Background - LoRa. Long Range, WAN, low data rate, small battery consumption. - The Things Network? ## Setting up your Pycom device - Legacy FW, the choice for this guide. - Pybytes is an option - provision is easier and handled within the Pybytes platform. ## Creating your application in TTN - TTN Console. Create application. - Add device. OTAA: Over the air activation (Recommended) ABP: Activation by personalization. - LoRa MAC, unique identfier. Device specific. - Codes needed: - DevEUI (Extended Unique Identifier) - Application EUI - App Key ## Setting up your code Example from: https://github.com/iot-lnu/applied-iot-20 Getting started docs Pycom. https://docs.pycom.io/tutorials/lora/lorawan-otaa/ # Decoding functions TTN Data formats for sensors. Recommend using the ```struct``` library. https://docs.python.org/3/library/struct.html Useful functions in Python for understanding bytes, bin, hex. ```python bin() hex() ``` The data that your application recives in TTN needs to be decrypted. All is sent in bytes, hexadecimal. You should always avoid plain text as it uses too much data, which means time and battery. Use the hex() function in Python if you want to get your head around the hexadecimal system, base of 16. 1 byte = 8 bits = 2^8 = 255 2 bytes = 16 bits = 2^16 = 65 536 Always note which resolution you need for your sensor data. A temperature sensor that measures a value range between 0-60 degrees Celsius, if using only a single byte the resolution is 60/255 = 0.23 C, which is likely enough for most applications. This value needs to be encoded/decoded in both ends to represent the range, if not the resolution will be 1 deg C within the range 0-255. We want to use as little data as possible. So depending on your application need, device the function accordingly. Do you need negative values, in that case use a signed format. Otherwise, unsigned. https://docs.python.org/3/library/struct.html TTN example of writing Payload function https://www.youtube.com/watch?v=nT2FnwCoP7w Plain text. ```javascript= function Decoder(bytes, port) { // Decode plain text; for testing only return { myTestValue: String.fromCharCode.apply(null, bytes) }; } ``` Creating a callback event for downlink. Note, it's only recieved when sending data. ```python= def lora_cb(lora): events = lora.events() if events & LoRa.RX_PACKET_EVENT: print('Lora packet received') if events & LoRa.TX_PACKET_EVENT: print('Lora packet sent') lora.callback(trigger=(LoRa.RX_PACKET_EVENT | LoRa.TX_PACKET_EVENT), handler=lora_cb) ```