For this project we are assuming, that you have a C# development environment set up and that you have a rudimentary understanding of the C# language.
If you are totally new to C# itself you should start here. If you are new to the Tinkerforge API, you should start here.
We are setting the following goals for this project:
Since this project will likely run 24/7, we will also make sure that the application is as robust towards external influences as possible. The application should still work when
In the following we will show step-by-step how this can be achieved.
To start off, we need to define where our program should connect to:
private static string HOST = "localhost";
private static int PORT = 4223;
If the WIFI Extension is used or if the Brick Daemon is running on a different PC, you have to exchange "localhost" with the IP address or hostname of the WIFI Extension or PC.
When the program is started, we need to register the EnumerateCallback
callback and the Connected
callback and trigger a first
enumerate:
static void Main()
{
ipcon = new IPConnection();
ipcon.Connect(HOST, PORT);
ipcon.EnumerateCallback += EnumerateCB;
ipcon.Connected += ConnectedCB;
ipcon.Enumerate();
}
The enumerate callback is triggered if a Brick gets connected over USB or if
the Enumerate()
function is called. This allows to discover the Bricks and
Bricklets in a stack without knowing their types or UIDs beforehand.
The connected callback is triggered if the connection to the WIFI Extension or to the Brick Daemon got established. In this callback we need to trigger the enumerate again, if the reason is an auto reconnect:
static void ConnectedCB(IPConnection sender, short connectedReason)
{
if(connectedReason == IPConnection.CONNECT_REASON_AUTO_RECONNECT)
{
ipcon.Enumerate();
}
}
An auto reconnect means, that the connection to the WIFI Extension or to the Brick Daemon was lost and could subsequently be established again. In this case the Bricklets may have lost their configurations and we have to reconfigure them. Since the configuration is done during the enumeration process (see below), we have to trigger another enumeration.
Step 1 put together:
class WeatherStation
{
private static string HOST = "localhost";
private static int PORT = 4223;
static void ConnectedCB(IPConnection sender, short connectedReason)
{
if(connectedReason == IPConnection.CONNECT_REASON_AUTO_RECONNECT)
{
ipcon.Enumerate();
}
}
static void Main()
{
ipcon = new IPConnection();
ipcon.Connect(HOST, PORT);
ipcon.EnumerateCallback += EnumerateCB;
ipcon.Connected += ConnectedCB;
ipcon.Enumerate();
}
}
During the enumeration we want to configure all of the weather measuring Bricklets. Doing this during the enumeration ensures that Bricklets get reconfigured if the stack was disconnected or there was a power loss.
The configurations should be performed on first startup
(ENUMERATION_TYPE_CONNECTED
) as well as whenever the enumeration is
triggered externally by us (ENUMERATION_TYPE_AVAILABLE
):
static void EnumerateCB(IPConnection sender, string UID, string connectedUID, char position,
short[] hardwareVersion, short[] firmwareVersion,
int deviceIdentifier, short enumerationType)
{
if(enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED ||
enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE)
The LCD 20x4 configuration is simple, we want the current text cleared and we want the backlight on:
if(deviceIdentifier == BrickletLCD20x4.DEVICE_IDENTIFIER)
{
brickletLCD = new BrickletLCD20x4(UID, ipcon);
brickletLCD.ClearDisplay();
brickletLCD.BacklightOn();
}
We configure the Ambient Light, Humidity and Barometer Bricklet to return their respective measurements continuously with a period of 1000ms (1s):
else if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER)
{
brickletAmbientLight = new BrickletAmbientLight(UID, ipcon);
brickletAmbientLight.SetIlluminanceCallbackPeriod(1000);
brickletAmbientLight.Illuminance += IlluminanceCB;
}
else if(deviceIdentifier == BrickletHumidity.DEVICE_IDENTIFIER)
{
brickletHumidity = new BrickletHumidity(UID, ipcon);
brickletHumidity.SetHumidityCallbackPeriod(1000);
brickletHumidity.Humidity += HumidityCB;
}
else if(deviceIdentifier == BrickletBarometer.DEVICE_IDENTIFIER)
{
brickletBarometer = new BrickletBarometer(UID, ipcon);
brickletBarometer.SetAirPressureCallbackPeriod(1000);
brickletBarometer.AirPressure += AirPressureCB;
}
This means that the Bricklets will call the IlluminanceCB
, HumidityCB
and AirPressureCB
callback functions whenever the value has changed, but
with a maximum period of 1000ms.
Step 2 put together:
static void EnumerateCB(IPConnection sender, string UID, string connectedUID, char position,
short[] hardwareVersion, short[] firmwareVersion,
int deviceIdentifier, short enumerationType)
{
if(enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED ||
enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE)
{
if(deviceIdentifier == BrickletLCD20x4.DEVICE_IDENTIFIER)
{
brickletLCD = new BrickletLCD20x4(UID, ipcon);
brickletLCD.ClearDisplay();
brickletLCD.BacklightOn();
}
else if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER)
{
brickletAmbientLight = new BrickletAmbientLight(UID, ipcon);
brickletAmbientLight.SetIlluminanceCallbackPeriod(1000);
brickletAmbientLight.Illuminance += IlluminanceCB;
}
else if(deviceIdentifier == BrickletHumidity.DEVICE_IDENTIFIER)
{
brickletHumidity = new BrickletHumidity(UID, ipcon);
brickletHumidity.SetHumidityCallbackPeriod(1000);
brickletHumidity.Humidity += HumidityCB;
}
else if(deviceIdentifier == BrickletBarometer.DEVICE_IDENTIFIER)
{
brickletBarometer = new BrickletBarometer(UID, ipcon);
brickletBarometer.SetAirPressureCallbackPeriod(1000);
brickletBarometer.AirPressure += AirPressureCB;
}
}
}
We want a neat arrangement of the measurements on the display, such as:
Illuminanc 137.39 lx
Humidity 34.10 %
Air Press 987.70 mb
Temperature 22.64 °C
The decimal marks and the units should be below each other. To achieve this we use two characters for the unit, two decimal places and crop the name to use the maximum characters that are left. That's why "Illuminanc" is missing its final "e".
string text = string.Format("{0,6:###.00}", value);
The code above converts a floating point value to a string according to the given format specification. The result will be at least 6 characters long with 2 decimal places, filled up with spaces from the left if it would be shorter than 6 characters otherwise.
static void IlluminanceCB(BrickletAmbientLight sender, int illuminance)
{
string text = string.Format("Illuminanc {0,6:###.00} lx", illuminance/10.0);
brickletLCD.WriteLine(0, 0, text);
}
static void HumidityCB(BrickletHumidity sender, int humidity)
{
string text = string.Format("Humidity {0,6:###.00} %", humidity/10.0);
brickletLCD.WriteLine(1, 0, text);
}
static void AirPressureCB(BrickletBarometer sender, int airPressure)
{
string text = string.Format("Air Press {0,7:####.00} mb", airPressure/1000.0);
brickletLCD.WriteLine(2, 0, text);
}
We are still missing the temperature. The Barometer Bricklet can
measure temperature, but it doesn't have a callback for it. As a
simple workaround we can retrieve the temperature in the AirPressureCB
callback function:
static void AirPressureCB(BrickletBarometer sender, int airPressure)
{
string text = string.Format("Air Press {0,7:####.00} mb", airPressure/1000.0);
brickletLCD.WriteLine(2, 0, text);
int temperature = sender.GetChipTemperature();
text = string.Format("Temperature {0,5:##.00} {1}C", temperature/100.0, (char)0xDF);
brickletLCD.WriteLine(3, 0, text);
}
Step 3 put together:
static void IlluminanceCB(BrickletAmbientLight sender, int illuminance)
{
string text = string.Format("Illuminanc {0,6:###.00} lx", illuminance/10.0);
brickletLCD.WriteLine(0, 0, text);
}
static void HumidityCB(BrickletHumidity sender, int humidity)
{
string text = string.Format("Humidity {0,6:###.00} %", humidity/10.0);
brickletLCD.WriteLine(1, 0, text);
}
static void AirPressureCB(BrickletBarometer sender, int airPressure)
{
string text = string.Format("Air Press {0,7:####.00} mb", airPressure/1000.0);
brickletLCD.WriteLine(2, 0, text);
int temperature = sender.GetChipTemperature();
// 0xDF == ° on LCD 20x4 charset
text = string.Format("Temperature {0,5:##.00} {1}C", temperature/100.0, (char)0xDF);
brickletLCD.WriteLine(3, 0, text);
}
That's it. If we would copy these three steps together in one file and execute it, we would have a working Weather Station!
There are some obvious ways to make the output better.
The name could be cropped according to the exact space that is available
(depending on the number of digits of the measured value). Also, reading the
temperature in the AirPressureCB
callback function is suboptimal. If the
air pressure doesn't change, we won't update the temperature. It would be better to read the temperature in a different thread in an endless
loop with a one second sleep after each read. But we want to keep this code as
simple as possible.
However, we do not meet all of our goals yet. The program is not yet robust enough. What happens if it can't connect on startup? What happens if the enumerate after an auto reconnect doesn't work?
What we need is error handling!
On startup, we need to try to connect until the connection works:
while(true)
{
try
{
ipcon.Connect(HOST, PORT);
break;
}
catch(System.Net.Sockets.SocketException e)
{
System.Console.WriteLine("Connection Error: " + e.Message);
System.Threading.Thread.Sleep(1000);
}
}
and we need to try enumerating until the message goes through:
while(true)
{
try
{
ipcon.Enumerate();
break;
}
catch(NotConnectedException e)
{
System.Console.WriteLine("Enumeration Error: " + e.Message);
System.Threading.Thread.Sleep(1000);
}
}
With these changes it is now possible to first start the program and connect the Weather Station afterwards.
We also need to make sure, that we only write to the LCD if it is already initialized:
static void IlluminanceCB(BrickletAmbientLight sender, int illuminance)
{
if(brickletLCD != null)
{
string text = string.Format("Illuminanc {0,6:###.00} lx", illuminance/10.0);
brickletLCD.WriteLine(0, 0, text);
System.Console.WriteLine("Write to line 0: " + text);
}
}
and that we have to deal with errors during the initialization:
if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER)
{
try
{
brickletAmbientLight = new BrickletAmbientLight(UID, ipcon);
brickletAmbientLight.SetIlluminanceCallbackPeriod(1000);
brickletAmbientLight.Illuminance += IlluminanceCB;
System.Console.WriteLine("Ambient Light initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Ambient Light init failed: " + e.Message);
brickletAmbientLight = null;
}
}
Additionally we added some logging. With the logging we can later find out what exactly caused a problem, if the Weather Station failed for some time period.
For example, if we connect to the Weather Station via Wi-Fi and we have regular auto reconnects, it likely means that the Wi-Fi connection is not very stable.
That's it! We are already done with our Weather Station and all of the goals should be met.
Now all of the above put together (download):
using Tinkerforge;
class WeatherStation
{
private static string HOST = "localhost";
private static int PORT = 4223;
private static IPConnection ipcon = null;
private static BrickletLCD20x4 brickletLCD = null;
private static BrickletAmbientLight brickletAmbientLight = null;
private static BrickletAmbientLightV2 brickletAmbientLightV2 = null;
private static BrickletAmbientLightV3 brickletAmbientLightV3 = null;
private static BrickletHumidity brickletHumidity = null;
private static BrickletHumidityV2 brickletHumidityV2 = null;
private static BrickletBarometer brickletBarometer = null;
private static BrickletBarometerV2 brickletBarometerV2 = null;
static void IlluminanceCB(BrickletAmbientLight sender, int illuminance)
{
if(brickletLCD != null)
{
string text = string.Format("Illuminanc {0,6:###.00} lx", illuminance / 10.0);
brickletLCD.WriteLine(0, 0, text);
System.Console.WriteLine("Write to line 0: " + text);
}
}
static void IlluminanceV2CB(BrickletAmbientLightV2 sender, long illuminance)
{
if(brickletLCD != null)
{
string text = string.Format("Illumina {0,8:###.00} lx", illuminance / 100.0);
brickletLCD.WriteLine(0, 0, text);
System.Console.WriteLine("Write to line 0: " + text);
}
}
static void IlluminanceV3CB(BrickletAmbientLightV3 sender, long illuminance)
{
if(brickletLCD != null)
{
string text = string.Format("Illumina {0,8:###.00} lx", illuminance / 100.0);
brickletLCD.WriteLine(0, 0, text);
System.Console.WriteLine("Write to line 0: " + text);
}
}
static void HumidityCB(BrickletHumidity sender, int humidity)
{
if(brickletLCD != null)
{
string text = string.Format("Humidity {0,6:###.00} %", humidity / 10.0);
brickletLCD.WriteLine(1, 0, text);
System.Console.WriteLine("Write to line 1: " + text);
}
}
static void HumidityV2CB(BrickletHumidityV2 sender, int humidity)
{
if(brickletLCD != null)
{
string text = string.Format("Humidity {0,6:###.00} %", humidity / 100.0);
brickletLCD.WriteLine(1, 0, text);
System.Console.WriteLine("Write to line 1: " + text);
}
}
static void AirPressureCB(BrickletBarometer sender, int airPressure)
{
if(brickletLCD != null)
{
string text = string.Format("Air Press {0,7:####.00} mb", airPressure / 1000.0);
brickletLCD.WriteLine(2, 0, text);
System.Console.WriteLine("Write to line 2: " + text);
int temperature;
try
{
temperature = sender.GetChipTemperature();
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Could not get temperature: " + e.Message);
return;
}
// 0xDF == ° on LCD 20x4 charset.
text = string.Format("Temperature {0,5:##.00} {1}C", temperature / 100.0, (char)0xDF);
brickletLCD.WriteLine(3, 0, text);
System.Console.WriteLine("Write to line 3: " + text.Replace((char)0xDF, '°'));
}
}
static void AirPressureV2CB(BrickletBarometerV2 sender, int airPressure)
{
if(brickletLCD != null)
{
string text = string.Format("Air Press {0,7:####.00} mb", airPressure / 1000.0);
brickletLCD.WriteLine(2, 0, text);
System.Console.WriteLine("Write to line 2: " + text);
int temperature;
try
{
temperature = sender.GetTemperature();
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Could not get temperature: " + e.Message);
return;
}
// 0xDF == ° on LCD 20x4 charset.
text = string.Format("Temperature {0,5:##.00} {1}C", temperature / 100.0, (char)0xDF);
brickletLCD.WriteLine(3, 0, text);
System.Console.WriteLine("Write to line 3: " + text.Replace((char)0xDF, '°'));
}
}
static void EnumerateCB(IPConnection sender,
string UID,
string connectedUID,
char position,
short[] hardwareVersion,
short[] firmwareVersion,
int deviceIdentifier,
short enumerationType)
{
if(enumerationType == IPConnection.ENUMERATION_TYPE_CONNECTED ||
enumerationType == IPConnection.ENUMERATION_TYPE_AVAILABLE)
{
if(deviceIdentifier == BrickletLCD20x4.DEVICE_IDENTIFIER)
{
try
{
brickletLCD = new BrickletLCD20x4(UID, ipcon);
brickletLCD.ClearDisplay();
brickletLCD.BacklightOn();
System.Console.WriteLine("LCD 20x4 initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("LCD 20x4 init failed: " + e.Message);
brickletLCD = null;
}
}
else if(deviceIdentifier == BrickletAmbientLight.DEVICE_IDENTIFIER)
{
try
{
brickletAmbientLight = new BrickletAmbientLight(UID, ipcon);
brickletAmbientLight.SetIlluminanceCallbackPeriod(1000);
brickletAmbientLight.Illuminance += IlluminanceCB;
System.Console.WriteLine("Ambient Light initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Ambient Light init failed: " + e.Message);
brickletAmbientLight = null;
}
}
else if(deviceIdentifier == BrickletAmbientLightV2.DEVICE_IDENTIFIER)
{
try
{
brickletAmbientLightV2 = new BrickletAmbientLightV2(UID, ipcon);
brickletAmbientLightV2.SetConfiguration(BrickletAmbientLightV2.ILLUMINANCE_RANGE_64000LUX,
BrickletAmbientLightV2.INTEGRATION_TIME_200MS);
brickletAmbientLightV2.SetIlluminanceCallbackPeriod(1000);
brickletAmbientLightV2.Illuminance += IlluminanceV2CB;
System.Console.WriteLine("Ambient Light 2.0 initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Ambient Light 2.0 init failed: " + e.Message);
brickletAmbientLightV2 = null;
}
}
else if(deviceIdentifier == BrickletAmbientLightV3.DEVICE_IDENTIFIER)
{
try
{
brickletAmbientLightV3 = new BrickletAmbientLightV3(UID, ipcon);
brickletAmbientLightV3.SetConfiguration(BrickletAmbientLightV3.ILLUMINANCE_RANGE_64000LUX,
BrickletAmbientLightV3.INTEGRATION_TIME_200MS);
brickletAmbientLightV3.SetIlluminanceCallbackConfiguration(1000, false, 'x', 0, 0);
brickletAmbientLightV3.IlluminanceCallback += IlluminanceV3CB;
System.Console.WriteLine("Ambient Light 3.0 initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Ambient Light 3.0 init failed: " + e.Message);
brickletAmbientLightV3 = null;
}
}
else if(deviceIdentifier == BrickletHumidity.DEVICE_IDENTIFIER)
{
try
{
brickletHumidity = new BrickletHumidity(UID, ipcon);
brickletHumidity.SetHumidityCallbackPeriod(1000);
brickletHumidity.Humidity += HumidityCB;
System.Console.WriteLine("Humidity initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Humidity init failed: " + e.Message);
brickletHumidity = null;
}
}
else if(deviceIdentifier == BrickletHumidityV2.DEVICE_IDENTIFIER)
{
try
{
brickletHumidityV2 = new BrickletHumidityV2(UID, ipcon);
brickletHumidityV2.SetHumidityCallbackConfiguration(1000, true, 'x', 0, 0);
brickletHumidityV2.HumidityCallback += HumidityV2CB;
System.Console.WriteLine("Humidity 2.0 initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Humidity 2.0 init failed: " + e.Message);
brickletHumidityV2 = null;
}
}
else if(deviceIdentifier == BrickletBarometer.DEVICE_IDENTIFIER)
{
try
{
brickletBarometer = new BrickletBarometer(UID, ipcon);
brickletBarometer.SetAirPressureCallbackPeriod(1000);
brickletBarometer.AirPressure += AirPressureCB;
System.Console.WriteLine("Barometer initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Barometer init failed: " + e.Message);
brickletBarometer = null;
}
}
else if(deviceIdentifier == BrickletBarometerV2.DEVICE_IDENTIFIER)
{
try
{
brickletBarometerV2 = new BrickletBarometerV2(UID, ipcon);
brickletBarometerV2.SetAirPressureCallbackConfiguration(1000, false, 'x', 0, 0);
brickletBarometerV2.AirPressureCallback += AirPressureV2CB;
System.Console.WriteLine("Barometer 2.0 initialized");
}
catch(TinkerforgeException e)
{
System.Console.WriteLine("Barometer 2.0 init failed: " + e.Message);
brickletBarometerV2 = null;
}
}
}
}
static void ConnectedCB(IPConnection sender, short connectedReason)
{
if(connectedReason == IPConnection.CONNECT_REASON_AUTO_RECONNECT)
{
System.Console.WriteLine("Auto Reconnect");
while(true)
{
try
{
ipcon.Enumerate();
break;
}
catch(NotConnectedException e)
{
System.Console.WriteLine("Enumeration Error: " + e.Message);
System.Threading.Thread.Sleep(1000);
}
}
}
}
static void Main()
{
ipcon = new IPConnection();
while(true)
{
try
{
ipcon.Connect(HOST, PORT);
break;
}
catch(System.Net.Sockets.SocketException e)
{
System.Console.WriteLine("Connection Error: " + e.Message);
System.Threading.Thread.Sleep(1000);
}
}
ipcon.EnumerateCallback += EnumerateCB;
ipcon.Connected += ConnectedCB;
while(true)
{
try
{
ipcon.Enumerate();
break;
}
catch(NotConnectedException e)
{
System.Console.WriteLine("Enumeration Error: " + e.Message);
System.Threading.Thread.Sleep(1000);
}
}
System.Console.WriteLine("Press enter to exit");
System.Console.ReadLine();
ipcon.Disconnect();
}
}