.NET nanoFramework BME680 Library Debugging Part 2

Reading the RAK1906 WisBlock Environment Sensor/BME680 GasResistance was failing randomly so I decided to dig a bit deeper. I checked the termination resistors, made sure the sensor was firmly seated on the RAK5005, and tried another Inter-Integrated Circuit(I²C) device on the same physical port.

I then used Visual Studio 2022 Debugger to “single step” further into the BME680 code and the first thing that looked a bit odd was the TryReadTemperatureCore, TryReadPressureCore, TryReadHumidityCore and TryReadGasResistanceCore return values were ignored.

/// <summary>
/// Performs a synchronous reading.
/// </summary>
/// <returns><see cref="Bme680ReadResult"/></returns>
public Bme680ReadResult Read()
{
   SetPowerMode(Bme680PowerMode.Forced);
   Thread.Sleep((int)GetMeasurementDuration(HeaterProfile).Milliseconds);

    TryReadTemperatureCore(out Temperature temperature);
    TryReadPressureCore(out Pressure pressure, skipTempFineRead: true);
    TryReadHumidityCore(out RelativeHumidity humidity, skipTempFineRead: true);
    TryReadGasResistanceCore(out ElectricResistance gasResistance);

    return new Bme680ReadResult(temperature, pressure, humidity, gasResistance);
}

I then single stepped into the TryReadTemperatureCore which was returning a boolean indicating whether the read was success.

private bool TryReadTemperatureCore(out Temperature temperature)
{
    if (TemperatureSampling == Sampling.Skipped)
    {
        temperature = default;
        return false;
    }

    var temp = (int)Read24BitsFromRegister((byte)Bme680Register.TEMPDATA, Endianness.BigEndian);

    temperature = CompensateTemperature(temp >> 4);
    return true;
}

This library was based on the dotnet/iot Bmxx80 code, it looked similar, but I missed an important detail lots more ?’s…

Console.WriteLine("Hello BME680!");

// The I2C bus ID on the Raspberry Pi 3.
const int busId = 1;
// set this to the current sea level pressure in the area for correct altitude readings
Pressure defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;

I2cConnectionSettings i2cSettings = new(busId, Bme680.DefaultI2cAddress);
I2cDevice i2cDevice = I2cDevice.Create(i2cSettings);

using Bme680 bme680 = new Bme680(i2cDevice, Temperature.FromDegreesCelsius(20.0));

while (true)
{
    // reset will change settings back to default
    bme680.Reset();

    // 10 consecutive measurement with default settings
    for (var i = 0; i < 10; i++)
    {
        // Perform a synchronous measurement
        var readResult = bme680.Read();

        // Print out the measured data
        Console.WriteLine($"Gas resistance: {readResult.GasResistance?.Ohms:0.##}Ohm");
        Console.WriteLine($"Temperature: {readResult.Temperature?.DegreesCelsius:0.#}\u00B0C");
        Console.WriteLine($"Pressure: {readResult.Pressure?.Hectopascals:0.##}hPa");
        Console.WriteLine($"Relative humidity: {readResult.Humidity?.Percent:0.#}%");

        if (readResult.Temperature.HasValue && readResult.Pressure.HasValue)
        {
            var altValue = WeatherHelper.CalculateAltitude(readResult.Pressure.Value, defaultSeaLevelPressure, readResult.Temperature.Value);
            Console.WriteLine($"Altitude: {altValue.Meters:0.##}m");
        }

        if (readResult.Temperature.HasValue && readResult.Humidity.HasValue)
        {
            // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
            Console.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(readResult.Temperature.Value, readResult.Humidity.Value).DegreesCelsius:0.#}\u00B0C");
            Console.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(readResult.Temperature.Value, readResult.Humidity.Value).DegreesCelsius:0.#}\u00B0C");
        }

        // when measuring the gas resistance on each cycle it is important to wait a certain interval
        // because a heating plate is activated which will heat up the sensor without sleep, this can
        // falsify all readings coming from the sensor
        Thread.Sleep(1000);
    }
    ...
}

The Bme680 Read() method checked the TryReadTemperatureCore, TryReadPressureCore, TryReadHumidityCore & TryReadGasResistanceCore return values.

/// <summary>
/// Performs a synchronous reading.
/// </summary>
/// <returns><see cref="Bme680ReadResult"/></returns>
public Bme680ReadResult Read()
{
    SetPowerMode(Bme680PowerMode.Forced);
    Thread.Sleep((int)GetMeasurementDuration(HeaterProfile).Milliseconds);

    var tempSuccess = TryReadTemperatureCore(out var temperature);
    var pressSuccess = TryReadPressureCore(out var pressure, skipTempFineRead: true);
    var humiditySuccess = TryReadHumidityCore(out var humidity, skipTempFineRead: true);
    var gasSuccess = TryReadGasResistanceCore(out var gasResistance);

    return new Bme680ReadResult(tempSuccess ? temperature : null, pressSuccess ? pressure : null, humiditySuccess ? humidity : null, gasSuccess ? gasResistance : null);
}

The dotnet/iot Bmxx80 library uses Nullable reference types which are not supported by the nanoFramework(Sept 2022), and this was overlooked when the library was ported.

I have created a Github issue.

.NET nanoFramework BME680 Library Debugging Part 1

I was intending to use a RAK1906 WisBlock Environment Sensor/BME680 for my nanoFramework RAK11200 Azure IoT Hub HTTP basic project, but the test application kept failing.

RAK1120+RAK5005+RAK106 Test setup

My test setup was a RAKwireless RAK11200 WisBlock WiFi Module, RAK5005 WisBlock Base Board and a RAK1906 WisBlock Environmental Sensor. I used the RAK1906 Sensor because it has nanoFramework.IoTDevice library support.

Visual Studio 2022 Output Window Output window when application failed

When I connected to the device with Tera Term it confirmed that the device was in a “kernel panic” loop.

nanoFramework Kernel Panic loop captured with Tera Term

Before I could debug the BME680 sample I had to get the Bmxx80 & Bmxx80.sample projects to compile (update NuGet packages and remove NerdBank.GitVersioning references).

BMXX80 Solution from nanoFramework.IoT.Device

I then used the Visual Studio 2022 Debugger to “single step” into the library code

/// <summary>
/// Sets the power mode to the given mode
/// </summary>
/// <param name="powerMode">The <see cref="Bme680PowerMode"/> to set.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown when the power mode does not match a defined mode in <see cref="Bme680PowerMode"/>.</exception>
[Property("PowerMode")]
public void SetPowerMode(Bme680PowerMode powerMode)
{
    //if (!powerMode.Equals(Bme680PowerMode.Forced) &&
    //    !powerMode.Equals(Bme680PowerMode.Sleep))
    //{
    //   throw new ArgumentOutOfRangeException();
    //}

    var status = Read8BitsFromRegister((byte)Bme680Register.CTRL_MEAS);
    status = (byte)((status & (byte)~Bme680Mask.PWR_MODE) | (byte)powerMode);

    SpanByte command = new[]
    {
        (byte)Bme680Register.CTRL_MEAS, status
    };
    _i2cDevice.Write(command);
}

The first problem was the two powerMode.Equals statements used to validate the powerMode parameter around line 287 in Bme680.cs so I commented them out.

Exception when getting the “GasResistance” value

On start-up references to readResult.GasResistance.Ohms would regularly fail, so I commented out everywhere it was used.

Exception when getting the “Barometric Pressure” value

Then references to readResult.Pressure.Hectopascals would randomly fail, so I commented out everywhere it was used.

public static void RunSample()
{
    Debug.WriteLine("Hello BME680!");

    //////////////////////////////////////////////////////////////////////
    Configuration.SetPinFunction(Gpio.IO04, DeviceFunction.I2C1_DATA);
    Configuration.SetPinFunction(Gpio.IO05, DeviceFunction.I2C1_CLOCK);

    // The I2C bus ID on the MCU.
    const int busId = 1;
    // set this to the current sea level pressure in the area for correct altitude readings
    Pressure defaultSeaLevelPressure = WeatherHelper.MeanSeaLevel;

    I2cConnectionSettings i2cSettings = new(busId, Bme680.DefaultI2cAddress);
    I2cDevice i2cDevice = I2cDevice.Create(i2cSettings);

    using Bme680 bme680 = new Bme680(i2cDevice, Temperature.FromDegreesCelsius(20.0));

    while (true)
    {
        // reset will change settings back to default
        bme680.Reset();

        // 10 consecutive measurement with default settings
        for (var i = 0; i < 10; i++)
        {
            // Perform a synchronous measurement
            var readResult = bme680.Read();

            // Print out the measured data
            //Debug.WriteLine($"Gas resistance: {readResult.GasResistance.Ohms}Ohm");
            Debug.WriteLine($"Temperature: {readResult.Temperature.DegreesCelsius}\u00B0C");
            //Debug.WriteLine($"Pressure: {readResult.Pressure.Hectopascals}hPa");
            Debug.WriteLine($"Relative humidity: {readResult.Humidity.Percent}%");

            /* 
            if (!readResult.Temperature.Equals(null) && !readResult.Pressure.Equals(null))
            {
                var altValue = WeatherHelper.CalculateAltitude(readResult.Pressure, defaultSeaLevelPressure, readResult.Temperature);
                Debug.WriteLine($"Altitude: {altValue.Meters}m");
            }

            if (!readResult.Temperature.Equals(null) && !readResult.Humidity.Equals(null))
            {
                // WeatherHelper supports more calculations, such as saturated vapor pressure, actual vapor pressure and absolute humidity.
                Debug.WriteLine($"Heat index: {WeatherHelper.CalculateHeatIndex(readResult.Temperature, readResult. Humidity).DegreesCelsius}\u00B0C");
                Debug.WriteLine($"Dew point: {WeatherHelper.CalculateDewPoint(readResult.Temperature, readResult.Humidity).DegreesCelsius}\u00B0C");
            }
            */

            // when measuring the gas resistance on each cycle it is important to wait a certain interval
            // because a heating plate is activated which will heat up the sensor without sleep, this can
            // falsify all readings coming from the sensor
            Thread.Sleep(1000);
        }
...
}
Visual Studio Debugger output displaying temperature and humidity values

After commenting the out all the .Equal, readResult.GasResistance.Ohms and readResult.Pressure.Hectopascals references the application would run for hours displaying only temperature and relative humidity values.

Next step is figuring out why the readResult.GasResistance.Ohms and readResult.Pressure.Hectopascals are failing.

I have created Github issue for the .Equals crash.

.NET nanoFramework RAK2305 – RAK4630 Basic connectivity issue

After much trial and error, I couldn’t get a RAK2305 WisBlock Wifi Interface Module running the .NET nanoFramework plugged into the IO Slot of RAK5005 Base Board to send RUIV3 AT Commands to a RAK4631 Module.

RA2305, RAK5005, RAK4631 test rig

When I requested the version information with “AT+VER=?” the RAK4630 Module did not respond with version information.

RA2305, RAK5005, RAK4631 firmware version request failure

I reviewed the schematics of the RAK2305 WisBlock Wifi Interface Module, RAK5005 Base Board and RAK4630 Module

RAK2305 ESP32 schematic

The RAK2305 WisBlock Wifi Interface Module has the TX0 pin is connected to pin 11, RX0 is connected to pin 12, TX1 pin (Gpio.IO21) is connected to pin 34, and the RX1 pin (Gpio.IO21) is connected to pin 33 of the IO Slot connector (crossover TX & RX).

RAK5005 schematic

On the RAK5005 Base Board the RAK2305 WisBlock Wifi Interface Module is plugged into the IO Extension Slot (BTB40_F) with TX pin 33 and RX pin 34.

RAK5005 schematic 2
RAK4361 schematic 1

The RAK4630 Module is plugged into the CPU slot (BTB40_F) of the RAK5005 Base Board with TX pin 33 and RX pin 34. The RAK4630 Module UART2_TX pin is connected to 33, and the UART2_RX is connected to 34 on the CPU slot.

I then read the RAK4630 AT Command documentation to see if I could enable AT Commands on the second serial port

I tried AT+ATM which didn’t work, and I had to reflash the device to get the UART0(USB port) to work. The TXD0 & RXD0 on the RAK4630 Module & RAK2305 WisBlock Wifi Interface Modules are connected by the RAK5005 Base Board. The .NET nanoFramework uses TXDO & RXD0 for debugging so I couldn’t connect to the first serial port on the RAK4630 Module

I had a look at the RAK4360 RAK Unified Interface (RUI) code to see if I could modify it so UART1 responded to AT Commands but I’m not certain this would work.

This is a longish post about failure, it took many hours to explore all the different approaches which was way longer than I should have spent. For why see “sunk cost fallacy”

.NET nanoFramework RAK11200 – Azure IoT Hub HTTP SAS Tokens

This is the simplest .NET nanoFramework Azure IoT Hub client I could come up with (inspired by this nanoFramework sample).

My test setup was a RAKwireless RAK11200 WisBlock WiFi Module, RAK5005 WisBlock Base Board or RAK19001 WisBlock Dual IO Base Board and RAK1901 WisBlock Temperature and Humidity Sensor

RAK112000+RAK5005-O+RAK1901 Test rig
RAK112000+RAK19001+RAK1901 Test rig

I used a RAK1901 WisBlock Temperature and Humidity Sensor because it has nanoFramework.IoTDevice library support

public class Program
{
    private static TimeSpan SensorUpdatePeriod = new TimeSpan(0, 30, 0);

    private static HttpClient _httpClient;

    public static void Main()
    {
        Debug.WriteLine("devMobile.IoT.RAK.Wisblock.AzureIoHub.RAK1901 starting");

        Configuration.SetPinFunction(Gpio.IO04, DeviceFunction.I2C1_DATA);
        Configuration.SetPinFunction(Gpio.IO05, DeviceFunction.I2C1_CLOCK);

        if (!WifiNetworkHelper.ConnectDhcp(Config.Ssid, Config.Password, requiresDateTime: true))
        {
            if (NetworkHelper.HelperException != null)
            {
                Debug.WriteLine($"WifiNetworkHelper.ConnectDhcp failed {NetworkHelper.HelperException}");
            }

            Thread.Sleep(Timeout.Infinite);
        }

        _httpClient = new HttpClient
        {
            SslProtocols = System.Net.Security.SslProtocols.Tls12,
            HttpsAuthentCert = new X509Certificate(Config.DigiCertBaltimoreCyberTrustRoot),
            BaseAddress = new Uri($"https://{Config.AzureIoTHubHostName}.azure-devices.net/devices/{Config.DeviceID}/messages/events?api-version=2020-03-13"),
        };
        _httpClient.DefaultRequestHeaders.Add("Authorization", Config.SasKey);

        I2cConnectionSettings settings = new(1, Shtc3.DefaultI2cAddress);
        I2cDevice device = I2cDevice.Create(settings);
        Shtc3 shtc3 = new(device);

        while (true)
        {
            if (shtc3.TryGetTemperatureAndHumidity(out var temperature, out var relativeHumidity))
            {
                Debug.WriteLine($"Temperature {temperature.DegreesCelsius:F1}°C  Humidity {relativeHumidity.Value:F0}%");

                string payload = $"{{\"RelativeHumidity\":{relativeHumidity.Value:F0},\"Temperature\":{temperature.DegreesCelsius.ToString("F1")}}}";

                try
                {
                    using (HttpContent content = new StringContent(payload))
                    using (HttpResponseMessage response = _httpClient.Post("", content))
                    {
                        Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} Response code:{response.StatusCode}");

                        response.EnsureSuccessStatusCode();
                    }
                }
                catch(Exception ex)
                {
                    Debug.WriteLine($"Azure IoT Hub POST failed:{ex.Message}");
                }
            }

            Thread.Sleep(SensorUpdatePeriod);
        }
    }
}

I generated the Azure IoT Hub Shared Access Signature(SAS) Tokens (10800 minutes is 1 week) with Azure IoT Explorer (Trim the SAS key so it starts with SharedAccessSignature sr=….)

Azure IoT Explorer SAS Token Generation

I was using Azure IoT Explorer to monitor the telemetry and found that the initial versions of the application would fail after 6 or 7 hours. After reviewing the code I added a couple of “using” statements which appear to have fixed the problem as the soak test has been running for 12hrs, 24hrs, 36hrs, 48hrs, 96hrs

.NET nanoFramework RAK2305 – RAK4200 Library Usage (AS923 Sorted)

This post covers the usage of my RAK4200LoRaWAN-NetNF library with a RAK3205 WisBlock Wifi Interface Module on a RAK4200 Evaluation Board. This post was delayed because of the issue covered in .NET nanoFramework RAK2305 – RAK4200 Library Usage AS923 Issue. After posting in the RAKWireless formus RAKWireless support very quickly provided updated RAK4200 firmware which fixed the issue.

RAK2305 RAK4200 Evaluation Board based test rig

The RAK4200LoRaWANDeviceClient now reliably joins The Things Network, then sends and receives messages.

When I initially deployed the RAK4200LoRaWANDeviceClient the RAK4200LoRaWAN-NetNF library failed in the OtaaInitialise method. I think this was caused by the “at+set_config=lora:work_mode:0” command rebooting the RAK4200 Module. I have commented out the code but may move it to a standalone method if required.

// Set the Working mode to LoRaWAN, not/never going todo P2P with this library.
#if DIAGNOSTICS
Debug.WriteLine($" {DateTime.UtcNow:hh:mm:ss} at+set_config=lora:work_mode:0");
#endif
Result result = SendCommand("Initialization OK", "at+set_config=lora:work_mode:0", CommandTimeoutDefault);
if (result != Result.Success)
{
#if DIAGNOSTICS
         Debug.WriteLine($" {DateTime.UtcNow:hh:mm:ss} at+set_config=lora:work_mode:0 failed {result}");
#endif
	return result;
}

I think it would be reasonable to assume that the device is in the correct mode (the default after a reset to factory) on startup so I removed the LoRa® network work mode configuration code.

.NET nanoFramework RAK2305 – RAK4200 Library AS923 Issue

This post was going to be about how to the use my RAK4200LoRaWAN-NetNF library with a RAK3205 WisBlock Wifi Interface Module and RAK4200 Evaluation Board but there was a problem…

RAK2305 RAK4200 Evaluation Board based test rig

When I ran the RAK4200LoRaWANDeviceClient the first couple of join attempts failed which was odd as my sparkfun ESP32 thing plus with RAK4200 Breakout Board setup was very reliable.

Visual Studio Debug output for RAK4200LoRaWANDeviceClient Join failure
The Things Network RAK4200LoRaWANDeviceClient application Join failure

When I looked at The Things Network “Live data” tab the RAK4200 Module on the RAK4200 Evaluation Board wasn’t using the LoRaWAN AS923 Join-Request channels 923.20 & 923.40 MHz.

AS923 Join Channels

The RAK4200 Module on the appeared to be cycling through all the AS923 channels and every so often would use one the join request channels.

Visual Studio Debug output for RAK4200LoRaWANDeviceClient successful Join and Send
The Things Network RAK4200LoRaWANDeviceClient successful Join and Send

The RAK4200 Breakout Board module is running a later firmware version (V3.2.0.16) than the RAK4200 Evaluation Board module (V3.2.0.15) which is most probably the problem.

Visual Studio Debug output for RAK4200 Evaluation Board Version Request
Visual Studio Debug output for RAK4200 Breakout Board Version Request

The RAK811 module (which has been retired) also had similar issues with AS923.

.NET nanoFramework RAK2305 – RAK4200 Basic connectivity

After some experimentation could get a RAK2305 WisBlock Wifi Interface Module running the .NET nanoFramework plugged into the IO Slot of RAK4200 Evaluation Board to send AT Commands to the RAK4200 Module.

RAK4200 EVB with FTDI Adaptor

After reviewing the RAK4200 Evaluation Board and RAK2305 WisBlock Wifi Interface Module schematics I realised that the Universal Asynchronous Receiver-Transmistted(UART) transmit and receive pins had to be reversed the with the nanoFramwork ESP32 specific Configuration.SetPinFunction.

namespace devMobile.IoT.LoRaWAN.nanoFramework.RAK4200
{
	using System;
	using System.Diagnostics;
	using System.IO.Ports;
	using System.Threading;
   using global::nanoFramework.Hardware.Esp32; //need NuGet nanoFramework.Hardware.Esp32

   public class Program
	{
		private static SerialPort _SerialPort;
        private const string SerialPortId = "COM2";

        public static void Main()
		{
			Thread.Sleep(5000);

#if SERIAL_THREADED_READ
			Thread readThread = new Thread(SerialPortProcessor);
#endif

			Debug.WriteLine("devMobile.IoT.LoRaWAN.nanoFramework.RAK4200 BreakoutSerial starting");

			try
			{
            // set GPIO functions for COM2 (this is UART1 on ESP32)
            Configuration.SetPinFunction(Gpio.IO21, DeviceFunction.COM2_TX);
			Configuration.SetPinFunction(Gpio.IO19, DeviceFunction.COM2_RX);

            Debug.Write("Ports:");
				foreach (string port in SerialPort.GetPortNames())
				{
					Debug.Write($" {port}");
				}
				Debug.WriteLine("");

				using (_SerialPort = new SerialPort(SerialPortId))
				{
					// set parameters
					//_SerialPort.BaudRate = 9600;
					_SerialPort.BaudRate = 115200;
					_SerialPort.Parity = Parity.None;
					_SerialPort.DataBits = 8;
					_SerialPort.StopBits = StopBits.One;
					_SerialPort.Handshake = Handshake.None;
					_SerialPort.NewLine = "\r\n";

					//_SerialPort.ReadBufferSize = 128; 
					//_SerialPort.ReadBufferSize = 256; 
					_SerialPort.ReadBufferSize = 512; 
					//_SerialPort.ReadBufferSize = 1024;
					_SerialPort.ReadTimeout = 1000;

					//_SerialPort.WatchChar = '\n'; // May 2022 WatchChar event didn't fire github issue https://github.com/nanoframework/Home/issues/1035

					_SerialPort.DataReceived += SerialDevice_DataReceived;

					_SerialPort.Open();

					_SerialPort.WatchChar = '\n';

					for (int i = 0; i < 5; i++)
					{
						string atCommand;
						atCommand = "at+version";
						//atCommand = "at+set_config=device:uart:1:9600";
						//atCommand = "at+get_config=lora:status";
						//atCommand = "at+get_config=device:status";
						//atCommand = "at+get_config=lora:channel";
						//atCommand = "at+help";
						//atCommand = "at+set_config=device:restart";
						//atCommand = "at+set_config=lora:default_parameters";
						//atCommand = "at+set_config=lora:work_mode:0";
						Debug.WriteLine("");
						Debug.WriteLine($"{i} TX:{atCommand} bytes:{atCommand.Length}--------------------------------");
						_SerialPort.WriteLine(atCommand);

						Thread.Sleep(5000);
					}
				}
				Debug.WriteLine("Done");
			}
			catch (Exception ex)
			{
				Debug.WriteLine(ex.Message);
			}
		}

		private static void SerialDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
		{
			SerialPort serialPort = (SerialPort)sender;

			switch (e.EventType)
			{
				case SerialData.Chars:
					break;

				case SerialData.WatchChar:
					string response = serialPort.ReadExisting();
					Debug.Write(response);
					break;
				default:
					Debug.Assert(false, $"e.EventType {e.EventType} unknown");
					break;
			}
		}
	}
}

When I requested the version information with “at+version” the RAK4200 Module responded with version information.

RAK4200 EVB Debug Output

.NET nanoFramework RAK2305 – RAK3172 Library Usage

This post covers the usage of my RAK3172LoRaWAN-NetNF library with a RAK3205 WisBlock Wifi Interface Module on a RAK3172 Evaluation Board.

RAK2305 RAK3172 Evaluation Board based test rig

The first time the RAK3172LoRaWANDeviceClient is run the following preprocessor directives may need to be defined to configure the RAK3172 module.

//---------------------------------------------------------------------------------
//#define ST_STM32F769I_DISCOVERY      // nanoff --target ST_STM32F769I_DISCOVERY --update 
//#define  SPARKFUN_ESP32_THING_PLUS  // nanoff --platform esp32 --serialport COM4 --update
//#define RAK_WISBLOCK_RAK2305 // nanoff --update --target ESP32_PSRAM_REV0 --serialport COM4
#define DEVICE_DEVEUI_SET
//#define FACTORY_RESET
//#define PAYLOAD_BCD
#define PAYLOAD_BYTES
#define OTAA
//#define ABP
//#define CONFIRMED
#define UNCONFIRMED
#define REGION_SET
#define ADR_SET
//#define SLEEP
namespace devMobile.IoT.LoRaWAN
{
Visual Studio Debug output for RAK3172LoRaWANDeviceClient full configuration

Once the RAK3172 Module is the RAK3172LoRaWANDeviceClient can be run with only PAYLOAD_BCD or PAYLOAD_BYTES defined

//---------------------------------------------------------------------------------
//#define ST_STM32F769I_DISCOVERY      // nanoff --target ST_STM32F769I_DISCOVERY --update 
//#define  SPARKFUN_ESP32_THING_PLUS  // nanoff --platform esp32 --serialport COM4 --update
//#define RAK_WISBLOCK_RAK2305 // nanoff --update --target ESP32_PSRAM_REV0 --serialport COM4
//#define DEVICE_DEVEUI_SET
//#define FACTORY_RESET
//#define PAYLOAD_BCD
#define PAYLOAD_BYTES
//#define OTAA
//#define ABP
//#define CONFIRMED
//#define UNCONFIRMED
//#define REGION_SET
//#define ADR_SET
//#define SLEEP
namespace devMobile.IoT.LoRaWAN
{
Visual Studio Debug output for RAK3172LoRaWANDeviceClient minimal configuration

When I initially deployed ran the RAK3172LoRaWANDeviceClient the RAK3172LoRaWAN-NetNF library crashed in the OtaaInitialise method. I think this was caused by the RAKwireless Unified Interface V3(RUIV3) “AT+NWM=1” command rebooting the RAK3172 Module.

// Set the Working mode to LoRaWAN, not/never going todo P2P with this library.
#if DIAGNOSTICS
Debug.WriteLine($" {DateTime.UtcNow:hh:mm:ss} AT+NWM=1");
#endif
Result result = SendCommand("Current Work Mode: LoRaWAN.", "AT+NWM=1", CommandTimeoutDefault);
if (result != Result.Success)
{
#if DIAGNOSTICS
	Debug.WriteLine($" {DateTime.UtcNow:hh:mm:ss} AT+NWM=1 failed {result}");
#endif
	return result;
}

I think it would be reasonable to assume that the device is in the correct mode (the default after a reset to factory) on startup so I removed the LoRa® network work mode configuration code.

.NET nanoFramework RAK2305 – RAK3172 Basic connectivity

After some experimentation could get a RAK2305 WisBlock Wifi Interface Module running the .NET nanoFramework plugged into the IO Slot of RAK3172 Evaluation Board to send RUIV3 AT Commands to the RAK3172 Module.

RAK2305 + RAK 3172 EVB with FTDI module for Visual Studio 2022 Connectivity

After reviewing the RAK3172 Evaluation Board and RAK2305 WisBlock Wifi Interface Module schematics I realised that the Universal Asynchronous Receiver-Transmistted(UART) transmit and receive pins had to be reversed the with the nanoFramwork ESP32 specific Configuration.SetPinFunction.

namespace devMobile.IoT.LoRaWAN.nanoFramework.RAK.LoraWAN
{ 
   using System;
   using System.Diagnostics;
   using System.IO.Ports;
   using System.Threading;
   using global::nanoFramework.Hardware.Esp32;

   public class Program
   {
      private static SerialPort _SerialPort;

      private const string SerialPortId = "COM2";

      public static void Main()
      {
         Debug.WriteLine("devMobile.IoT.LoRaWAN.nanoFramework.RAK.LoraWAN RAK3172/RAK4630 EVB starting");

         try
         {
            // set GPIO functions for COM2 (this is UART1 on RAK2305)
            Configuration.SetPinFunction(Gpio.IO21, DeviceFunction.COM2_TX);
            Configuration.SetPinFunction(Gpio.IO19, DeviceFunction.COM2_RX);

            Debug.Write("Ports:");
            foreach (string port in SerialPort.GetPortNames())
            {
               Debug.Write($" {port}");
            }
            Debug.WriteLine("");

            using (_SerialPort = new SerialPort(SerialPortId))
            {
               // set parameters
               _SerialPort.BaudRate = 115200;
               _SerialPort.Parity = Parity.None;
               _SerialPort.DataBits = 8;
               _SerialPort.StopBits = StopBits.One;
               _SerialPort.Handshake = Handshake.None;
               _SerialPort.NewLine = "\r\n";
               _SerialPort.ReadTimeout = 1000;

               //_SerialPort.WatchChar = '\n'; // May 2022 WatchChar event didn't fire github issue https://github.com/nanoframework/Home/issues/1035

               _SerialPort.DataReceived += SerialDevice_DataReceived;

               _SerialPort.Open();

               _SerialPort.WatchChar = '\n';

               _SerialPort.ReadExisting(); // Running at 115K2 this was necessary


               for (int i = 0; i < 5; i++)
               {
                  string atCommand;
                  atCommand = "AT+VER=?";
                  //atCommand = "AT+SN=?"; // Empty response?
                  //atCommand = "AT+HWMODEL=?";
                  //atCommand = "AT+HWID=?";
                  //atCommand = "AT+DEVEUI=?";
                  //atCommand = "AT+APPEUI=?";
                  //atCommand = "AT+APPKEY=?";
                  //atCommand = "ATR";
                  //atCommand = "AT+SLEEP=4000";
                  //atCommand = "AT+ATM";
                  //atCommand = "AT?";
                  Debug.WriteLine("");
                  Debug.WriteLine($"{DateTime.UtcNow:hh:mm:ss} {i} TX:{atCommand} bytes:{atCommand.Length}--------------------------------");
                  _SerialPort.WriteLine(atCommand);

                  Thread.Sleep(5000);
               }
            }
            Debug.WriteLine("Done");
         }
         catch (Exception ex)
         {
            Debug.WriteLine(ex.Message);
         }
      }

      private static void SerialDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
         SerialPort serialPort = (SerialPort)sender;

         switch (e.EventType)
         {
            case SerialData.Chars:
               break;

            case SerialData.WatchChar:
               string response = serialPort.ReadExisting();
               Debug.Write(response);
               break;
            default:
               Debug.Assert(false, $"e.EventType {e.EventType} unknown");
               break;
         }
      }
   }
}

When I requested the version information with “AT+VER=?” the RAK3172 Module responded with version information.

.NET nanoFramework RAK2305 – UART GPS

The RAKwireless RAK2305 WisBlock WiFi Interface Module module is based on an Expressif ESP32 processor which is supported by the .NET nanoFramework and I wanted try out it out with a RAK1910 GNSS GPS Location Module.

RAK2350, RAK5005-O and RAK1910 with GPS Antenna

The RAK1910 application is based on the TinyGPSPlusNF library by MBoude which parses the NMEA 0183 sentences produced by the RAK1910.

//---------------------------------------------------------------------------------
// Copyright (c) August 2022, devMobile Software
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// RAK Core WisBlock
// https://docs.rakwireless.com/Product-Categories/WisBlock/RAK11200
//
// RAK WisBlock Wireless
// https://docs.rakwireless.com/Product-Categories/WisBlock/RAK2305/Overview/
//
// RAK WisBlock Bases
// https://docs.rakwireless.com/Product-Categories/WisBlock/RAK5005-O

// https://docs.rakwireless.com/Product-Categories/WisBlock/RAK19001
//
// RAK WisBlock Sensor
// https://docs.rakwireless.com/Product-Categories/WisBlock/RAK1910
//
// Uses the library
// https://github.com/mboud/TinyGPSPlusNF
//
// Inspired by
// https://github.com/RAKWireless/WisBlock/tree/master/examples/common/sensors/RAK1910_GPS_UBLOX7
//
// Pins mapped with
// https://docs.rakwireless.com/Knowledge-Hub/Pin-Mapper/
//
// Flash device with
// nanoff --target ESP32_REV0 --serialport COM16 --update
//
//---------------------------------------------------------------------------------
namespace devMobile.IoT.RAK.Wisblock.RAK1910
{
   using System;
   using System.Device.Gpio;
   using System.Diagnostics;
   using System.IO.Ports;
   using System.Threading;

   using nanoFramework.Hardware.Esp32;

   using TinyGPSPlusNF;

   public class Program
   {
      private static TinyGPSPlus _gps;

      public static void Main()
      {
         Debug.WriteLine($"devMobile.IoT.RAK.Wisblock.RAK1910 starting TinyGPS {TinyGPSPlus.LibraryVersion}");

         try
         {
#if RAK11200
            Configuration.SetPinFunction(Gpio.IO21, DeviceFunction.COM2_TX);
            Configuration.SetPinFunction(Gpio.IO19, DeviceFunction.COM2_RX);
#endif
#if RAK2350
            Configuration.SetPinFunction(Gpio.IO21, DeviceFunction.COM2_RX);
            Configuration.SetPinFunction(Gpio.IO19, DeviceFunction.COM2_TX);
#endif

            _gps = new TinyGPSPlus();

            // UART1 with default Max7Q baudrate
            SerialPort serialPort = new SerialPort("COM2", 9600);

            serialPort.DataReceived += SerialDevice_DataReceived;
            serialPort.Open();
            serialPort.WatchChar = '\n';

            // Enable the GPS module GPS 3V3_S/RESET_GPS - IO2 - GPIO27
            GpioController gpioController = new GpioController();

            GpioPin Gps3V3 = gpioController.OpenPin(Gpio.IO27, PinMode.Output);
            Gps3V3.Write(PinValue.High);

            Debug.WriteLine("Waiting...");

            Thread.Sleep(Timeout.Infinite);
         }
         catch (Exception ex)
         {
            Debug.WriteLine($"UBlox MAX7Q initialisation failed {ex.Message}");

            Thread.Sleep(Timeout.Infinite);
         }
      }

      private static void SerialDevice_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {
         // we only care if got EoL character
         if (e.EventType != SerialData.WatchChar)
         {
            return;
         }

         SerialPort serialDevice = (SerialPort)sender;

         string sentence = serialDevice.ReadExisting();

         if (_gps.Encode(sentence))
         {
            if (_gps.Date.IsValid)
            {
               Debug.Write($"{_gps.Date.Year}-{_gps.Date.Month:D2}-{_gps.Date.Day:D2} ");
            }

            if (_gps.Time.IsValid)
            {
               Debug.Write($"{_gps.Time.Hour:D2}:{_gps.Time.Minute:D2}:{_gps.Time.Second:D2}.{_gps.Time.Centisecond:D2} ");
            }

            if (_gps.Location.IsValid)
            {
               Debug.Write($"Lat:{_gps.Location.Latitude.Degrees:F5}° Lon:{_gps.Location.Longitude.Degrees:F5}° ");
            }

            if (_gps.Altitude.IsValid)
            {
               Debug.Write($"Alt:{_gps.Altitude.Meters:F1}M ");
            }

            if (_gps.Location.IsValid)
            {
               Debug.Write($"Hdop:{_gps.Hdop.Value:F2}");
            }

            if (_gps.Date.IsValid || _gps.Time.IsValid || _gps.Location.IsValid || _gps.Altitude.IsValid)
            {
               Debug.WriteLine("");
            }
         }
      }
   }
}

My RAK2305 WisBlock WiFi Interface Module, RAK1910, and RAK5005-O WisBlock Base Board configuration wasn’t supported by the RAK WinBlock Pin Mapper(AUG 2022) tool.

After some experimentation I found that serial port TX/RX lines had to be reversed because both devices would normally be connected to a WisBlock core module.

Visual Studio 2K22 Output Window