I would like to send some heart rate values I receive from a Microsoft Band from a UWP app to Unity. I have currently a working Tcp Server in Unity but I could not seem to use System.Net.Sockets in UWP. Anyone knows how to make a tcp client on the UWP app and send the data to Unity?
My server code is as follows:
using UnityEngine;
using System.Collections;
using System.Net.Sockets;
using System.IO;
using System.Net;
using System.Threading;
public class Server {
public static TcpListener listener;
public static Socket soc;
public static NetworkStream s;
public void StartService () {
listener = new TcpListener (15579);
listener.Start ();
for(int i = 0;i < 1;i++){
Thread t = new Thread(new ThreadStart(Service));
t.Start();
}
}
void Service () {
while (true)
{
soc = listener.AcceptSocket ();
s = new NetworkStream (soc);
StreamReader sr = new StreamReader (s);
StreamWriter sw = new StreamWriter (s);
sw.AutoFlush = true;
while(true)
{
string heartrate = sr.ReadLine ();
if(heartrate != null)
{
HeartRateController.CurrentHeartRate = int.Parse(heartrate);
Debug.Log(HeartRateController.CurrentHeartRate);
}
else if (heartrate == null)
{
break;
}
}
s.Close();
}
}
void OnApplicationQuit()
{
Debug.Log ("END");
listener.Stop ();
s.Close();
soc.Close();
}
}
My UWP code is as follows:
public IBandInfo[] pairedBands;
public IBandClient bandClient;
public IBandHeartRateReading heartreading;
public MainPage()
{
this.InitializeComponent();
ConnectWithBand();
}
public async void ConnectWithBand()
{
pairedBands = await BandClientManager.Instance.GetBandsAsync();
try
{
if (pairedBands.Length > 0)
{
bandClient = await BandClientManager.Instance.ConnectAsync(pairedBands[0]);
}
else
{
return;
}
}
catch (BandException ex)
{
textBlock.Text = ex.Message;
}
GetHeartRate();
}
public async void GetHeartRate()
{
IEnumerable<TimeSpan> supportedHeartBeatReportingIntervals = bandClient.SensorManager.HeartRate.SupportedReportingIntervals;
bandClient.SensorManager.HeartRate.ReportingInterval = supportedHeartBeatReportingIntervals.First<TimeSpan>();
bandClient.SensorManager.HeartRate.ReadingChanged += this.OnHeartRateChanged;
try
{
await bandClient.SensorManager.HeartRate.StartReadingsAsync();
}
catch (BandException ex)
{
throw ex;
}
Window.Current.Closed += async (ss, ee) =>
{
try
{
await bandClient.SensorManager.HeartRate.StopReadingsAsync();
}
catch (BandException ex)
{
// handle a Band connection exception
throw ex;
}
};
}
private async void OnHeartRateChanged(object sender, BandSensorReadingEventArgs<IBandHeartRateReading> e)
{
var hR = e.SensorReading.HeartRate;
await textBlock.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =>
{
textBlock.Text = hR.ToString();
});
}