Serial Port connection problems - bluetooth

I bought a sensor that is able to acquire phisiological parameters; it is connected to my pc with bluetooth protocol, so when it is connected a serial port (named for example COM10) is assigned.
Now I'm writing a simple routine to read the data in real time:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using SewLib;
using System.IO.Ports;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
SewDevice myDevice;
SerialPort comPort;
public Form1()
{
InitializeComponent();
comPort = new SerialPort("COM10");
myDevice = new SewDevice(ref comPort);
myDevice.OnSamplesReceived += new ReceivedSamplesHandler(ReceiveData);
}
private void btstart_Click(object sender, EventArgs e)
{
eErrorClassOpcodes reply = myDevice.StartStreaming();
if (reply == eErrorClassOpcodes.Ok)
{
// ok device is connected and streaming is started
}
}
This works for me, but now I would to have a non static procedure for the selection of com port: my idea is to cycle beetween all the ports that my pc detect and select only the port with the bluetooth adapter.
Have you any ideas?
Thanks
Andrea

Auto-detecting your serial devices is a slippery slope. If you absolutely must, then I would just make a new helper class that looks something like this (untested)
class MyAutoDetector
{
public MyAutoDetector(){}
public SewDevice AutoDetect()
{
SerialPort comPort;
SewDevice myDevice = null;
eErrorClassOpcodes reply;
foreach(string portName in SerialPort.GetPortNames().ToList())
{
comPort = new SerialPort("COM10");
myDevice = new SewDevice(ref comPort);
reply = myDevice.StartStreaming();
if (reply == eErrorClassOpcodes.Ok)
{
// ok device is connected and streaming is started
break;
}
}
return myDevice;
}
I don't know about SewLib but you should verify that baud rate, bits, encoding, etc. Usually you configure your serial port with these.... but perhaps SewLib does that for you.
Another option, if you happen to know the unique PID/VID is answered here:
How do I get serial Port device id?

Related

Environment.userName is Unknown in Hololens2

I have an hololens2 application that I built in Unity. The Environment.Username works in the Unity editor correctly, but when I deployed to the HL2, the Environment.UserName is Unknown. Under the player settings I've applied Enterprise Application, WebCam,Microphone, HumanInterfaceDevice, UserAccountInformation, Bluetooth, SystemManagement, UserDataTasks and Contacts.
It builds just fine and deploys to HL2 without problems, but the UserName is Unknown. When I go to the HL2 start menu, it displays my name correctly.
Please Help,
Martin F.
Please try the following code, it should display the account name signed into the HoloLens2:
using System;
using System.Collections.Generic;
using System.Text;
using TMPro;
using UnityEngine;
#if WINDOWS_UWP
using Windows.System;
#endif
public class UserName : MonoBehaviour
{
[SerializeField]
private TMP_Text userNameText = null;
// Start is called before the first frame update
async void Start()
{
#if WINDOWS_UWP
IReadOnlyList<User> users = await User.FindAllAsync();
StringBuilder sb = new StringBuilder();
foreach (User u in users)
{
string name = (string)await u.GetPropertyAsync(KnownUserProperties.AccountName);
if (string.IsNullOrWhiteSpace(name))
{
name = "unknown account name";
}
sb.AppendLine(name);
}
userNameText.text = sb.ToString();
#endif
}
}

How to close a socket.io connection correctly in UnityEditor?

It's a simple sample. The server's developed with node.js and socket.io, and the client's developed with unity3d and BestHTTP.
When I play client in UnityEditor, everything is ok, but after the UnityEditor stoped, it still keeps connected with the server via socket.io.
I think there is a thread still working in background. Is it a problem of UnityEditor? And how do I to make it work correctly?
Server code:
io.on('connection', function(socket) {
console.log('User[' + socket.id + '] connected.');
socket.on('disconnect', () => {
console.log('disconnect.');
});
});
Client code:
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using BestHTTP;
using BestHTTP.SocketIO;
public class SocketIOClientTest : MonoBehaviour
{
private SocketManager _manager = null;
// Start is called before the first frame update
void Start()
{
_manager = new SocketManager(new Uri("http://localhost:9314/socket.io/"));
_manager.Socket.On("connect", (socket, packet, args) => { Debug.Log("1"); });
}
}
BestHTTP is decently documented, you should definitely read it.
What I use in my project :
private void OnDestroy()
{
_socket?.Disconnect();
_socketManager?.Close();
}

UDP sockect about string in UWP

I find a strange problem when I write code in UWP.
I use UDP sockect to send a coordinates to hololens.
The coordinate is like "1.0_1.0_1.0", it was send as string and will be cut according to "_",then the coordinate will be used to control the moving of a sphere.
First of all, it run all right in the unity editor.
But in the hololens, for example, I only receive "1.0_1.0_1.0", but cannot change it to vector3:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using HoloToolkit.Unity;
#if !UNITY_EDITOR
using System;
using Windows.Foundation;
#endif
public class pre : MonoBehaviour
{
public TextMesh tm = null;
public TextMesh tmmm = null;
public GameObject sphere;
string test;
public void ResponseToUDPPacket(string incomingIP, string incomingPort, string data)
{
string[] centre = data.Split('_');
float[] num= new float[3];
if (tm != null)
tm.text = data;
num[0] = float.Parse(centre[0]);
num[1] = float.Parse(centre[1]);
num[2] = float.Parse(centre[2]);
Debug.Log(num[1]);
if (tmmm != null)
tmmm.text = num[1].ToString();
sphere.transform.position = new Vector3(num[0], num[1], num[2]);
//var headPosition = Camera.main.transform.position;
//headPosition.z = headPosition.z+10;
//sphere1.transform.position = headPosition;
}
}
I use two testmesh to show the result, "data"is the string I have received, the first "tm" doesn't have problem.for example, it will show"1.0_1.0_1.0".
But the "tmm" which is get according to num[1] is never work.
I have thought it is the problem of UWP.
BUT!!!!!!!!!!!!!!!!!!!!!!!
I send the UDP string by a c++ program, but when I use a software(UDPsender or something like it) to send string manually, the problem in hololens disappeared!
But I don't think there is a problem in my C++ program, because at least it run well in unity editor.
Is there anyone has idea about the problem?
Maybe your emulator and your device have different cultures and one understands 1.0 while the other expects 1,0 in the float.Parse.
You can pass your culture (or InvariantCulture) to float.Parse if that is the case.
Does the Debug.Log(num[1]) print the correct number in all cases? If not, this could confirm the above theory.

C# code fails to read serial input from Arduino

Hi I am trying to read serial input from my Arduino but I am having no luck. I believe I am opening and closing the connection correctly but do not appear to be having much success!
I'm sure the Arduino is outputting data because I can see it in the serial terminal.
The code for my C# program is below, I was wondering if anyone could spot any mistakes I may have missed.
Also this is an example of the serial data I should receive "12.2,1111,332,233"
namespace FridgeProtectionDeviceMonitor
{
public partial class Online_mode : Form
{
public Online_mode()
{
InitializeComponent();
}
private void Online_mode_Load(object sender, EventArgs e)
{
cmbPortSelection.DataSource = SerialPort.GetPortNames();
cmbChartSelection.SelectedIndex = 0;
}
string x = "";
SerialPort port;
private void btnFindPorts_Click(object sender, EventArgs e)
{
var ports = SerialPort.GetPortNames();
cmbPortSelection.DataSource = ports;
}
private void btnOpenPort_Click(object sender, EventArgs e)
{
if (cmbPortSelection.SelectedIndex > -1)
{
port = new SerialPort(cmbPortSelection.Text);
try
{
if (!port.IsOpen)
{
port.BaudRate = 9600;
port.Open();
}
}
catch (Exception)
{
MessageBox.Show("Serial connection request denied: Port is in use!");
}
}
else
{
MessageBox.Show("Serial connection request denied: No port selected!");
}
}
private void btnClosePort_Click(object sender, EventArgs ex)
{
try
{
port.Close();
}
catch (Exception)
{
MessageBox.Show("Serial close connection request denied: ", ex.ToString());
}
}
private void update(object sender, EventArgs e)
{
txtSaveLocation.Text = x;
}
private void port_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
x = port.ReadLine().ToString();
MessageBox.Show(x);
this.Invoke(new EventHandler(update));
}
}
}
I was just working on the same thing as you, you'll have to modify it if you want to use it for your purposes, but here's the code I use that works. The only problem is that for me I need it to read very quickly because it's for a speedometer and it sort of lags (anyone know why?) but anyways here's my code that works for me.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public void Form1_Load(object sender, EventArgs e)
{
try
{
if (arduinoCom.IsOpen == false)
{
arduinoCom.Open();
}
}
catch
{
MessageBox.Show("Serial Error: Is your serial plugged in?");
}
}
private void refresh_Tick(object sender, EventArgs e)
{
string speedReading = arduinoCom.ReadLine();
speed.Text = speedReading;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
arduinoCom.Close();
}
}
}
I've got a USB to serial converter linked to an XBee wireless bridge linked to PIC micro-controllers and i've found that running the serial port read functions in a separate thread increases communication speeds something chronic!
The readline blocks the code until the newline character is received, therefore blocking your main thread. Before i moved it to another thread my GUI became un-responsive etc.
By the way I'm using ReadByte().
I'm continuously reading bytes from the serial buffer in a backgroundworker and storing them in a thread safe queue. Then checking the queue for my communication start bits and analyzing the packet from there. Using manual reset events I'm syncing everything.
In my experience the port_datareceived event is a nice addition to the serialport class but unfortunately it is relatively useless for fast communications. I'm running at 12900 baud.
If you want code snippets i can provide them.
Regards,
Pete
P.S. I'm using an ATS5004D 4 channel differential oscilloscope with multichannel software. multichannel software can analyse the voltage signal into serial data through it's built in serial analyzer block. That way you can see what's actually being discussed on the serial comms lines!! cutting out all the BS other serial terminals add...
#michael b I'd start by looking at what the actual communication is doing i.e. scope the TX RX lines to see what the arduino board is putting out. I have only little experience with arduino but its predecessor the PICAXE system had a debug function which slowed everything down heaps, is something like this going on?
How many times per second do you want to update the speedo?
The SAE J1939 automotive serial communication standard says that RPM only needs to be updated once every 100ms. The human eye usually can't see/react faster than 300ms. 9600 baud gives you one 8bit byte per millisecond approx.
Personally I wouldn't use the timer to get the updates and instead do everything on a separate thread from main, and let it run as fast/slow as it wants.
this thread shows you roughly how i've set up my communications System.IO.IOException: A device attached to the system is not functioning C# .NET 4.0
hope it helps,
pete

Windows Phone 8 (HTC 8X) Flashlight does not turn on(Without using camera)

As a newbie programmer I am going to ask a silly question. I want to turn on the flashlight of windows phone 8 without blinking (continous like other flashlight apps). Now I tried to use the sample example of
Reflection failure when attempting to access Microsoft.Phone.Media.Extended
but it did not work. I created a button called 'flash' and paste the code. It compiled fine, but my device HTC 8X does not turn on the flashlight even for a second. What I should do ?
The library & code I used :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Flashlight_V_0._1.Resources;
using Microsoft.Phone.Media;
using Windows.Phone.Media.Capture;
using Microsoft.Xna.Framework.Media;
using System.IO;
namespace Flashlight_V_0._1
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
// Sample code to localize the ApplicationBar
//BuildLocalizedApplicationBar();
}
private async void Button_Click_1(object sender, RoutedEventArgs e)
{
var sensorLocation = CameraSensorLocation.Back;
try
{
// get the AudioViceoCaptureDevice
var avDevice = await AudioVideoCaptureDevice.OpenAsync(sensorLocation,
AudioVideoCaptureDevice.GetAvailableCaptureResolutions(sensorLocation).First());
// turn flashlight on
var supportedCameraModes = AudioVideoCaptureDevice
.GetSupportedPropertyValues(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchMode);
if (supportedCameraModes.ToList().Contains((UInt32)VideoTorchMode.On))
{
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
// set flash power to maxinum
avDevice.SetProperty(KnownCameraAudioVideoProperties.VideoTorchPower,
AudioVideoCaptureDevice.GetSupportedPropertyRange(sensorLocation, KnownCameraAudioVideoProperties.VideoTorchPower).Max);
}
else
{
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
catch (Exception ex)
{
// Flashlight isn't supported on this device, instead show a White Screen as the flash light
//ShowWhiteScreenInsteadOfCameraTorch();
}
}
}
}
I also tried this:
try
{
var _device = await AudioVideoCaptureDevice.OpenAsync(CameraSensorLocation.Back, AudioVideoCaptureDevice.GetAvailableCaptureResolutions(CameraSensorLocation.Back).First());
_device.SetProperty(KnownCameraAudioVideoProperties.VideoTorchMode, VideoTorchMode.On);
}
catch (Exception ex)
{
//
}
What am I doing wrong?
Sorry for late reply, got it ago but could not post.Sorry for that.
WP7/WP7.5 gives default to access all the sensors. But in WP8, you have to manually enable the sensors capability.
Go to the solution explorer.
Select the project.
Select Properties -> WMAppManifest.xml
Double Click on 'WMAppManifest.xml'
Select 'Capabilities'
Enable proper capability for app
To resolve my problem I had to enable two capabilities.
ID_CAP_ISV_CAMERA
ID_CAP_MICROPHONE
Thank YOU

Resources