I am trying to get information reading a card using the RFID Gigatek UR110/115U.
This card just has a code, and I want to read it and store it in a variable.
My reader is in COM4 and is connected by USB.
I am trying something like this:
Designer:
private void InitializeComponent()
{
//...
this.serialPort1 = new System.IO.Ports.SerialPort(this.components);
//...
this.serialPort1.DataReceived += new System.IO.Ports.SerialDataReceivedEventHandler(this.serialPort1_DataReceived);
//...
private System.IO.Ports.SerialPort serialPort1;
//...
}
Method:
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
if (this.serialPort1.IsOpen == true)
{
String aux = this.serialPort1.ReadLine();
if (Encoding.ASCII.GetBytes(aux)[0] == 2)
aux = aux.Substring(1);
if (aux.Length > 10)
aux = aux.Substring(0, 10);
this.Lectura = aux;
if (this.serialPort1.IsOpen)
this.serialPort1.Close();
this.tiempo_esperado = 0;
}
}
But this is not working. What could am I doing wrong? Thanks in advance!
Related
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)
I'm trying to plot the data read from a serial port using zedgraph. I'm still learing to code so I couldn't deduce why the plot does not work. Please have a look at the code and advice;
namespace WindowsApplication2
{
public partial class Form1 : Form
{
string t;
SerialPort sp;
Thread m_thread;
bool m_running = false;
ManualResetEvent m_event = new ManualResetEvent(true);
bool m_pause = false;
private GraphPane myPane;
public Form1()
{
InitializeComponent();
Control.CheckForIllegalCrossThreadCalls = false;
// User can already search for ports when the constructor of the FORM1 is calling
// And let the user search ports again with a click
// Searching for ports function
SearchPorts();
CreateZedGraph(); //error : Severity Code Description Project File Line Suppression State
//Error CS7036 There is no argument given that corresponds to the required formal parameter
//'w' of 'Form1.DrawPoint(ZedGraphControl, int, PointPair)'
}
// start button
private void btnStart_Click(object sender, EventArgs e)
{
if (m_thread == null || m_thread.IsAlive == false)
{
ClearGraph();
m_thread = new Thread(Process);
m_thread.Start();
}
}
void Process()
{
PointPair point = new PointPair();
btnStart.Enabled = false;
btnStop.Enabled = true;
m_running = true;
while (m_running == true)
{
m_event.WaitOne();
point.Y = Convert.ToDouble(serialPort1);
point.X++; //time instance of measurement??
DrawPoint(zed1, point);
ssData.Value = point.Y.ToString();
RefresheZedGraphs(zed1);
Thread.Sleep(700);
}
btnStart.Enabled = true;
}
private void CreateZedGraph(object sender, SerialDataReceivedEventArgs e, ZedGraphControl zgc)
{
myPane = zgc.GraphPane;
// axes stuff
myPane.Title.Text = "FRDM-KW40z serial Test";
myPane.XAxis.Title.Text = "Time";
myPane.YAxis.Title.Text = "Voltage";
myPane.XAxis.MajorGrid.IsVisible = true;
myPane.YAxis.MajorGrid.IsVisible = true;
myPane.XAxis.MinorGrid.IsVisible = true;
myPane.YAxis.MinorGrid.IsVisible = true;
// data from serial port
PointPairList list = new PointPairList();
zed1.GraphPane.AddCurve("Test", list, Color.Red);
}
To open and read from a serial port, I use a combox and a couple of buttons (and then later I try to save it to a text file);
private void button2_Click(object sender, EventArgs e)
{
comboBox1.Items.Clear();
SearchPorts();
}
void SearchPorts()
{
string[] ports = SerialPort.GetPortNames();
foreach (string port in ports)
{
comboBox1.Items.Add(port);
}
}
private void button3_Click(object sender, EventArgs e)
{
// Catch exception if it will be thrown so the user will see it in a message box
OpenCloseSerial();
}
void OpenCloseSerial()
{
try
{
if (sp == null || sp.IsOpen == false)
{
t = comboBox1.Text.ToString();
sErial(t);
button3.Text = "Close Serial port"; // button text
}
else
{
sp.Close();
button3.Text = "Connect and wait for inputs"; // button text
}
}
catch (Exception err) // catching error message
{
MessageBox.Show(err.Message); // displaying error message
}
}
void sErial(string Port_name)
{
try
{
sp = new SerialPort(Port_name, 115200, Parity.None, 8, StopBits.One); // serial port parameters
sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
sp.Open();
}
catch (Exception err)
{
throw (new SystemException(err.Message));
}
}
private void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
// This below line is not need , sp is global (belongs to the class!!)
//SerialPort sp = (SerialPort)sender;
if (e.EventType == SerialData.Chars)
{
if (sp.IsOpen)
{
string w = sp.ReadExisting();
if (w != String.Empty)
{
Invoke(new Action(() => Control.Update(w)));
}
}
}
}
private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
if (sp == null || sp.IsOpen == false)
{
OpenCloseSerial();
}
}
The plot does not update! I can't quite guess why. Please tell me if there's mistakes in my approach or the code.
I get an error at : Invoke(new Action(() => Control.Update(w))); when trying to update the graph so that I can save after that.
I again have an error at: DrawPoint(zed1, point);
Thank you all for your time. Good day.
Cheers,
Ram.
To update the chart, you need to call the Invalidate method.
When you receive data from serial port, you need to convert it to double[] and add those points to your PointPairList.
PointPairList list = new PointPairList();
zed1.GraphPane.AddCurve("Test", list, Color.Red);
//Convert the received data to double array
double[] serialPortData = ....
//You may want to clear list first, by list.Clear();
list.Add(serialPortData);
//Invalidate the ZedGraphControl to update
zed1.Invalidate();
I am trying to write a program that communicates with a controller. The controller is supposed to send a "welcome" message when a connection is successfully established and, in fact, it does when I connect using a communications software. However, using the .NET code below, I never see the welcome message. Beyond that, it works. How can I capture this message. It seems to be sent the moment the connection is established.
Again, I am able to communicate fine with the controller after connection but I simply cannot seem to get the welcome message that is sent a the moment the connection is opened.
using System;
using System.IO.Ports;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public delegate void AddDataDelegate(String myString);
public AddDataDelegate myDelegate;
SerialPort sp;
public Form1()
{
InitializeComponent();
}
public void AddDataMethod(String myString)
{
richTextBox1.AppendText(myString);
richTextBox1.SelectionStart = richTextBox1.Text.Length;
richTextBox1.ScrollToCaret();
}
private void button1_Click(object sender, EventArgs e)
{
try
{
sp = new SerialPort(comboBox1.SelectedItem.ToString(),Int32.Parse(comboBox2.SelectedItem.ToString()));
sp.DataReceived += SerialPort_OnDataReceived;
sp.Close();
sp.Open();
richTextBox1.AppendText("open\n");
button2.Enabled = true;
button3.Enabled = true;
}
catch (Exception ex)
{
richTextBox1.AppendText(ex.Message);
}
}
void SerialPort_OnDataReceived(object sender,SerialDataReceivedEventArgs args)
{
SerialPort sp = sender as SerialPort;
string s = sp.ReadExisting();
richTextBox1.Invoke(this.myDelegate, new Object[] { s });
}
private void button2_Click(object sender, EventArgs e)
{
sp.WriteLine(textBox1.Text);
textBox1.Text = "";
}
private void button3_Click(object sender, EventArgs e)
{
sp.DiscardOutBuffer();
sp.DiscardInBuffer();
sp.Close();
richTextBox1.AppendText("\nclosed\n");
}
private void Form1_Load_1(object sender, EventArgs e)
{
this.myDelegate = new AddDataDelegate(AddDataMethod);
string[] Ports = SerialPort.GetPortNames();
comboBox2.SelectedIndex = comboBox2.Items.Count - 1;
Array.Sort(Ports, (a, b) => string.Compare(a.Substring(3).PadLeft(3, '0'), b.Substring(3).PadLeft(3, '0')));
foreach (string port in Ports)
{
comboBox1.Items.Add(port);
}
comboBox1.SelectedIndex = 0;
}
}
}
I worked it out. Required a slight delay between connection and trying to pull data from the port.
What I want to do with my application is to be able to read the characteristics of the scanned devices. I'm able to scan devices, but the scan will keep taking in whatever it finds. So I would like to have an filter for that as well. An attached picture of my results are located below my codes.
Here are my codes
using Robotics.Mobile.Core.Bluetooth.LE;
using Adapter = Robotics.Mobile.Core.Bluetooth.LE.Adapter;
var appContext = Application.Context;
_manager = (BluetoothManager)appContext.GetSystemService(BluetoothService); // ("bluetooth");
_adapter = _manager.Adapter;
_bleAdapter = new Adapter();
_bleAdapter.DeviceDiscovered += _bleAdapter_DeviceDiscovered;
_bleAdapter.ScanTimeoutElapsed += _bleAdapter_ScanTimeoutElapsed;
}
private void _bleAdapter_ScanTimeoutElapsed(object sender, EventArgs e)
{
_bleAdapter.StopScanningForDevices();
DisplayInformation("Bluetooth scan timeout elapsed, no ble devices were found");
}
private void _bleAdapter_DeviceDiscovered(object sender, DeviceDiscoveredEventArgs e)
{
var msg = string.Format(#"Device found: {0}
{1} - {2}", e.Device.Name, e.Device.ID, e.Device.Rssi);
DisplayInformation(msg);
}
private void ButtonScanBleClick(object sender, EventArgs e)
{
if (!_bleAdapter.IsScanning)
_bleAdapter.StartScanningForDevices();
}
private void DisplayInformation(string line)
{
_textboxResults.Text = $"{line}\r\n{_textboxResults.Text}";
Console.WriteLine(line);
}
Picture of my output result Here
If I understand well, you want some filter for found devices.
You have to write a bluetooth scanner callback, and then something like this:
in callback:
public void OnLeScan(BluetoothDevice device, int rssi, byte[] scanRecord)
{
if (device.Name != null)
{
EventScanDevice(device, rssi);
}
}
in MainActivity:
List<string> scanList;
private void Scanner_EventScanDevice(BluetoothDevice device, int rssi)
{
if (!scanList.Contains(device.Name))
{
scanList.Add(device.Name + ", RSSI = " + rssi.ToString());
}
}
I'm attempting to write a program which would enable texts to be sent out to customers, I'm using AT Commands with a GSM modem to accomplish this, I have looked at various bits of Documentation but have been unable to find a solution for the following problem.
I am attempting to make the GSM modem return all of the text messages contained within its memory, I have tried many combinations of AT Commands and Parsing techniques to throw this into a text box, but to no avail.
Any help on this would be most appreciated, my code is below
private SerialPort _serialPort2 = new SerialPort("COM3", 115200);
private void MailBox_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
_serialPort2.Open();
//_serialPort2.Write("AT+CMGF=1 \r");
_serialPort2.Write("AT+CMGL=\"ALL\"");
string SerialData = _serialPort2.ReadExisting();
var getnumbers = new string((from s in SerialData where char.IsDigit(s) select s).ToArray());
var getText = SerialData;
SendTxt.Text = getnumbers;
SendMsgBox.Text = getText;
//for (int i = 0; i < SerialData.Length; i++ )
//{
// if (char.IsDigit(SerialData))
//}
//.Text = _serialPort2.ReadExisting();
//string[] text = { textBox1.Text };
//IEnumerable<string> formattext = from words in text where words.("+447") select words;
// foreach (var word in formattext)
//{
//SenderBox.Items.Add(word.ToString());
// }
_serialPort2.Close();
//_serialPort2.DataReceived += new SerialDataReceivedEventHandler(_serialPort2_DataReceived);
}