I'm working on a Project (Console-Application .NET Framework 4.7.2 c#) to find nearby BLE devices and it's working well, the device(The device is just an Arduino with a BLE shield.) is discovered and i was able to read values from it. so the problem is that i wanted to do the same but on another PC (Same Code, Conditions, everything the same). it showed me that the pc is with the device connected but unreachable here on this place of the code :
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
So i tried again and again on 3 different PCs and Laptops but it didn't work.
On the pc first i got connected to, it works well without problems. Can someone pls help me and say what is the matter. Here is my Code:
namespace QuickBlueToothLE
{
class Program
{
static public readonly Dictionary<string, DeviceInformation> mDiscoveredDevices = new Dictionary<string, DeviceInformation>();
static DeviceInformation device = null;
public static string HEG_Service_ID = "00001826-0000-1000-8000-00805f9b34fb";
public static DeviceWatcher deviceWatcher = null;
// Abfrage nach zusätzlichen Eigenschaften, die zurückgegeben werden sollen
public static string[] requestedProperties =
{
"System.Devices.Aep.DeviceAddress",
"System.Devices.Aep.IsConnected",
"System.Devices.Aep.Bluetooth.Le.IsConnectable"
};
static async Task Main(string[] args)
{
deviceWatcher = DeviceInformation.CreateWatcher
(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompletedAsync;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
while (true)
{
if (device == null)
Thread.Sleep(2000);
else
{
Console.WriteLine("Press Any Key to connect to HEG-900725");
Console.ReadKey();
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
Console.WriteLine("Attempting to connect with device");
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
var services = result.Services;
if (result.Status == GattCommunicationStatus.Success)
{
Console.WriteLine("Connection succeeded" + " "+ bluetoothLeDevice.DeviceInformation.Pairing.IsPaired);
Console.WriteLine(device.Id);
foreach (var service in services)
{
if (service.Uuid.ToString() == HEG_Service_ID)
{
Console.WriteLine("Found Heg Service");
GattCharacteristicsResult charactiristicResult = await service.GetCharacteristicsAsync();
if (charactiristicResult.Status == GattCommunicationStatus.Success)
{
var characteristics = charactiristicResult.Characteristics;
foreach (var characteristic in characteristics)
{
Console.WriteLine("---------------");
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
Console.WriteLine("CharactesticHandle:"+characteristic.AttributeHandle +"\r\n"+"UUID"+characteristic.Uuid);
if (properties.HasFlag(GattCharacteristicProperties.Notify))
{
Console.WriteLine("Notify poroperty found");
GattCommunicationStatus status =
await characteristic.WriteClientCharacteristicConfigurationDescriptorAsync(
GattClientCharacteristicConfigurationDescriptorValue.Notify);
if (status == GattCommunicationStatus.Success)
{
characteristic.ValueChanged += Characteristic_ValueChanged;
// Server has been informed of clients interest.
}
}
}
}
}
}
}
Console.WriteLine("Press Any Key to Exit application");
Console.WriteLine("\r\n" + "Values" + "\r\n");
Console.ReadKey();
foreach (var service in services)
{
service.Dispose();
}
bluetoothLeDevice.Dispose();
bluetoothLeDevice = null;
device = null;
Console.WriteLine(mDiscoveredDevices);
Console.WriteLine(mDiscoveredDevices.Count());
break;
}
}
Console.ReadKey();
deviceWatcher.Stop();
deviceWatcher = null;
}
private static void TXCharacteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
byte[] buffer = args.CharacteristicValue.ToArray();
}
private static void Characteristic_ValueChanged(GattCharacteristic sender, GattValueChangedEventArgs args)
{
var reader = DataReader.FromBuffer(args.CharacteristicValue);
var flags = reader.ReadByte();
var value = reader.ReadByte();
Console.WriteLine($"{flags} - {value}");
}
private static void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
}
private static void DeviceWatcher_EnumerationCompletedAsync(DeviceWatcher sender, object args)
{
}
private static void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate args)
{
}
private static void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate args)
{
//throw new NotImplementedException();
}
private static void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation args)
{
Console.WriteLine(args.Name);
if (args.Name == "HEG_100053" || args.Name =="Arduino")
{
Console.WriteLine("Found: " + args.Name);
device = args;
bool keyExists = mDiscoveredDevices.ContainsKey(device.Id);
if (!keyExists)
{
mDiscoveredDevices.Add(device.Id, device);
}
}
}
//900725
//|| args.Name == "HEG_100053"
}
}
Related
I want to make call with sip using Ozeki library.
But this library throws me state excepton.
I use asteriks telephony in the server.
My code is below:
class Program
{
static ISoftPhone softphone; // softphone object
static IPhoneLine phoneLine; // phoneline object
static IPhoneCall call;
static Microphone microphone;
static Speaker speaker;
static MediaConnector connector;
static PhoneCallAudioSender mediaSender;
static PhoneCallAudioReceiver mediaReceiver;
public static void Main(string[] args)
{
// Create a softphone object with RTP port range 5000-10000
softphone = SoftPhoneFactory.CreateSoftPhone(1, 10000);
// SIP account registration data, (supplied by your VoIP service provider)
var registrationRequired = true;
var userName = "111";
var displayName = "111";
var authenticationId = "111";
var registerPassword = "pin111";
var domainHost = "localhost";
var domainPort = 5038;
var account = new SIPAccount(registrationRequired, displayName, userName, authenticationId, registerPassword, domainHost, domainPort);
// Send SIP regitration request
RegisterAccount(account);
microphone = Microphone.GetDefaultDevice();
speaker = Speaker.GetDefaultDevice();
mediaSender = new PhoneCallAudioSender();
mediaReceiver = new PhoneCallAudioReceiver();
connector = new MediaConnector();
// Prevents the termination of the application
Console.WriteLine("\nDone");
Console.ReadLine();
}
static void RegisterAccount(SIPAccount account)
{
try
{
phoneLine = softphone.CreatePhoneLine(account);
phoneLine.RegistrationStateChanged += line_RegStateChanged;
softphone.RegisterPhoneLine(phoneLine);
}
catch (Exception ex)
{
Console.WriteLine("Error during SIP registration: " + ex);
}
}
static void line_RegStateChanged(object sender, RegistrationStateChangedArgs e)
{
if (e.State == RegState.NotRegistered || e.State == RegState.Error)
Console.WriteLine("Registration failed!");
if (e.State == RegState.RegistrationSucceeded)
{
Console.WriteLine("Registration succeeded - Online!");
CreateCall();
}
}
private static void CreateCall()
{
var numberToDial = "00994122000020";
call = softphone.CreateCallObject(phoneLine, numberToDial);
call.CallStateChanged += call_CallStateChanged;
call.Start();
}
private static void SetupDevices()
{
connector.Connect(microphone, mediaSender);
connector.Connect(mediaReceiver, speaker);
mediaSender.AttachToCall(call);
mediaReceiver.AttachToCall(call);
microphone.Start();
speaker.Start();
}
static void call_CallStateChanged(object sender, CallStateChangedArgs e)
{
Console.WriteLine("Call state: {0}.", e.State);
if (e.State == CallState.Answered)
SetupDevices();
}
}
This code show me this error message:
Registration succeeded - Online!
Call state: Setup.
Call state: Error.
What is the problem? What must I chane for working this code?
P.S Please, If you know the better library for making call with asteriks you can tell me.
I am able to pair a Bluetooth skincare device to my PC using a C# app that I wrote.
Definition:
//Device Data
BluetoothLEDevice bluetoothLeDevice;
DeviceData deviceData=new DeviceData();
GattDeviceServicesResult result;
static DeviceInformation device = null;
The handlers that reads devices, implemented in MainForm():
// Query for extra properties you want returned
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
DeviceWatcher deviceWatcher =
DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
// Added, Updated and Removed are required to get all nearby devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
// EnumerationCompleted and Stopped are optional to implement.
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start the watcher.
deviceWatcher.Start();
The code that pairs the device with a click of a button:
private async void btnPair_Click(object sender, EventArgs e)
{
feedbackTB.AppendText("Waiting for pairing..." + Environment.NewLine);
if (device == null)
{
statusBox.Text = "Please, make sure the device is on, and try again. Uncover the device and it will automatically turn on.";
feedbackTB.AppendText("Timed out." + Environment.NewLine);
Thread.Sleep(200);
}
else
{
try
{
hydrationFqList = new List<int>();
psList = new List<int>();
bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(device.Id);
statusBox.Text = "Attempting to pair with device";
result = await bluetoothLeDevice.GetGattServicesAsync();
if (result.Status == GattCommunicationStatus.Success)
{
statusBox.Text = "Pairing succeeded";
feedbackTB.AppendText("Device paired." + Environment.NewLine);
var services = result.Services;
foreach (var service in services)
{
if (service.Uuid.ToString() == deviceData.devInfoSvc)
{
GattCharacteristicsResult charactiristicResult = await service.GetCharacteristicsAsync();
feedbackTB.AppendText("Skimming device info service... " + Environment.NewLine);
if (charactiristicResult.Status == GattCommunicationStatus.Success)
{
feedbackTB.AppendText("Reading device info... " + Environment.NewLine);
var characteristics = charactiristicResult.Characteristics;
foreach (var characteristic in characteristics)
{
GattCharacteristicProperties properties = characteristic.CharacteristicProperties;
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
GattReadResult rResult = await characteristic.ReadValueAsync();
var reader = DataReader.FromBuffer(rResult.Value);
byte[] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(input);
string data = Encoding.ASCII.GetString(input);
if (characteristic.Uuid.ToString() == deviceData.mfgNameCt)
{
mfgNameTB.Text = data;
}
if (characteristic.Uuid.ToString() == deviceData.modelNumCt)
{
modelNumTB.Text = data;
}
if (characteristic.Uuid.ToString() == deviceData.serialNumCt)
{
serialNumber = data;
snTB.Text = serialNumber;
}
if (characteristic.Uuid.ToString() == deviceData.macAddrCt)
{
macAddress = data;
macAddrTB.Text = macAddress;
}
if (characteristic.Uuid.ToString() == deviceData.hwRevCt)
{
hwRevisionTB.Text = data;
}
if (characteristic.Uuid.ToString() == deviceData.fwRevCt)
{
fwRevisionTB.Text = data;
}
}
statusBox.Text = "Press and hold device against your skin to start scan.";
}
}
}
}
}
else
{
statusBox.Text = "Please, make sure the device is connected, and try again.";
feedbackTB.AppendText("Timed out." + Environment.NewLine);
}
feedbackTB.AppendText("Number of run(s):" + increment + Environment.NewLine);
}
catch (Exception err)
{
ErrorWindow eWindow = new ErrorWindow();
eWindow.label4.Text = err.GetType().ToString();
eWindow.errorDetails.Text = err.Message;
eWindow.ShowDialog();
}
}
}
And this is my newly implemented disconnect button:
private void btnDisconnect _Click(object sender, EventArgs e)
{
bluetoothLeDevice.Dispose();
}
Now we get to the issue.
When the device is on, a blue light is suppose to flash.
When the device is paired to a PC or app, the blue light will stay on.
I expect the device to disconnect when the button is clicked. Upon the click, the light will start flashing again when it's just turned on.
But upon clicking on the button, nothing happened. The device is still stuck connected.
How can I fix this?
I have a C# Class Library, that reads Bluetooth LE Characteristics. I want to use this DLL to get the read values in my VB6 app.
My Problem is: I need the complete code to get the result. That means i have to call the main function from my VB6 program, but i have no idea what parameters i have to use and how i can get the right return value.
My Dll:
using SDKTemplate;
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Windows.Devices.Bluetooth;
using Windows.Devices.Bluetooth.GenericAttributeProfile;
using Windows.Devices.Enumeration;
using Windows.Storage.Streams;
using System.Threading.Tasks;
using System.Runtime.Remoting.Messaging;
using System.Runtime.InteropServices;
namespace BleSirLo
{
public class Program
{
public byte[] ret = new byte[6];
static void Main(string[] args)
{
Task t = MainAsync(args);
t.Wait();
// or, if you want to avoid exceptions being wrapped into AggregateException:
// MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync(string[] args)
{
Program p = new Program();
p.StartBleDeviceWatcher();
}
private List<DeviceInformation> UnknownDevices = new List<DeviceInformation>();
private List<DeviceInformation> _knownDevices = new List<DeviceInformation>();
private IReadOnlyList<GattCharacteristic> characteristics;
private IReadOnlyList<GattDeviceService> services;
private GattDeviceService currentSelectedService = null;
private GattCharacteristic currentSelectedCharacteristic = null;
private DeviceWatcher deviceWatcher;
public bool done = false;
private void StartBleDeviceWatcher()
{
// Additional properties we would like about the device.
// Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx
string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" };
// BT_Code: Example showing paired and non-paired in a single query.
string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")";
deviceWatcher =
DeviceInformation.CreateWatcher(
aqsAllBluetoothLEDevices,
requestedProperties,
DeviceInformationKind.AssociationEndpoint);
// Register event handlers before starting the watcher.
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Removed += DeviceWatcher_Removed;
deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted;
deviceWatcher.Stopped += DeviceWatcher_Stopped;
// Start over with an empty collection.
_knownDevices.Clear();
//deviceWatcher.Stop();
deviceWatcher.Start();
while(true)
if (done == true)
break;
}
private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo)
{
//Debug.WriteLine(String.Format("Device Found!" + Environment.NewLine + "ID:{0}" + Environment.NewLine + "Name:{1}", deviceInfo.Id, deviceInfo.Name));
//notify user for every device that is found
if (sender == deviceWatcher)
{
if ((deviceInfo.Name == "Ei Gude, wie?") || (deviceInfo.Name == "Ei Gude, Wie?"))
{
sender.Stop();
ConnectDevice(deviceInfo);
}
}
}
private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfo)
{
}
private void DeviceWatcher_Removed(DeviceWatcher sender, DeviceInformationUpdate deviceInfo)
{
}
private void DeviceWatcher_EnumerationCompleted(DeviceWatcher sender, object args)
{
}
private void DeviceWatcher_Stopped(DeviceWatcher sender, object args)
{
}
//trigger StartBleDeviceWatcher() to start bluetoothLe Operation
private void Scan()
{
//empty devices list
_knownDevices.Clear();
UnknownDevices.Clear();
//finally, start scanning
StartBleDeviceWatcher();
}
private async void ConnectDevice(DeviceInformation deviceInfo)
{
//get bluetooth device information
BluetoothLEDevice bluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id);
//Respond(bluetoothLeDevice.ConnectionStatus.ToString());
//get its services
GattDeviceServicesResult result = await bluetoothLeDevice.GetGattServicesAsync();
//verify if getting success
if (result.Status == GattCommunicationStatus.Success)
{
//store device services to list
services = result.Services;
//loop each services in list
foreach (var serv in services)
{
//get serviceName by converting the service UUID
string ServiceName = Utilities.ConvertUuidToShortId(serv.Uuid).ToString();
//if current servicename matches the input service name
if (ServiceName == "65520") //ServiceTxtBox.Text)
{
//store the current service
currentSelectedService = serv;
//get the current service characteristics
GattCharacteristicsResult resultCharacterics = await serv.GetCharacteristicsAsync();
//verify if getting characteristics is success
if (resultCharacterics.Status == GattCommunicationStatus.Success)
{
//store device services to list
characteristics = resultCharacterics.Characteristics;
//loop through its characteristics
foreach (var chara in characteristics)
{
//get CharacteristicName by converting the current characteristic UUID
string CharacteristicName = Utilities.ConvertUuidToShortId(chara.Uuid).ToString();
//if current CharacteristicName matches the input characteristic name
if (CharacteristicName == "65524")//CharacteristicsTxtBox.Text)
{
//store the current characteristic
currentSelectedCharacteristic = chara;
//stop method execution
readBuffer();
return;
}
}
}
}
}
}
}
//function that handles the read button event
private async void readBuffer()
{
{
if (currentSelectedService != null && currentSelectedCharacteristic != null)
{
GattCharacteristicProperties properties = currentSelectedCharacteristic.CharacteristicProperties;
//if selected characteristics has read property
if (properties.HasFlag(GattCharacteristicProperties.Read))
{
//read value asynchronously
GattReadResult result = await currentSelectedCharacteristic.ReadValueAsync();
if (result.Status == GattCommunicationStatus.Success)
{
int a, b, c, d, e, f;
var reader = DataReader.FromBuffer(result.Value);
//byte [] input = new byte[reader.UnconsumedBufferLength];
reader.ReadBytes(ret);
a = ret[0];
b = ret[1];
c = ret[2];
d = ret[3];
e = ret[4];
f = ret[5];
Ret_val(ret);
}
}
}
}
}
private void Response_TextChanged(object sender, EventArgs e)
{
}
}
In my VB6 program I call the Library like this: (It is obviously not working, but i dont know how i should do it.
Dim WithEvents CSharpInteropServiceEvents As CSharpInteropService.LibraryInvoke
Dim load As New LibraryInvokeparam(0) = Me.hwnd
Dim sa as variant
Set CSharpInteropServiceEvents = load
sa = load.GenericInvoke("C:\Program Files (x86)\Microsoft Visual Studio\VB98\WINCOM\BleSirLo.dll", "BleSirLo.Program", "Main", param)
so what im actually trying to do is to comunicate with a DMX-Interface pluged to a PC/Host via an Xamarin Android App.
Allready got my Server running, works also with an console client i wrote first. So now I wrote the app,using the same Way as before, with a TCPClient and then writing the data via a stream.
Because I'm running the app in the emulator I use as IP 10.0.2.2 to connect, but I cannot establish a connection. The App crashes or I get a timeout exeption. Been trying and researching now for two days and now i'm desperate, so I attach my code here, hope anyone can help
Thanks, Johannes
App:
public class MainActivity : Activity
{
public Stream Stream;
TcpClient Client = null;
protected override void OnCreate(Bundle bundle)
{
base.OnCreate(bundle);
SetContentView(Resource.Layout.Main);
//adding control elements from Resource.Layout.Main
Button at = FindViewById<Button>(Resource.Id.at);
Button enter = FindViewById<Button>(Resource.Id.enter);
Button thru = FindViewById<Button>(Resource.Id.thru);
Button all = FindViewById<Button>(Resource.Id.all);
Button one = FindViewById<Button>(Resource.Id.one);
Button two = FindViewById<Button>(Resource.Id.two);
Button three = FindViewById<Button>(Resource.Id.three);
Button four = FindViewById<Button>(Resource.Id.four);
Button five = FindViewById<Button>(Resource.Id.five);
Button six = FindViewById<Button>(Resource.Id.six);
Button seven = FindViewById<Button>(Resource.Id.seven);
Button eight = FindViewById<Button>(Resource.Id.eight);
Button nine = FindViewById<Button>(Resource.Id.nine);
Button zero = FindViewById<Button>(Resource.Id.zero);
Button comma = FindViewById<Button>(Resource.Id.comma);
Button connect = FindViewById<Button>(Resource.Id.connect);
Button clear = FindViewById<Button>(Resource.Id.clear);
at.Click += (o, e) =>
{
UpdateCmdLine("#");
};
clear.Click += (o, e) =>
{
FlushCmdLine();
};
enter.Click += (o, e) =>
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
ProcessData(cmdLine.Text);
FlushCmdLine();
};
thru.Click += (o, e) =>
{
UpdateCmdLine("/");
};
all.Click += (o, e) =>
{
UpdateCmdLine("#");
};
one.Click += (o, e) =>
{
UpdateCmdLine("1");
};
two.Click += (o, e) =>
{
UpdateCmdLine("2");
};
three.Click += (o, e) =>
{
UpdateCmdLine("3");
};
four.Click += (o, e) =>
{
UpdateCmdLine("4");
};
five.Click += (o, e) =>
{
UpdateCmdLine("5");
};
six.Click += (o, e) =>
{
UpdateCmdLine("6");
};
seven.Click += (o, e) =>
{
UpdateCmdLine("7");
};
eight.Click += (o, e) =>
{
UpdateCmdLine("8");
};
nine.Click += (o, e) =>
{
UpdateCmdLine("9");
};
zero.Click += (o, e) =>
{
UpdateCmdLine("0");
};
comma.Click += (o, e) =>
{
UpdateCmdLine(",");
};
connect.Click += (o, e) =>
{
try
{
TextView ip = FindViewById<TextView>(Resource.Id.ipField);
TextView port = FindViewById<TextView>(Resource.Id.portField);
TextView connectionStatus = FindViewById<TextView>(Resource.Id.connectedStatus);
Client = new TcpClient("10.0.2.2", 4711);
connectionStatus.Text = "Connected";
}
catch (System.Exception)
{
}
};
//implementing click functions
}
public void UpdateCmdLine(string update)
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
cmdLine.Text += update;
}
public void FlushCmdLine()
{
TextView cmdLine = FindViewById<TextView>(Resource.Id.cmdLine);
cmdLine.Text = "";
}
public int[] GetData(string channel, string value)
{
int[] data = new int[] {Int32.Parse(channel), Int32.Parse(value)};
return data;
}
public void SendData(int channel, int data)
{
if (Client.Connected)
{
Stream = Client.GetStream();
byte[] outgoingBytes = new byte[] {Convert.ToByte(channel),Convert.ToByte(data)};
Stream.Write(outgoingBytes,0,outgoingBytes.Length);
}
}
public void ProcessData(string cmdLine)
{
string[] divideStackedOps = cmdLine.Split(',');
foreach (string s in divideStackedOps)
{
if (s.Contains("/"))
{
string[] dividedThru = s.Split('/');
int channel1 = Int32.Parse(dividedThru[0]);
string[] dividedAt = dividedThru[1].Split('#');
int channel2 = Int32.Parse(dividedAt[0]);
int value = Int32.Parse(dividedAt[1]);
for (int e = channel2; e >= channel1; e--)
{
SendData(e, value);
}
}
else if (s.Contains("#"))
{
string[]dividedAll = s.Split('#');
int value = Int32.Parse(dividedAll[1]);
for (int e = 100; e > 0; e--)
{
SendData(e, value);
}
}
}
}
}
}
Server
public class DmxInterface
{
[DllImport("K8062D.dll")]
public static extern void StartDevice();
[DllImport("K8062D.dll")]
public static extern void SetData(int channel, int data);
[DllImport("K8062D.dll")]
public static extern void StopDevice();
[DllImport("K8062D.dll")]
public static extern void SetChannelCount(int count);
}
class Program
{
private static TcpListener Listener;
private static ArrayList Threads = new ArrayList();
public static Boolean ServerStopped;
public static void Main()
{
DmxInterface.StartDevice();
DmxInterface.SetChannelCount(10);
//Initialize Listener, start Listener
int port = 4711;
IPAddress ip = IPAddress.Parse("127.0.0.1");
Listener = new TcpListener(ip, port);
Listener.Start();
Console.WriteLine("Creating new listener on: "+ip+":"+port);
//Initialize MainServerThread, start MainServerThread
Console.WriteLine("Starting MainThread");
Thread mainThread = new Thread(Run);
mainThread.Start();
Console.WriteLine("Done");
while (!ServerStopped)
{
Console.WriteLine("Write 'stop' to stop Server...");
String cmd = "";
cmd = Console.ReadLine();
if (cmd.ToLower().Equals("stop"))
{
Console.WriteLine("stopping server");
ServerStopped = true;
}
else
{
Console.WriteLine("unknow command: " + cmd);
}
}
EndThreads(mainThread);
}
public static void EndThreads(Thread mainThread)
{
//stopping MainThread
mainThread.Abort();
Console.WriteLine("MainThread stopped");
//stopping all Threads
for (IEnumerator e = Threads.GetEnumerator(); e.MoveNext();)
{
//Getting next ServerThread
Console.WriteLine("Stopping the ServerThreads");
ServerThread serverThread = (ServerThread)e.Current;
//Stop it
serverThread.Stop = true;
while (serverThread.Running)
{
Thread.Sleep(1000);
}
}
//Stopping Listener
Listener.Stop();
Console.WriteLine("listener stopped");
Thread.Sleep(5000);
Console.Clear();
}
//opening a new ServerThread
public static void Run()
{
while (true)
{
Console.WriteLine("Listener waiting for connection wish");
//waiting for incoming connection wish
TcpClient client = Listener.AcceptTcpClient();
Threads.Add(new ServerThread(client));
}
}
}
class ServerThread
{
public bool Stop;
public bool Running;
private TcpClient client;
public ServerThread(TcpClient client)
{
this.client = client;
//starting new thread with run() function
Console.WriteLine("Starting new ServerThread");
new Thread(new ThreadStart(Run)).Start();
}
//threaded function
public void Run()
{
Stream stream = null;
Boolean gotstream = false;
Console.WriteLine("Reading incoming Data Stream");
Running = true;
while (!gotstream)
{
//making sure stream is not null to avoid exeption
if (client.GetStream() != null)
{
//getting stream, setting flag true
stream = client.GetStream();
gotstream = true;
}
}
Boolean loop = true;
byte[] incomingValues = new byte[] {255, 255};
Boolean gotData = false;
while (loop)
{
//checking if a remote host is still connected
if (client.Connected)
{
try
{
//reading Byte Array
stream.Read(incomingValues, 0, incomingValues.Length);
gotData = true;
}
catch (Exception e)
{
//catching exeptions
Console.WriteLine("Ooops, something wrent wrogn \n" + e);
loop = false;
}
if (gotData)
{
//converting bytes to int, sending DMX Values
int channel = Convert.ToInt32(incomingValues[0]);
int value = Convert.ToInt32(incomingValues[1]);
DmxInterface.SetData(channel, value);
Console.WriteLine("Received Data... \n Channel: " + channel + " Value: " + value);
}
}
else
{
//exiting loop if connection is lost
Console.WriteLine("connection lost");
Program.ServerStopped = true;
loop = false;
}
}
}
}
}
Specifically, I need to develop a Desktop app that pulls data from H7 Heart Rate Sensor in C# code.
I have searched everywhere and i cant find nothing to help me.
The closest i cam is with this video (https://www.youtube.com/watch?v=Jn05CU3mxzo&list=UUizfLH6Q2igGUyTWO1bH3YA) tutorial but still it didn't find my H7 Heart Rate Sensor.
namespace _123
{
public partial class Form1 : Form
{
List<string> items;
public Form1()
{
InitializeComponent();
items = new List<string>();
}
private void bGo_Click(object sender, EventArgs e)//button
{
if (serverStarted)
{
updateUI("server aleredy started");
return;
}
if (rbClient.Checked) {
startScan();
}
else{
connectAsServer();
}
}
private void startScan() {
listBox1.DataSource = null;
listBox1.Items.Clear();
items.Clear();
Thread bluetoothScanThread = new Thread(new ThreadStart(scan));
bluetoothScanThread.Start();
}
BluetoothDeviceInfo[] devices;
private void scan ()
{
updateUI("Starting scan...");
BluetoothClient client = new BluetoothClient();
devices = client.DiscoverDevicesInRange();
updateUI("Scan complet");
updateUI(devices.Length.ToString() + "devices discovered");
foreach (BluetoothDeviceInfo d in devices)
{
items.Add(d.DeviceName);
}
updateDeviceList();
}
private void connectAsServer()
{
Thread bluetoothServerTherad = new Thread(new ThreadStart(ServerConnectThread));
bluetoothServerTherad.Start();
}
private void connectAsClient()
{
}
Guid mUUID = new Guid("ECC037FD-72AE-AFC5-9213-CA785B3B5C63");
bool serverStarted = false;
private void ServerConnectThread()
{
//throw new NotImplementedException();
serverStarted = true;
updateUI("Server started, waiting for clients");
BluetoothListener blueListener = new BluetoothListener(mUUID);
blueListener.Start();
BluetoothClient conn = blueListener.AcceptBluetoothClient();
updateUI("Client has connected");
Stream mStream = conn.GetStream();
while (true)
{
try
{
byte[] received = new byte[1024];
mStream.Read(received, 0, received.Length);
updateUI("Received: " + Encoding.ASCII.GetString(received));
byte[] sent = Encoding.ASCII.GetBytes("hello world");
mStream.Write(sent, 0, sent.Length);
}
catch (IOException exeption)
{
updateUI("Client has disconected!");
}
}
}
private void updateUI(string message)
{
Func<int> del = delegate()
{
tbOutput.AppendText(message + System.Environment.NewLine);
return 0;
};
Invoke(del);
}
private void updateDeviceList()
{
Func<int> del = delegate()
{
listBox1.DataSource = items;
return 0;
};
Invoke(del);
}
BluetoothDeviceInfo deviceInfo;
private void listBox1_DoubleClick(object sender, EventArgs e)
{
deviceInfo = devices.ElementAt(listBox1.SelectedIndex);
updateUI(deviceInfo.DeviceName + " was selected, attemting connect");
if (pairDevice())
{
updateUI("device paired..");
updateUI("starting conected thread");
Thread bluetoothClientThread = new Thread(new ThreadStart(ClientConnectThread));
bluetoothClientThread.Start();
}
else
{
updateUI("pair failed");
}
}
private void ClientConnectThread()
{
BluetoothClient client = new BluetoothClient();
updateUI("attepting connnection");
client.BeginConnect(deviceInfo.DeviceAddress, mUUID, this.BluetoothClientConnectCallback, client);
}
void BluetoothClientConnectCallback(IAsyncResult result)
{
BluetoothClient client = (BluetoothClient)result.AsyncState;
client.EndConnect(result);
Stream stream = client.GetStream();
stream.ReadTimeout = 1000;
while (true)
{
while (!ready) ;
stream.Write(message, 0, message.Length);
}
}
string myPin = "1234";
private bool pairDevice()
{
if (!deviceInfo.Authenticated)
{
if (!BluetoothSecurity.PairRequest(deviceInfo.DeviceAddress, myPin))
{
return false;
}
}
return true;
}
bool ready = false;
byte[] message;
private void tbText_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == 13)
{
message = Encoding.ASCII.GetBytes(tbText.Text);
ready = true;
tbText.Clear();
}
}
}
}
This question is old now but here is my answer. So if you have Polar H7 and you are trying to get the Heart rate then I would recommend follow this Bluetooth Low Energy sample and just run the code it should work fine.
After you run this sample click on start enumerating and it will give you list of all the Bluetooth device .
Then find Polar H7 and click on it.
Go to step 2 and hit Connect and choose characteristic and service and you are done.