This is my first time integrating Serial to USB in a C# application, so please pardon me if this sounds like a stupid question.
I have Class IV laser. I am integrating that in to my C# application.
My problem is I can connect to the laser, I can send data to the laser but i don't get any return from the laser.
private void Bt_Start_Click(object sender, EventArgs e)
{
SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
serialPort.Handshake = Handshake.XOnXOff;
serialPort.DtrEnable = true;
serialPort.RtsEnable = true;
serialPort.ReadTimeout = 500;
serialPort.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived);
ConenctToLaser("COM3", serialPort);
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
byte[] buffer = new byte[sp.BytesToRead];
int bytesRead = sp.Read(buffer, 0, buffer.Length);
var message = Encoding.ASCII.GetString(buffer, 0, bytesRead);
MessageBox.Show(message);
}
public void ConenctToLaser(string port, SerialPort serialPort)
{
StreamReader openfile = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\commands.txt");
if (serialPort.IsOpen == false)
{
serialPort.Open();
string command = "";
command = openfile.ReadLine();
while(command!=null)
{
byte[] buffer = Encoding.ASCII.GetBytes(command);
serialPort.Write(buffer, 0, buffer.Length);
command = openfile.ReadLine();
}
}
}
The commands.txt includes my commands. which are
\r
MTT\r
MCM\r
SPR300\r
on different lines
When i send these commands to the laser all i get back is the echo. So in reality when i send ("MTT\r") i should get back the temperature of the hardware. When i test my hardware in putty it works i get return for all the commands above. Here's the definition for one of the commands from the .pdf they have provided.
Laser Temperature Command: MTT\r
Description: The laser actual laser temperature expressed in XX.X degC
After hours of researching I found the answer to my question. From what i read online it seems like the SerialPort class by Microsoft doesn't work very well with all the serial Hardware. So I would need to use a wrapper class to work with Win32 API.
I found this article which explains how to use Win32 class to communicate with the serial device. It also has a wrapper to call the Win32 methods. You can read all about it and download all the code from the below link.
https://msdn.microsoft.com/en-us/magazine/cc301786.aspx
Hope this helps somebody who's having the same problem.
Related
I have a barcode Scanner and I want to read the Barcode Prefix from the Hardware
on the hardware set, a two character like "01" or "AA" as a Prefix
I receive from comport "\u0002\0\0\u0001\031" what is it? Hex? Or Unicode?
Hex must be Like this : 0x30 // 0
0x31 // 1
Documentation
Here is my Write method an the Comport
public void GetPrefix(SerialPort serialPort)
{
try
{
if (serialPort.IsOpen)
{
Thread.Sleep(100);
Console.WriteLine("Open");
byte[] my_byte = new byte[9];
my_byte[0] = 0x7E;//Header
my_byte[1] = 0x00;//Header
my_byte[2] = 0x08;//Type
my_byte[3] = 0x01;//Lens
my_byte[4] = 0x63;//add
my_byte[5] = 0x71;//add
my_byte[6] = 0x08;//data : The data read
my_byte[7] = 0xAB;//CRC
my_byte[8] = 0xCD;//
serialPort.Write(my_byte, 0, 9);
rx_message = serialPort.ReadExisting();
Console.WriteLine(rx_message);
}
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
Here is a DataReceivedHandler method
private void DataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(1000);
SerialPort sp = (SerialPort)sender;
unicode = sp.ReadExisting(); //Read the data
Console.WriteLine(unicode);
}
catch (Exception)
{
throw;
}
}
What you received is what is written on page 68 of the document.
It indicates that the processing of the write command you sent has completed normally.
However, this is a strange phenomenon. The documentation only lists addresses from 0x0000 to 0x00E5, and the 0x6371(or 0x7163?) you specify is a private address.
You may have broken something in the barcode scanner by doing this.
And you sent a write command, which you wouldn't be able to use to read your intended barcode prefix.
You should use the read command, which is written from page 64 of the document.
By reading 0x11 bytes from 0x0060 of the address, you will be able to check the presence/absence, length, and data of the prefix.
Details of them can be found on pages 87-88 of the documentation.
I am trying to develope a Voice Chat window application using NAudio with multiple client, the problem is its not working or how can i send recorded voice to all the clients at same time and play on client side, then send the recorded voice of client and send it back to server.I am also using NetComm.dll to fetaure my application with Text Chat. Any help would be higly appreciated.enter image description here
using NAudio.Wave;
namespace NaudioVoiceChat
{
public partial class Server: Form
{
#region Codes for NAudio ------->>>> This is for NAudio
private BufferedWaveProvider bwp;
WaveIn wi;
WaveOut wo;
public Server()
{
InitializeComponent();
#region Code for Naudio
wo = new WaveOut();
wi = new WaveIn();
wi.DataAvailable += new EventHandler<WaveInEventArgs>(wi_DataAvailable);
bwp = new BufferedWaveProvider(wi.WaveFormat);
bwp.DiscardOnBufferOverflow = true;
wo.Init(bwp);
wi.StartRecording();
}
void wi_DataAvailable(object sender, WaveInEventArgs e)
{
bwp.AddSamples(e.Buffer, 0, e.BytesRecorded);
server.SendData("Client-1", e.Buffer);
}
I'm familiar with C#, and know some python. Recent days I'm learning the book Programming Python, 4th Edition and have run the very basic socket samples: echo-server.py and echo-client.py
They work well on my Windows, python 3.x.
python server:
from socket import *
myHost = 'localhost'
myPort = 50007
sockobj = socket(AF_INET, SOCK_STREAM)
sockobj.bind((myHost, myPort))
sockobj.listen(5)
while True:
connection, address = sockobj.accept()
print('Server connected by', address)
while True:
data = connection.recv(1024)
if not data: break
connection.send(b'Echo=>' + data)
connection.close()
Now I want to learn socket in C# too, so I wrote a C# .net framework 4.5 socket client, expecting to receive and show what echo-client.py does.
I got the C# demo from msdn and made some refactor to reduce code size.
public static void Main(string[] args)
{
string server = "localhost";
int port = 50007;
string request = "GET / HTTP/1.1\r\nHost: " + server +
"\r\nConnection: Close\r\n\r\n";
Byte[] sent = Encoding.ASCII.GetBytes(request);
Byte[] recv = new Byte[256];
IPHostEntry hostEntry = Dns.GetHostEntry(server);
IPEndPoint ipe = new IPEndPoint(hostEntry.AddressList[1], port);
Socket s =
new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp);
s.Connect(ipe);
s.Send(sent, sent.Length, 0);
int bytes = 0;
string page = "recived:\r\n";
//do
{
bytes = s.Receive(recv, recv.Length, 0);
page = page + Encoding.ASCII.GetString(recv, 0, bytes);
}
//while (bytes > 0);
Console.WriteLine(page);
Console.WriteLine("result");
Console.ReadKey();
}
My test steps:
If I set up a web site using local IIS, such as
http://localhost:801, then above code can show the homepage html
contents, this means my C# code is working.
Run echo-server.py, and change C# code's port to 50007, then run,
nothing output in console, and application does not exit, if I place a break point within the loop, I can see the loop has only run once. The python server did output some log saying C# is connecting.
Comment do while loop(as commented in code), this time the output is exactly same as echo-client.py(expected).
So I'm wondering what's wrong when I'm using do while loop?
I am trying to communicate with a Nokia Lumia phone(RM-917), over USB using LIBUSING and C#. LIBUSB is able to see the device's information(pid,vid,etc). However, I am not able to successfully write to ANY endpoint, even sending the exact command as the Windows Device Recovery Tool.
According to WinUSB, the write endpoint is EP07, however, this endpoint just times out. I have tried every other endpoint, and all of these fail.
`
public void initDevice()
{
if(this.lumiaDevice == null)
{
throw new Exception("LumiaPhoneManager does not have a selected device");
}
UsbDeviceFinder MyUsbFinder = new UsbDeviceFinder(0x0421, 0x0661);
MyUsbDevice = UsbDevice.OpenUsbDevice(MyUsbFinder);
IUsbDevice wholeUsbDevice = MyUsbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
// This is a "whole" USB device. Before it can be used,
// the desired configuration and interface must be selected.
// Select config #1
wholeUsbDevice.SetConfiguration(1);
// Claim interface #0.
wholeUsbDevice.ClaimInterface(1);
}
if (this.writer == null)
{
writer = MyUsbDevice.OpenEndpointWriter(WriteEndpointID.Ep07);
}
}
public void readPCode()
{
currentID++;
var _x = new jsonPkt();
ErrorCode ec = ErrorCode.None;
int bytesWritten;
_x.id = this.currentID + 1;
_x.method = "ReadProductCode";
string value = #"{""jsonrpc"":""<JSONRPC>"",""id"":<ID>,""method"":""<METHOD>"",""params"":null}";
value = value.Replace("<JSONRPC>", "2.0");
value = value.Replace("<ID>", currentID.ToString());
value = value.Replace("<METHOD>", _x.method.ToString());
ec = writer.Write(Encoding.Default.GetBytes(value), 8000, out bytesWritten);
currentID++;
if (ec != ErrorCode.None) throw new Exception(UsbDevice.LastErrorString);
byte[] readBuffer = new byte[1024];
while (ec == ErrorCode.None)
{
int bytesRead;
// If the device hasn't sent data in the last 100 milliseconds,
// a timeout error (ec = IoTimedOut) will occur.
ec = reader.Read(readBuffer, 100, out bytesRead);
// if (bytesRead == 0) throw new Exception("No more bytes!");
// Write that output to the console.
this.rtb.Text += Encoding.Default.GetString(readBuffer, 0, bytesRead).ToString() + "\n";
}
}
Found the solution
Debugged the OEM software and found the program was using a different path to the USB device. After that I was getting access denied errors, which was solved by moving the project to a different drive. For reasons unknown, when the program runs on c drive, the CreateFile function fails with access denied
Its possible that to activate write, you need to send some class specific control request first. You mentioned that windows device recovery tool is able to write.
You can install USB packet sniffer software in your windows PC and then use the device manager to write some data to the device. Packet sniffer tool will be able to capture all the packets sent to the device.
This way you can see the exact device requests which are required to enable write operation.
Analyzer software - http://www.usblyzer.com/
Please try this way to resolve your problem.
PS- I am assuming you do not have a hardware USB packet analyzer like Lecroy advisor or Beagle. Software packet sniffer should be fine since the host is a PC.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a device that can communicate trough RS232. and it comes with the communication protocol to access the data.
I'm writing a simple c# program to connect and get the status from the device and Im not quite sure whether Im on the right path.
Below is the sample they have given.
Command 50: status request
The status request command is used to request the register response package, without later actions that may alter the status of the system.
0 1 2 3 4 5 6 7 8 9 10 11 12 13
STX ADDR ADDR CMOD "5" "0" "0" "3" TKN1 TKN0 TYPE CHKL CHKH 0X0D
STX = Start byte of the frame (0x02)
ADDR = TE550 logical address [2 bytes]
CMOD = CMOD to refer [1 byte]
TKN1/0 = Frame identification bytes [2 bytes]
TYPE = Selection byte for customizable box (RiqA/B)* [1 byte]
CHKH/L = Checksum [2 bytes]
END = End byte of the frame (0x0D)
Example:
status request from PC to TE550 (address 01), CMOD 1, Token 01, Type 1
[0x02]0115003011EE[0x0D]
I can connect to the com port using the serial port.
I am referring to the answer by DesMy "RS232 serial port communication c# win7 .net framework 3.5 sp1"
So far Im not getting any signal once write to the COM port. However I'm not quite sure whether Im sending the correct data to the com port. Currently Im sending data as below
comPort.Write("20115003011EE3");
Any help / sample code etc would be much appreciated.
public void ConnectRS232 ()
{
try
{
SerialPort mySerialPort = new SerialPort("COM1");
mySerialPort.BaudRate = 9600;
mySerialPort.Parity = Parity.None;
mySerialPort.StopBits = StopBits.One;
mySerialPort.DataBits = 8;
mySerialPort.Handshake = Handshake.None;
mySerialPort.ReadTimeout = 2000;
mySerialPort.WriteTimeout = 500;
mySerialPort.DtrEnable = true;
mySerialPort.RtsEnable = true;
mySerialPort.Open();
mySerialPort.DataReceived += DataReceivedHandler;
mySerialPort.Write("20115003011EE3");
}
catch (Exception ex)
{
textBox1.Text = ex.Message;
}
}
public void DataReceivedHandler(object sender,SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
System.Threading.Thread.Sleep(500);
string indata = sp.ReadExisting();
this.BeginInvoke(new SetTextDeleg(DisplayToUI), new object[] { indata });
}
private void DisplayToUI(string displayData)
{
textBox1.Text += displayData.Trim();
}
When dealing with low level port I/O, characters are not bytes!
Do not send strings. Create a byte stream containing the correct characters and send that.
[In .NET characters are shorts, not bytes. Doesn't matter. Use bytes.]