Skip to content

Instantly share code, notes, and snippets.

@garuma
Created January 15, 2018 23:51
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save garuma/4ac9d21ba26dd81a5bbd231e4a001144 to your computer and use it in GitHub Desktop.
Save garuma/4ac9d21ba26dd81a5bbd231e4a001144 to your computer and use it in GitHub Desktop.
Netduino 3 Wi-Fi OneWire temperature sensor sent over MQTT
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
using System.Threading;
using System.IO;
using System.Net;
using SecretLabs.NETMF.Hardware.Netduino;
using Microsoft.SPOT.Net.NetworkInformation;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Utility;
using MqttTrace = uPLibrary.Networking.M2Mqtt.Utility.Trace;
namespace NetduinoBlink
{
public class Program
{
const string MqttUsername = "...";
const string MqttPassword = "...";
const string MqttTopic = "home/room/temperature";
const string MqttIP = "192.168.x.x";
static readonly byte[] SensorSerialNumber = new byte[8];
static readonly byte[] MatchRomCommand = new byte[9];
public static void Main()
{
Debug.Print ("Application starting...");
var port = new OutputPort (Pins.GPIO_PIN_D7, false);
var oneWire = new OneWire (port);
var utf8Encoding = System.Text.Encoding.UTF8;
if (!EnsureConnectedToNetwork ()) {
Debug.Print ("Couldn't connect to network, bye.");
return;
}
MqttTrace.TraceLevel = TraceLevel.Error | TraceLevel.Frame | TraceLevel.Queuing | TraceLevel.Information | TraceLevel.Verbose | TraceLevel.Warning;
MqttTrace.TraceListener = (format, args) => Debug.Print (format);
MqttClient client = null;
try {
client = new MqttClient (MqttIP, 8887, false, null, null, MqttSslProtocols.None);
if (client.Connect ("netduino", MqttUsername, MqttPassword) != 0) {
Debug.Print ("Couldn't connect to MQTT broker");
return;
}
} catch (Exception ex) {
Debug.Print ("Error while connecting to MQTT");
Debug.Print (ex.ToString ());
return;
}
Debug.Print ("MQTT connected");
while (true) {
try {
var temp = ReadTemperature (oneWire);
Debug.Print ("Current temperature is in C: " + temp);
try {
var shortTemp = temp.ToString ("F2");
client.Publish (MqttTopic, utf8Encoding.GetBytes (shortTemp));
} catch (Exception e) {
Debug.Print ("Couldn't send temp update to MQTT");
Debug.Print (e.ToString ());
}
} catch (Exception e) {
Debug.Print ("A random exception happened");
Debug.Print (e.ToString ());
break;
} finally {
oneWire.Release ();
}
Thread.Sleep (20000);
}
if (client.IsConnected)
client.Disconnect ();
}
static float ReadTemperature (OneWire oneWire)
{
try {
oneWire.AcquireEx ();
var firstDevice = oneWire.FindFirstDevice (performResetBeforeSearch: true,
searchWithAlarmCommand: false);
Debug.Print ("First device id: " + firstDevice);
oneWire.SerialNum (SensorSerialNumber, true);
Array.Copy (SensorSerialNumber, 0, MatchRomCommand, 1, 8);
PrintSerial (SensorSerialNumber);
oneWire.TouchReset ();
oneWire.WriteByte (0xCC /* SKIP ROM */);
oneWire.WriteByte (0x44 /* ConvertT */);
Thread.Sleep (750);
oneWire.TouchReset ();
MatchRomCommand[0] = 0x55 /* MATCH ROM */;
for (int j = 0; j < MatchRomCommand.Length; j++)
oneWire.WriteByte (MatchRomCommand[j]);
oneWire.WriteByte (0xBE /* Read Scratchpad */);
var tempLo = (byte)oneWire.ReadByte ();
var tempHi = (byte)oneWire.ReadByte ();
var temp = ConvertTemperature (tempLo, tempHi);
return temp;
} finally {
oneWire.Release ();
}
}
static float ConvertTemperature (byte tempLo, byte tempHi)
{
return ((short)((tempHi << 8) | tempLo)) / 16F;
}
static void PrintSerial (byte[] serial)
{
string output = "{";
for (int i = 0; i < serial.Length; i++)
output += serial[i].ToString ();
output += "}";
Debug.Print (output);
}
static bool EnsureConnectedToNetwork ()
{
var interfaces = NetworkInterface.GetAllNetworkInterfaces ();
Debug.Print ("Found interface count: " + interfaces.Length);
if (interfaces.Length == 0)
return false;
var iface = interfaces[0];
if (HasDefaultIp (iface)) {
if (!iface.IsDhcpEnabled) {
Debug.Print ("No IP and no DHCP");
return false;
}
Debug.Print ("Trying to get an IP address");
for (int tries = 0; tries < 100; tries++) {
Thread.Sleep (100);
if (!HasDefaultIp (iface))
break;
}
if (HasDefaultIp (iface)) {
Debug.Print ("Still no IP");
return false;
}
}
Debug.Print ("Got an IP: " + iface.IPAddress);
return true;
}
static bool HasDefaultIp (NetworkInterface iface) => string.Equals (iface.IPAddress, "0.0.0.0");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment