I have a UWP headed app running on my raspberry pi controlling a 8 relays HAT board. It works great. I added the possibility to also control the relays through a web server (I took the model from the "Blinky WebServer" app, it worked. As a final step, I want to convert my initial headed app with UWP UI interface into a headless (background) application. Control of the relays will only be available from the web interface. I created a new headless / background project and added my I/O class that control the relays. Now that I corrected the main issue based on Michael suggestion, I have issued creating the two main methods (read and write) for my I2Cio class. I need to be able to return a value from the "read" and pass a value to the "write". It is important to notice that the «Windows.Devices.I2c.I2cDevice» "Read" and "Write" methods are neither async methods. Code is available here: TestAsync.zip
Main task:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using System.Threading.Tasks;
using Windows.ApplicationModel.Background;
// The Background Application template is documented at http://go.microsoft.com/fwlink/?LinkID=533884&clcid=0x409
namespace TestAsync
{
public sealed class StartupTask : IBackgroundTask
{
private BackgroundTaskDeferral deferral;
I2Cio relay8;
string result;
public async void Run(IBackgroundTaskInstance taskInstance)
{
deferral = taskInstance.GetDeferral();
relay8 = new I2Cio();
result = await relay8.InitRelay8Async();
// For test purpose, we will loop and set relays
// according to an incrementing value
// We will wait 1/2 a second between each value
for(byte i = 0; i < 255; i++)
{
await relay8.WriteRelay8Async(i);
await Task.Delay(500);
}
// The logic handling the relays as well
// as the interprocess communication with
// the web server will come here
deferral.Complete();
}
}
I2Cio class with methods (simplified):
using System;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Devices.Enumeration;
using Windows.Devices.I2c;
using Windows.Foundation;
namespace TestAsync
{
public sealed class I2Cio
{
private const string I2C_CONTROLLER_NAME = "I2C1"; //specific to RPi2 or RPi3
private const byte RELAY8_ADDRESS = 0x27;
private const byte RELAY8_IN_REG_ADD = 0x00;
private const byte RELAY8_OUT_REG_ADD = 0x01;
private const byte RELAY8_CFG_REG_ADD = 0x03;
private const byte ALL_IO_OUTPUT = 0x00;
private static I2cConnectionSettings settings;
private static string deviceSelector;
private static DeviceInformationCollection i2cDeviceControllers;
private static I2cDevice relay8_Board;
private byte[] readBuffer;
public IAsyncOperation<string> InitRelay8Async()
{
return AsyncInfo.Run(async _ =>
{
return await InitRelay8AsyncInternal();
});
}
internal async Task<string> InitRelay8AsyncInternal()
{
try
{
settings = new I2cConnectionSettings(RELAY8_ADDRESS)
{
BusSpeed = I2cBusSpeed.FastMode
};
deviceSelector = I2cDevice.GetDeviceSelector(I2C_CONTROLLER_NAME);
i2cDeviceControllers = await DeviceInformation.FindAllAsync(deviceSelector);
if (i2cDeviceControllers.Count == 0)
{
throw new System.IO.FileNotFoundException("No RPII2C controllers were found on the system");
}
relay8_Board = await I2cDevice.FromIdAsync(i2cDeviceControllers[0].Id, settings);
if (relay8_Board == null)
{
throw new UnauthorizedAccessException(string.Format("Slave address {0} on RPII2C Controller {1} is currently in use by " +
"another application. Please ensure that no other applications are using RPII2C.", settings.SlaveAddress, i2cDeviceControllers[0].Id));
}
return null;
}
catch (Exception e)
{
System.Diagnostics.Debug.WriteLine("Exception: {0}", e.Message);
return null;
}
}
public IAsyncOperation<byte> ReadRelay8Async()
{
return AsyncInfo.Run(async _ =>
{
return await ReadRelay8AsyncInternal();
});
}
internal Task<byte> ReadRelay8AsyncInternal()
{
byte[] readBuf = new byte[2];
readBuf[0] = RELAY8_IN_REG_ADD;
relay8_Board.Read(readBuf);
return readBuf[1];
}
public IAsyncOperation<String> WriteRelay8Async(byte value)
{
return AsyncInfo.Run(async _ =>
{
return await WriteRelay8AsyncInternal(value);
});
}
public async Task<String> WriteRelay8AsyncInternal(byte value)
{
readBuffer = new byte[2];
// make all I/O to input / output
relay8_Board.Write(new byte[] { RELAY8_CFG_REG_ADD, ALL_IO_OUTPUT });
// output the value
relay8_Board.Write(new byte[] { RELAY8_OUT_REG_ADD, value });
// re-read the value for validation(for future validation if ever required
//relay8_Board.WriteRead(new byte[] { RELAY8_OUT_REG_ADD }, readBuffer);
return null;
}
public IAsyncOperation<String> ResetRelay8Async()
{
return AsyncInfo.Run(async _ =>
{
return await ResetRelay8AsyncInternal();
});
}
public async Task<String> ResetRelay8AsyncInternal()
{
// Set all 8 relays to 0
// 1 - make all I/O to input / output mode
relay8_Board.Write(new byte[] { RELAY8_CFG_REG_ADD, ALL_IO_OUTPUT });
// 2 - output the value of 0 to each
relay8_Board.Write(new byte[] { RELAY8_OUT_REG_ADD, 0x00 });
return null;
}
}
}