using System;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.Devices.SerialCommunication;
using Windows.Storage.Streams;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using Microsoft.Azure.Devices.Client;
using System.Text;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=402352&clcid=0x409
namespace HeaterSerial
{
///
/// An empty page that can be used on its own or navigated to within a Frame.
///
public sealed partial class MainPage : Page
{
string iotHubUri = ".azure-devices.net"; // ! put in value !
string deviceId = ""; // ! put in value !
string deviceKey = ""; // ! put in value !
bool updatestatus = false;
private SerialDevice serialPort = null;
DataWriter dataWriteObject = null;
DataReader dataReaderObject = null;
string rcvdText = "";
List Datalist = new List();
string lastupdate = "";
public MainPage()
{
this.InitializeComponent();
startread();
StartXR();
}
private async Task StartXR()
{
while (true)
{
await Task.Delay(TimeSpan.FromSeconds(60));
global::System.Diagnostics.Debug.WriteLine("StartXR");
if (dataWriteObject == null)
{dataWriteObject = new DataWriter(serialPort.OutputStream);}
Task storeAsyncTask;
dataWriteObject.WriteString("XR" + "\r" + (Char)13 );
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
Datalist.Clear();
updatestatus = true;
UInt32 bytesWritten = await storeAsyncTask;
}
}
private async Task ReadAsync()
{
try
{
var deviceClient = DeviceClient.Create(iotHubUri,
AuthenticationMethodFactory.
CreateAuthenticationWithRegistrySymmetricKey(deviceId, deviceKey),
TransportType.Http1);
Task loadAsyncTask;
uint ReadBufferLength = 10;
// If task cancellation was requested, comply
// cancellationToken.ThrowIfCancellationRequested();
// Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
// Create a task object to wait for data on the serialPort.InputStream
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask();
// Launch the task and wait
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
rcvdText = dataReaderObject.ReadString(bytesRead);
rcvdText = rcvdText.Trim();
global::System.Diagnostics.Debug.WriteLine("-" + rcvdText.ToString() + "-");
global::System.Diagnostics.Debug.WriteLine("-" + rcvdText.Length + "-");
if (rcvdText.Length == 10 && updatestatus == true)
{
string datatoadd = rcvdText + "," + HexStringToInt(rcvdText.Substring(6)) + "," + strsensor(rcvdText.ToString());
global::System.Diagnostics.Debug.WriteLine(datatoadd);
Datalist.Add(lastupdate + "," + datatoadd);
DateTime timestamp = DateTime.Now;
string strtime = timestamp.ToString("yyyy-MM-dd HH:mm:ss");
string message = "";
string[] row = null;
string rowvalue = "";
string rowdate = "";
string rowsensor = "";
DateTime localDate = DateTime.Now;
if (Datalist.Count == 26)
{
updatestatus = false;
global::System.Diagnostics.Debug.WriteLine("StopXR");
if (dataWriteObject == null)
{ dataWriteObject = new DataWriter(serialPort.OutputStream); }
Task storeAsyncTask;
dataWriteObject.WriteString("XA" + "\r\n");
storeAsyncTask = dataWriteObject.StoreAsync().AsTask();
Datalist.ForEach(delegate (String item)
{
row = item.Split(',');
rowdate = row[0];
rowvalue = row[2];
rowsensor = row[3];
message = message + ",\"" + rowsensor + "\":" + rowvalue;
});
message = message.Remove(0, 2);
message = message.Insert(0, "\"timestamp\":" + "\"" + strtime + "\",\"deviceId\":\"raspberry01\",\"");
message = message.Insert(0, "{ ");
message += "}";
global::System.Diagnostics.Debug.WriteLine(message);
var interactiveMessage = new Message(Encoding.ASCII.GetBytes(message));
interactiveMessage.Properties["messageType"] = "interactive";
interactiveMessage.MessageId = Guid.NewGuid().ToString();
await deviceClient.SendEventAsync(interactiveMessage);
message = null;
}
}
}
// status.Text = "bytes read successfully!";
}
catch (Exception)
{ global::System.Diagnostics.Debug.WriteLine("Error in Async"); }
}
private async void Listen()
{
try
{
if (serialPort != null)
{
// global::System.Diagnostics.Debug.WriteLine("hej");
dataReaderObject = new DataReader(serialPort.InputStream);
// keep reading the serial input
while (true)
{
await ReadAsync();
}
}
}
catch (Exception ex)
{
if (ex.GetType().Name == "TaskCanceledException")
{
//status.Text = "Reading task was cancelled, closing device and cleaning up";
//CloseDevice();
global::System.Diagnostics.Debug.WriteLine(ex.Message);
}
else
{
//status.Text = ex.Message;
}
}
finally
{
// Cleanup once complete
if (dataReaderObject != null)
{
dataReaderObject.DetachStream();
dataReaderObject = null;
}
}
}
private async void startread()
{
try
{
ushort vid = 0x10C4;
ushort pid = 0xEA60;
string aqs = SerialDevice.GetDeviceSelectorFromUsbVidPid(vid, pid);
var myDevices = await Windows.Devices.Enumeration.DeviceInformation.FindAllAsync(aqs, null);
string id = myDevices[0].Id;
await Task.Delay(10);
serialPort = await SerialDevice.FromIdAsync(id);
// Configure serial settings
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(100);
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(100);
serialPort.BaudRate = 19200;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
Listen();
}
catch (Exception )
{
// status.Text = ex.Message;
// sendTextButton.IsEnabled = false;
global::System.Diagnostics.Debug.WriteLine("error in startread");
}
}
private static string strsensor(String sensordata)
{
switch (sensordata.Substring(0, 6))
{
case "XR0001":
return "rad_return";
case "XR0002":
return "rad_forward";
case "XR0003":
return "heatcarrier_return";
case "XR0004":
return "heatcarrier_forward";
case "XR0005":
return "brine_in";
case "XR0006":
return "brine out";
case "XR0007":
return "outdoor";
case "XR0008":
return "indoor";
case "XR0009":
return "Hot_water_1_Top";
case "XR000A":
return "Hot_water_2_Mid";
case "XR000B":
return "Hot_gas_Compr";
case "XR1A01":
return "Compressor_is";
case "XR1A02":
return "Add_Heat_1";
case "XR1A03":
return "Add_heat_2";
case "XR1A04":
return "Pump_Cold_circuit";
case "XR1A05":
return "Pump_Heat_circuit";
case "XR1A06":
return "Pump_Radiator";
case "XR1A07":
return "Switch_Valve";
case "XR1A20":
return "Alarm";
case "XR3104":
return "Add_heat_status";
case "XR0107":
return "Heating_setpoint";
case "XR0111":
return "Warm_water_setpoint";
case "XR0203":
return "Room_temp_setpoint";
case "XR2204":
return "Room_sensor_influence";
case "XR2205":
return "Heat_set_1_CurveL";
case "XR0207":
return "Heat_set_3_Parallel";
default:
return "Undetermined";
}
}
private static string HexStringToInt(String hexdata)
{
string op = hexdata.Substring(0, 1);
string a = hexdata.Substring(0, 2);
string b = hexdata.Substring(2);
if (op == "F")
{
double decValue = ((Convert.ToInt32(a, 16) * 256) + Convert.ToInt32(b, 16) - 65536);
decValue = decValue / 10;
return Convert.ToString(decValue);
}
else
{
double decValue = Convert.ToInt32(hexdata, 16);
decValue = decValue / 10;
return Convert.ToString(decValue);
}
}
}
}