Category Archives: Project

Getting the Heltec Wireless Lite V3 with SX1262 LoRa Radio Chip to work with LoRaWAN

This article is part 1.5 of the series – Developing a component for ESPHome, for the SX1262 LoRa Radio Chip. The process getting the LoRaWAN functionality of this development board to work with The Things Network proved to be an excercise infrustration management, so the following is a write up of what was required to get it to work. The following is my account of setting up the Heltec Wireless Lite V3 for
connecting to the LoRaWAN network. There were several false starts, but in
the end it was possible to send data and decode it correctly.

Development Environment

ArduinoIDE and the Heltec Board Manager extention

The Heltec boards are defined by the following file (link) which is added through the menu in Preferences…->Additional boards manager URLs

https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series/releases/download/0.0.7/package_heltec_esp32_index.json

This file specifies that esptool 3.3.0 is used for writing the firmware to the Heltec board. There is as issue with usung this version for the Heltec V3 boards, in that the firmware compiles and installs, but puts the ESP32-S3 processor into a boot loop.

The details of this issue is here: https://github.com/Heltec-Aaron-Lee/WiFi_Kit_series/issues/159#issuecomment-1842269504

The fix is to upgrade esptool 4.6.1. The following fix works on Ubuntu, but
it’s a hack. The correct fix would be to change the JSON definition file.

cd ~/.arduino15/packages/Heltec-esp32/tools/esptool_py
mv 3.3.0 3.3.0-bak
wget https://github.com/espressif/esptool/archive/refs/tags/v4.6.1.zip
unzip v4.6.1.zip
rm v4.6.1.zip
mv esptool-4.6.1 3.3.0

LoRaWAN Library

Install the ‘SX126X-Arduino’ library with the library manager (currently version
2.4.0).

A small fix is required. Edit the ‘src/mac/Commissioning.h’ file and comment out the check for whether the LoRaWAN Region has already being set (Line 40).

Example Code – LoRaWAN.ino

From the LoRaWAN library, the LoRaWAN example was copied and modified to get the
system to work.

Modifications:

  • Copy the LoRaWAN.ino file, and remove other unnecessary files. Fix the source to remove the dependancies.
  • Simplify the code. eg. Remove the code sections used for other processors.
  • Set the authentication mode to OTAA, the device type and the Frequency bandplan region to AU915 by adding the optional parameters to ‘lmh_init() – true, CLASS_A and LORAMAC_REGION_AU915.
  • Ensure that the correct LoRaWAN sub-band is being used for AU915 by calling ‘lmh_setSubBandChannels(2)’.
  • Additional Serial.println() output added to trace the execution of the firmware, including the output of the LoRaWAN parameters.

The LoRaWAN parameters (AppEUI, DevEUI and AppKey) are set in the following section.

The Things Network

The Heltec V3 Devices have not been configured as known devices in The Things
Network
, and need to be specifically setup.

Select “Enter end device specifics manually”.

Add a new device and set the following Device Parameters

  • Frequency Plan: Australia 915-928 MHz, FSB 2 (used by TTN)
  • LoRaWAN Version: LoRaWAN Specification 1.0.2
  • Regional Parameters version: RP001 Regional Parameters 1.0.2 revision B

Create a JoinEUI (previously known as the AppEUI). This can be freely set any 8-byte value, but cannot be changed once set.

The other parameters that need to be set are:

  • DevEUI
  • AppKey

The easiest way to to get these values is to allow them to be automatically generated by The Things Network interface. They can be specifically set if the manufacturer of a device has preprogrammed a device with a LoRaWAN configuration.

Build and Install Firmware on Device

Update the definitions of the LoRaWAN parameters in the code to reflect the values just generated. It is possible to directly produce the desired strings (in ‘msb’ format) from The Things Network device interface.

Paste these into the code

uint8_t nodeDeviceEUI[8] = {…};
uint8_t nodeAppEUI[8] = {…};
uint8_t nodeAppKey[16] = {…};

Ensure that these parameters are being set in the ‘setup()’ function with the following:

lmh_setDevEui(nodeDeviceEUI);
lmh_setAppEui(nodeAppEUI);
lmh_setAppKey(nodeAppKey);

It is also helpful to also have these values displayed when the board os booted.

The firmware compiles and can be installed onto the Heltec board. On boot, it should
connect to the LoRaWAN network and start transmitting packets of data.

On The Things Network, to check that the uploaded data is correct, the following JavaScript payload filter can be installed for the device, which will decode the data and
(hopefully) display the correct string.

function decodeUplink(input) {
var result;
result = String.fromCharCode.apply(null, input.bytes);
return {
  data: {
    bytes: input.bytes,
    result: result
  },
  warnings: [],
  errors: []
};
}

Notes, Issues and Errors

  • When selecting and playing around with different LoRaWAN Versions and Regonal Parameters, it appears as though The Things Network does not reset LoRaWAN values properly. Changing the LoRaWAN version to 1.1.0 required the additional parameter ‘NwsKey’. If the LoRaWAN version is then set back to 1.0.2, this value becomes the one that is used for the AppKey. There is a note about this in The Things Network interface, but it is not obvious what is required.
  • Care needs to be taken when setting the nodeDevEUI and nodeAppEUI not to set them the wrong way around. If connection packets are being received from the device, but it isn’t able to authenticate, then the nodeDevEUI will be correct, but the other parameters (including LoRaWAN Version) may be wrong.
  • If only intermittent transmitted packets are seen in The Things Network, and the device is not able to authenticate, check that the firmware has selected and is using the correct LoRaWAN sub-band.
  • Selecting other LoRaWAN versions eg. 1.1.0 will require additional parameters to be set., namely NwsKey. This setting is not removed if the LoRaWAN version is set back to 1.0.2, and this value is then used instead of the nodeAppKey. This is a trap. The only way to fix this is to delete the device definition in The Things Network and start over.

Next Steps

  • Convert the Arduino LoRaWAN firmware to ESPHome. This will allow LoRaWAN to be able to be used with the other ESPHome functions, including support for all of the existing supported sensors and outputs, and also operate with Home Assistant. (This will be Part 2 of the “Developing a component for ESPHome, for the SX1262 LoRa Radio Chip” series.)
  • Test with the Helium network. Register the device on the Helium network and check that data is routed correctly.
  • Implement as Class B and Class C LoRaWAN device. The example code currently only
    uploads data. Class B and Class C deviced allow data to be downloaded as well, for device control.

Installing ESPHome – A Quick Start Guide

These instructions are summarised from the online instructions. See: https://esphome.io/guides/installing_esphome.html

Quickstart

Installation

The following installs ESPhome on a Windows computer so that it can be run from the ‘cmd’ window (text input).

Install Python (and Pip)
See instructions here: https://www.python.org/downloads/

Ensure that option “Add Python to PATH” is selected before installing the package.

Check that Python is installed

In a Windows ‘cmd’ window (command prompt).

python --version
=> Should return something like: Python 3.10.1

Install dependencies

pip3 install wheel

Install ESPHome

pip install esphome

Check installation

esphome version
=> Should return something like: Version: 2023.12.0

ESPHome is now installed, and can be run from the Windows CMD

Using ESPHome

Create/Edit YAML files

ESPHome is driven via YAML configuration files in the working directory. YAML (Yet Another Markup Language) files are text files which are formatted in a specific way. They can be edited with any tool which can edit text files. (MS Notepad is good, MS Word may cause problems. MS Visual Studio (Code) is a good place to start.)

Once installed, view available ESPhome options

esphome -h

A simple YAML file that works with the Heltec Wifi LoRa 32 V3, which can be extended, looks like the following. (Copy and save this file as ‘esphome-device.yaml’) To understand the parts of this fle and the YAML configuration options, see: https://esphome.io/

esphome:
  name: "lora-sx126x"

esp32:
  board: esp32-s3-devkitc-1
  framework:
    type: arduino

logger:

wifi:
  networks:
  - ssid: WIFI_SSID_GOES_HERE
    password: WIFI_PASSWORD_GOES_HERE
 
ota:
  password: OTA_PASSWORD_GOES_HERE

# Enable Home Assistant API
api:
  encryption:
    key: API_KEY_GOES_HERE

web_server:
  port: 80

With an ESP32 board, new firmware can be built and installed using a YAML configuration file with:

esphome run esphome-device.yaml

These commands can be run individually as the following.

esphome compile configuration-file.yaml
esphome upload configuration-file.yaml
esphome logs configuration-file.yaml

When the program is running, it can be interupted by pressing the key combination: Ctrl-C

Over the Air (OTA) Updates

If enabled in the YAML file, ESPHome also supports “Over the Air” updates. This means that if the ESP board is currently connected to a Wifi network then using this connection, it can be directly upgraded with new firmware.

This option can be selected during the ‘upload’ step. If the board is not connected with USB and only connected to Wifi, this will happen automatically.

Additional notes – For Linux Users

Using a Virtual Environment – venv

The above process is very similar when installing on Linux or MacOS. On Linux, it is possible to setup a ‘virtual environment’ (venv) for development by installing and using the ‘venv’ command. This will allow the local Python libraries to be installed and run separately to the system libraries. This is useful to allow the development environment to use more recent library versions and/or allow the development environment to use more stable version. This helps when debugging and tracking down issues that may be caused by libraries.

Ensire that you are working in the required local project directory (eg. with the ‘cd’ command)

With Python and Pip installed as installed, create the venv development environment in the current working directory.

pip3 install venv
python -m venv venv
. venv/bin/activate

Install and run ESPHome as before.

To restart editing session in an existing venv enabled directory

Setup the venv environment again by using:

. venv/bin/activate

At this stage, it is also possible to install ESPHome directly from the GitHub
development repository. This is useful for debugging, bug fixing and testing.

Install development version from the Github ESPHome repository

This requires that the ‘git’ lool has been installed. (Use ‘apt git install’ on Ubuntu.)

git clone https://github.com/esphome/esphome.git
cd esphome
python -m venv venv
. venv/bin/activate
./scripts/setup

As required, update the local copy of the code with the following.

git pull
./scripts/setup

Developing a component for ESPHome, for the SX1262 LoRa Radio Chip – Part 1

Introduction

This post describes “Work in Progress”. I have deliberately decided to put these details together now as it has been possible to build something that ‘sort of’ works, in that all the pieces are there, ot nearly there. The end is in sight, albeit a reasonably long way away in time and effort.

The original aim was to make the SX1282 LoRa radio chip available, for both LoRa and LoRaWAN modes, directly in ESPHome. It is hoped that the use of the SX126X series of radio chips can be as easy as possible to use and in most cases wholly driven from the ESPHome YAML files. When creating an IoT device with a new dev board, this has been one of the frustrating pieces of the excercise, particularly when using the Arduino IDE and programmer.

The Github repository of the component is here: https://github.com/PaulSchulz/esphome-lora-sx126x

These notes assume that you have ESPHome installed (

To include this external component in your own ESPHome yaml file, see below, or read the repository’s documentation (which will be newer than this).

Hardware

This ESPHome component is being developed on the Heltec V3 Development Boards which use the LoRa SX1262 chip. These dev boards are:

At the present time, these boards are not available for selecting directly in the
ESPHome YAML file (when using the Arduino framework). In order to make these
boards work with the available version of ESPHome, the following YAML is required:

esp32:
  board: esp32-s3-devkitc-1
  framework:
    type: arduino

These board definitions are imported from the platform-espessif32 project here.

The LoRa Arduino Library

The Arduino library being used is beegee-tokyo/SX126X-Arduino, which itself is based on several other libraries. It appear to currently be the best and most maintained LoRa library available for these radio chips.

The following header file contains the descriptions of the functions and fields used by the library: https://github.com/beegee-tokyo/SX126x-Arduino/blob/master/src/radio/radio.h

Testing and Usage

The files lora-sx126x.yaml and secret.yaml provide an example of how to use the
component. To use with a working version of ESPHome, edit secret.yaml to add
your local Wifi details, then run:

esphome run lora-sx126x.yaml

Development Comments

To get the component into a working state, this ESPHome component currently does some things which are not encouraged by the ESPHome Core and Component developers (see below).

It is always hoped that this component will become compliant enough to be
included in ESPHome, but in the meantime, it can be included in your ESPHome
build by either cloning this repository locally and adding an external_component
with a local source; or by including the github repository directly as an
external_component. See the External Components documentation for more details

If downloading and using as a local source for external component:

external_components:
- source:
    type: local
    path: esphome/components
  components: ["lora_sx126x"]

and, using directly from the Github source for an external component

external_components:
- source:
    type: git
    url: https://github.com/PaulSchulz/esphome-lora-sc126x
    ref: main
  components: ["lora_sx126x"]

Considerations / Things to fix

Direct use of SPI and SX126x-Arduino libraries

If possible, the SX126x-Arduino library needs to be implemented natively in
ESPHome, to make use of the native ESPHome SPI code.

By using the Library directly, it is uncertain at the moment whether this component can be used generally with other devices that use the same SPI interface.

Example YAML

The following is the proposed example YAML configuration, for a ESPHome image that will enable the SX126X radio.

esphome:
  name: "lora-sx126x"
  libraries:
    - "SPI"
    - "Ticker"
    - "SX126x-Arduino"

...

external_components:
  - source:
      type: local
      path: esphome/components

...

lora_sx126x:
  # The frequency to use needs to be specified as will depend on the
  # hardware and the region in which the it is being used.
  frequency: 915000000

Development

Proposed YAML Options

The following is an example of the proposed full option list, for using the LoRa radio chip.

lora_sx126x:
  # optional, with sensile defaults, if possible from board id.
  pin_lora_reset: 12
  pin_lora_dio_1: 14
  pin_lora_busy: 13
  pin_lora_nss: 8
  pin_lora_sclk: 9
  pin_lora_miso: 11
  pin_lora_mosi: 10
  radio_txen: -1
  radio_rxen: -1
  use_dio2_ant_switch: true
  use_dio3_tcx0: true
  use_dxo3_ant_switch: false

  # required - depends on region and frequency band being used
  rf_frequency:           915000000
  # optional (sensible defaults)
  tx_output_power:               22
  lora_bandwidth:                 0
  lora_spreading_factor:          7
  lora_codingrate:                1
  lora_preamble_length:           8
  lora_symbol_timeout:            0
  lora_fix_length_layload_on: false
  lora_iq_inversion_on:       false
  rx_timeout_value:            3000
  tx_timeout_value:            3000

It should then be possible to use the radio with the various builtin types. This has yet to be implemented.

text_sensor:
  - platform: lora_sx126x
    id: lora_message
    name: LoRa Message

# Is there a component for this in ESPHome?
# Sending a string to a component?
text_message:
  - platform: lora_sx126x
    id: send_message
    name: "Send LoRa Message"

binary_sensor:
  - platform: lora_sx126x
    id: lora_sensor
    name: LoRa Sensor
    on_string: "@+++"
    off_string: "@---"

switch:
  - platform: lora_sx126x
    id: lora_switch
    name: LoRa Switch
    on_string: "@^^^"
    off_string: "@vvv"

binary_input:
 - platform: lora_sx126x
   id: lora_input
   name: LoRa Binary Input
   on_string: "@***"
   off_string: "@..."
  
binary_output:
 - platform: lora_sx126x
   id: lora_output
   name: LoRa Binary Ouput
   on_string: "@>>>"
   off_string: "@<<<"

Installing and Running Overleaf (for creating LaTeX Documents)

TL;DR

Instructions on how to install a full LaTeX installation in Overleaf, so that all of the available LaTeX packages can be used.

Introduction

I am using Overleaf to creare LaTex Documents. It is a web based interface which has a text editior and document preview window. It also allows multiple users to colabourate on the same document.

This is my attempt at documentaing my steps in getting Overleaf Community Edition installed on my local laptop so that I can create LaTeX documents. I have used Gummi in the past for writing LaTeX which I liked, but a lot of the LaTeX documentation that a Google search returns is for Overleaf, specifically the Overleaf Pro and Internet based version.

Background

While Internet hosted software applications can be good, they rely on having an internet connection, and that I am happy to share what I am doing with another, very unknown and anonymous system.

On a related note, some of this document has been written by ChatGPT. The irony of this is not lost on me.

This installation uses the most recently available version of the Overleaf Toolkit to install the current version of overleaf available in a docker image (sharelatex/sharelatex, version 4.0.1).

The previous installation processes used ‘docker-compose’ directly, and instructions here reflect that. They were useful in that they included details on how to add additional LaTeX packages. The current installation instructions (Quick Start Guide) are good, but they don’t incluse these details which are also need to subtly different.

As far as I can see, there is no Discord, Slack or even IRC channels for users of the Overleaf Community Edition, which made trying to get some help with figuring some of this stuff out. I was able to get some answers to my questions by searching Github issues, namely overleaf/toolkit/issues/85.

Prerequisites

This installation was done on a Ubuntu 23.04 laptop, which has docker-ce and docker-compose installed and configured so that the user is in the docker group and can run docker commands directly.

Note: It is also assumed that the user has suffient disk space to install and run the software. I start and checkout my git repositories into ~/Documents/git but you may be using another location.

Installation

The initial installation of Overleaf via the Overleaf Toolkit can be done via the folllowing commands (taken from the Quick Start document):

git clone https://github.com/overleaf/toolkit.git overleaf-toolkit
cd overleaf-toolkit
bin/init
bin/up

This last step will take some time to complete as it will download the Docker images and start up the Docker containers. After some time, it is possible to connect to Overleaf and set up the administrator account at http://localhost/launchpad. Setup an account (email address and password), and then login at http://localhost

It is now possible to create LaTeX documents, with the minimal number of available packages.

Adding additional LaTeX packages

With Overleaf running, it is possible to install additonal packages in the container by using the ‘tlmgr‘ command inside the container. For example, to install the gensymb package (so that the \ohm sysbol can be used), use:

docker exec sharelatex tlmgr install gensymb
docker exec sharelatex tlmgr path add

Alternatively, to install all of the available TeX Live packages, use the following. This will take a little bit of time and currently installs 4417 additional packages, providing that there is enough disk space. (With an original image size for sharelatex/sharelatex of 2.72GB, the new image ends up with a final size of 6.38GB.)

docker exec sharelatex tlmgr install scheme-full
docker exec sharelatex tlmgr path add

Once installed, these packages become avalable immediately for use in Overleaf. These installed packages will be ‘lost’ when the Docker container is restarted so the next step is to make these changes permanent.

Commit changes to ShareLaTeX container

To take a snapshot of the installed software, use:

docker commit sharelatex local/sharelatex-with-texlive-full:4.0.1

Instead of local/sharelatex-with-texlive-full, you can chose another image name. Due to the way Overleaf Toolbox works, the version (4.0.1) needs to match the config/version and needs to be in the form X.Y.Z-RC, where the ‘-RC’ is optional.

This command may take a while to run, but once complete, stop Overleaf (Ctl-C in the original window), and change the configuration to use the new image. Edit config/overleaf.rc and change SHARELATEX_IMAGE_NAME to the new image name.

SHARELATEX_IMAGE_NAME=local/sharelatex-with-texlive-full

Restart Overleaf in the background (daemon mode) with the following. This may take a little bit of time to start properly. (I was getting an Nginx Gateway error for a couple of minutes.)

bin/up -d

Conclusion

This documentation very briefly describes the steps required to install Overleaf Community Edition as a self hosted application with additional packages.

Any documents that are created are also stored persistantly on the local filesystem, under the overleaf-toolbox directlry. It is worth periodically downloading documents (as tar backup file) should the entire system need to be reinstalled from scratch.

Also, by default the installation uses port 80 for the web interface, and also supports an SSL configuration. It would be nice to be able to change this so that it won’t interfear with other installed web applications.

Setup and Configuration of a Commercial LoRaWAN Temperature Sensor

Introducton

This document is part of the PAE-IoT Parks and Gardens Project.

The aim of this post is to document the configuration details needed to setup a new temperature sensor which was deployed as part of the Port Adelaide-Enfield Library/Parks and Gardens collaboration, for monitoring the environment around a newly built sports ground and playing surface.

It is a fairly long document and aims to explicitly describe the code that is needed to set up the new data path. It is built on top of the existing data handling system (The Things Network, NodeRED, InfluxDB and Grafana) which has been described in previous posts, so it isn’t a complete explaination of this system.

Grafana graph from installed temperature sensors

More details about the project, including the live sensor data, can be found on the project pages:

The Hardware – Temperature Sensor

General information (from The Things Network)

Device Id:       eui-a840416eb183975f
Description:     LSN50V2-D23 LORAWAN WATERPROOF TEMPERATURE SENSOR (3 PROBES)
Frequency plan:  Australia 915-928 MHz, FSB 2 (used by TTN)
LoRaWAN version: LoRaWAN Specification 1.0.3
Regional Parameters version: RP001 Regional Parameters 1.0.3 revision A

Hardware

Brand:            dragino
Model:            lsn50v2-d20-d22-d23
Hardware version: unknown_hw_version
Firmware version: lsn50v2-d20-d22-d23 1.7.5

Note: The LoRaWAN Regional Parameters is set to “Version 1.0.3 Revision A”. This is different to what was found to work with custom developed sensors. It is unclear at this stage what the actual difference is.

The Things Network (TTN) Configuraton

The sensor was easily registered with The Things Network, as the hardware has been pre-configured with a hardware profile from The Things Network Device Repository. This configures the network parameters (as described in the previous section) as well as data formatting functions.

The current Formatter Code returns four data points (Temp_Black, Temp_Red, Temp White, and BatV) and two status values (Work_Mode and ALARM_status).

The code for this uplink data formatting function is as follows:

function decodeUplink(input) {
	var port = input.fPort;
	var bytes = input.bytes;
	var mode=(bytes[6] & 0x7C)>>2;
	var data = {};
	 switch (input.fPort) {
		 case 2:
if(mode=='3')
{
  data.Work_mode="DS18B20";
  data.BatV=(bytes[0]<<8 | bytes[1])/1000;
  data.ALARM_status=(bytes[6] & 0x01)? "TRUE":"FALSE";
  
  if((bytes[2]==0xff)&& (bytes[3]==0xff))
  {
    data.Temp_Red="NULL";
  }
  else
  {
    data.Temp_Red= parseFloat(((bytes[2]<<24>>16 | bytes[3])/10).toFixed(1));
  }

  if((bytes[7]==0xff)&& (bytes[8]==0xff))
  {
    data.Temp_White="NULL";
  }
  else
  {
  	data.Temp_White=parseFloat(((bytes[7]<<24>>16 | bytes[8])/10).toFixed(1));
  }
  
  if((bytes[9]==0xff)&& (bytes[10]==0xff))
  {
    data.Temp_Black="NULL";
  }
  else
  {
  	data.Temp_Black=parseFloat(((bytes[9]<<8 | bytes[10])/10) .toFixed(1)); 
  }
}
else if(mode=='31')
{
  data.Work_mode="ALARM";
  data.Temp_Red_MIN= bytes[4]<<24>>24;
  data.Temp_Red_MAX= bytes[5]<<24>>24; 
  data.Temp_White_MIN= bytes[7]<<24>>24;
  data.Temp_White_MAX= bytes[8]<<24>>24; 
  data.Temp_Black_MIN= bytes[9]<<24>>24;
  data.Temp_Black_MAX= bytes[10]<<24>>24;  
}

  if(bytes.length==11)
  return {
      data: data,
    }
	break;
default:
    return {
      errors: ["unknown FPort"]
    }
  }
}

The data that is then sent through to NodeRED via the MQTT service is a text formatted JSON data structure.

Comments

In previous PAEIoT projects, the decoding of the LoRaWAN uplink data has been done at a later step, in NodeRed. It was done like this for two reasons: 1) The encoded LoRaWAN packets were smaller for transmitting over the network; and 2) Understanding how to decode and process the data could be done separately to anything that TTN does.

Both of these conditions have changed.

In Version 3 of the TTN service, a lot more meta-data about the network is sent with the sensor data, so any advantages of savings made with minimising the size of the internet packet is lost.

As the uplink data formatting code is automatically included by the manucaturer, is available and open-source, provided thatit works, there is no advantage to not using it.

NodeRed and InfluxDB – Data Procesing and Storage

The following flow diagram describes the new path and changes added to support the new temperature sensor.

Specifically, the following changes and details were added.

TTN Decode (minor change)

The “TTN Decode” node now also passes the entire “uplink_message”, rather than just “payload_raw”. This means that the sensor location (longitude, latitude, and elevation) can be set via the registraion of the device in TTN.

payload.dev_id – Switch (New Output Added)

Added switch to separate flow for the Parks and Garden device (dev_id=eui-a840416eb183975f).

Note: When additional sensors are added, this switch node will need to be changed to also select the new sensor.

Parks Decode – Function (New)

This is the main function which pulls out and renames the data. The ‘msg.payload’ contains this data, and ‘msg.meta’ contains tags for the data.

// Parks Decode
// Decode temperature sensing device
// LSN50V2-D23 LORAWAN WATERPROOF TEMPERATURE SENSOR (3 PROBES)

var device_id = msg.payload.dev_id;

var batv       = msg.payload.uplink_message.decoded_payload.BatV;
var temp_black = msg.payload.uplink_message.decoded_payload.Temp_Black;
var temp_red   = msg.payload.uplink_message.decoded_payload.Temp_Red;
var temp_white = msg.payload.uplink_message.decoded_payload.Temp_White;

var latitude  = msg.payload.uplink_message.locations.user.latitude;
var longitude = msg.payload.uplink_message.locations.user.latitude;
var altitude  = msg.payload.uplink_message.locations.user.altitude;

var data = {};
data.batv       = batv;

data.temp_black = temp_black;
data.temp_red   = temp_red;
data.temp_white = temp_white;

data.temp_air     = temp_white;
data.temp_surface = temp_red;
data.temp_ground  = temp_black;

data.latitude   = latitude;
data.longitude  = longitude;
data.altitude   = altitude;

msg.payload = data;
msg.meta = {
    "device_id": device_id,
};

return msg;

InfluxDB Encode – Function (Copied)

This function is the same as prevously used to format the payload prior to sending it to the InfluxDB node (and into the database).

// InfluxDB Encode
var bucket    = "paeiot-bucket"

var device_id = msg.meta.device_id;
var fields    = msg.payload;

msg.payload = {   
  bucket: bucket,
  data: [{
    measurement: 'sensor',
    tags: {
      "dev_id":  device_id
    }, 
    fields: fields
  }]};

return msg;

InfluxDB – Database Node (Copied)

This uses the existing configured node without any changes.

Grafana Dashboard

A new folder and dashboardwas created to display the temperature data.

Parks and Gardens / Playing Ground Temperatures

The query used to return the air temperature (temp_air) is the following:

from(bucket: "paeiot-bucket")
 |> range(start: v.timeRangeStart, stop: v.timeRangeStop)
 |> filter(fn: (r) => r["_measurement"] == "sensor")
 |> filter(fn: (r) => r["dev_id"] == "eui-a840416eb183975f") 
 |> filter(fn: (r) => r["_field"] == "temp_air")
 |> drop(columns: ["dev_id", "latitude", "longitude", "altitude"])
 |> aggregateWindow(every: v.windowPeriod, fn: mean)
 |> yield(name: "mean")

An addtional two queries pull out the data for the surface temperature (temp_surface) and ground temperature (temp_ground) with the filter for the ‘_field’ value being changed respecfully. eg.

 filter(fn: (r) => r["_field"] == "temp_surface")
 filter(fn: (r) => r["_field"] == "temp_ground")

The resulting graph (as shown at the top of this post) also has some additional formatting changes (overrides), as pseudo-code:

Where field has name "temp_air", change Display Name to  "Air";
Where field has name "temp_surface", change Display Name to  "Surface";
Where field has name "temp_ground", change Display Name to  "Ground";

Conclusion

The existing PAE-IoT data processing system was modified to allow data from a newly added, commercially available temperature sensor, to be stored, displayed and dynamically updated.

A moderate amount of changes were required due to choices made by the hardware and system vendors. The system design choices that were made were informed by the desire to minimise additional changes if more sensors are added or if the system is extended in other straight forward ways.

This documentation is part of this process.

Power Monitoring using an Arduino

Open Energy Monitor is a project based in Wales which has developed an energy
and environmental monitoring system. They have an energy sensor (the emontx
series) which monitors the current in up to four(4) channels, together with the
AC voltage, in order to measure the power flowing through electrical circuits.

Current transformers are used, and are placed by clamping around individual
wires, allowing the current in the wire to be measured without making any change
or direct contact to the existing wiring.

The Open Energy Monitor store are selling their sensors as a kit, and one has
been ordered with four current transformers. This will be paired with an already
available Arduino UNO to allow for an evaluation of the monitoring software.

We are just after the power measurements for each channel to be reported via a
serial connection rather than using their project specific radio (a 433MHz radio
link).

All of the code that they are using (with and without the radio link) is
available via their forum and github repository.

As we evaluate this system we will be posting the results here.

The Open Energy Monitor also has a good set of documentation on how the units work, how they have been put together, and more on the theory of energy monitoring using current transformers.

New Toy (the reMarkable2) and a discussion about LoRaWAN and IoT

As a birthday present for myself earlier in the year I purchased a “reMarkable 2” e-ink tablet and it’s been awesome. More details about the device below (for those that are interested) but I recently had the chance to use it in a 1-1 meeting covering the PAE IoT Workshop and it worked really well as a paper notebook substitute. Afterwards I was able to go over the details, tidy them up, and rearrange them into a more sensible layout (rather than the original messy stream of consciousness).

Drawing on the reMarkable2

The tablet allows hand written text and drawings to be systematically edited, rearranged and replaced. There is the option on having layers (which I didn”t really use) and showing an underlying templete (lots to choose from) which is a useful guide for keeping everything nicely lined up, and which can be removed afterwards (replaced with the blank one).

The final result can emailed as PDF, PNG, or SVG formatted files, and the result is below.

About IoT Data Logging using LoRaWAN

The following is an example of the path which might be taken by a packet of date, created on a LoRaWAN IoT device, as it makes it’s way from the sensor to be displayed on a web-based dashboard on the Internet.

About the reMarkable2

There is quite a lot to talk about with the reMarkable2 but where is a vary brief summary – it’s a Linux based ARM system, which has Wifi access and drives a e-Ink display with stylus for drawing and input. The display and pen software is closed source, but everything else appears to be Free and Open Source Software. It is possible to SSH into the device from both Wifi and USB-C, with a password that is displayed from the settings menu. If you wanted to you could use that the change any of the software on the device but beware – there be dragons.

reMarkable (the company) currently send out software updates regularly (almost monthly), as these also include new features and tweeks.

There are also third party projects (the reHackable project) which make the tablet even more useful, and support the use of the reMarkable in many more ways than the manufacturer may have intended, including replacing the entire operating system. I have not considered doing this just yet.

Everything Old is New Again

Woohoo! A new project, or at the very least some new stuff to learn about. It’s been a while since I learnt about the basics of VLSI design and, in particular the ‘Magic’ chip design software package.

Google have just announced that they are partnering with SkyWater Technology Foundry to produce the “SkyWater Open Source PDK“, to produce a fully open Process Design Kit, for producing VLSI Chips. The 130nm process isn’t the newest, but it is still suitable for a variety of hardware applications.

As part of this collaboration, Google has also announced that they will be sponsoring a chip fabrication run later in the year, completely free for the chosen projects, when all the project code, file and documentation is Free and Open Source.

I’m not sure about you, but I have always loved the thought of producing a custom designed chip, otherwise known as an ASIC (Application Specific Integrated Circuit). There is going to be a whole bunch of things that I am going to have to learn, but being involved in the process of producing something like that will be awesome.

The aim is produce the design with cells provided in the SkyWater PDK. The initial proposal is that there will approximately 10mm^2 apace available (Maybe 3mm x 3mm). The 130nm process would there allow an area of 10,000 x 10,000 transistors ( Very roughly, if the transistors were 300nm in size. 3×10^-3 / (0.3 x 10^-6) = 10 x 10^3 )

Any-ho, this should be a lot of fun… and the Skywater-PDK Slack community has been particularly helpful.

References

Useful process documentation

Introduction to the design process for the chip fabrication process – https://www.vlsisystemdesign.com/inception-content-vsd/

The Super Chook House Project

After two years of delay, our household now has a chicken coop and five chickens (Bigbird, Tiny, Rose, Flame and Raptor).

Part of the plan other then getting the birds to produce eggs, eat garden waste, poop and generally scratch around, was to use this opportunity to turn their humble home into a Super Chicken House..

Currently, they need to be shut in and let our every day which which is not much of a chore but still needs to be done. Also, it would be nice to know when there are eggs to be collected, and if they need more water or food. Some temperature monitoring might also be ‘cool’ as well as air quality sensing.

As an acknowledgement to some other great work being done on home automation, the name and logo of the project had been blatantly copied and modified from Jon Oxer’s SuperHouse Automation business. (Does this classify as Fan art?)

Solar Power

I was struggling to find a reasonable cheap way to get power to the SuperCookHouse. I had some sets of solar powered garden fairy lights, several different models to experiment with. They all had internal batteries which charged up during the day and then automatically switched on at night.

The smaller units had multiple outputs on for their LED’s (three wires) which allowed them to have some interesting twinkle modes. They were cheaper, but they only contained a single Ni-MH battery. The larger unit had three batteries (see image below) but only had a two wire LED output. The cases themselves also had some rubber seals for waterproofing.

Inside connections and batteries of larger Solar Fairly Light unit.

In the larger unit the output from the charged batteries was 4.1V. This proved sufficient to power up a Heltec WiFi LoRa 32 (V2) board which I had at hand. This was connected directly across the batteries.

Connecting a device directly across the batteries.

This connection bypasses the power switch and the flashing circuit of the solar panel board. The batteries should still be able to be charged via the solar panel.

The single-sided controller board.

Briefly looking at the control board, with some hackery, it should be possible to make use of the on/off switch to control external power, but two other modifications would also need to be made;

  • bypass the flashing circuit
  • disable the ‘power off’ function when the solar panel is in light.

This work has been left to a time in the future.

Update: The batteries powered the module, as it was without any sensors, for about three hours.

Update 2: It looks like the chip SC24C02 (ATMEL268 24C02N) is an EEPROM 2-wire 2K memory chip (Datasheet). Pins 5 and 6 are the Serial Data (SDA) and Serial Clock Input (SCL) respectfully, which are routed up to pins 2 and 3 on the other (currently unknown) package.

Creating a Storybot

Testing Storybot output on a regular USB printer

Work has begun to create a robot for dispensing short stories at the touch of a button for Writers Week in 2020. The Storybot will be located in one of the Port Adelaide Enfield libraries and will print from it’s collection of pre-curated stories onto paper via a thermal printer for library patrons to take away with them.

Design

The initial design of the Storybot uses the following parts:

  • Raspberry Pi 4, with MicroSD card
  • Thermal Receipt Printer, USB (24V)
  • Button, resistor (220 Ohm) and connecting wire
  • Power supply (for Rasperry Pi and Printer)
  • Enclosure and stand

Intial print testing was done with a regular Canon USB Pixma printer.

Software

A repository of the code created for the Storybot can be found on GitHub. This repository ‘storybot’ is cloned directly into a subdirectory of the ‘pi’ user (in our case we are using ‘Document/git’).

The Raspberry Pi used has the most recent Raspbian installed which has been updated to the latest packages.

In addition, the CUPS Printing package has been installed, which allows Raspberry Pi to print to any of the supported printers including the receipt format thermal printer. This printer prints 40 column per row with a fixed width.

A quick solution[1] for selecting a random story used the ‘fortune‘[2] package.

Stories are copied to a directory on the Raspberry Pi as individual ASCII text files. Some example files have been created for testing purposes[3]. A global data file and index is created from these files, while also reformatting them for a 40 character line length. Fortune reads these files, and will extract a story and print it.

Story management is driven by a global Makefile with the following targets:

    make help    - this message (default)
make story - display a story
make prepare - compile the stories into data file
(This will be run automatically, if required.)
make list - list story files
make clean - reset system by removing generated files
make status - display system status

This system allows dependencies to be managed, so that ‘make prepare’ would be run if it is required and hasn’t yet been run, before ‘make story’. This allows new story uploads to be done even while the system may be printing.

Printing is done by sending (piping) the story output directly to the default printer with

    make story | lpr
Adding a button

To detect a button press, where a button has been wired up to a GPIO pin, there are several options available. These still need to be investigated, but they include:  Node-RED, WiringPi (C code and used in a previous project) or RPi.GPIO (Python)

  • Node-RED: This is a large-ish application, but it works well and does not require any addional configuration on system start-up and shut-down.
  • WiringPi: This C/C++library is useful for creating lightweight binary programs, but requires additional configuration to enable the created files to restart on reboot/startup. It is no longer being activity supported by it’s developer, but is open source software.
  • RPi.GPIO: Python library that together with Python makes writing scripts that interact with the GPIO on the RasberryPi very easy.

Each of these approaches will need to take care of button bounce/noisy inputs, and stop multiple press events happening in a short period. Some hardware conditioning may also be necessary.

Notes:
[1] Very quick. There are no options for recording any statistics about which stories are printed, or when, which might be a useful thing to record and report on.
[2] The fortune package has a very long history, originally appearing in very early editions of UNIX operating systems.
[3] Stories fro testing were created from the inital paragraphs from “The Princess Bride”, “War and Peace” and “A Tale of Two Cities”.