C# periodic new line reading from serial port - c#

Checked many pages but I still find it unanswered.
My problem is as follows. I have a device, connected over RS232 to the computer. The device is sending TWICE a second a line like this:
"*X;0;bbb;cc;d;eee;f\r\n"
The fields are fixed width numeric fields. Once every minute the 0 flag raises to 1 and the "cc" changes. This number I need then.
In the C# application, I cannot get it working. Tried to use the recieve event to get the data, but the refreshed result needs 10+ seconds to be processed. This means that 10 seconds after the flag was risen i get the result. Sometimes it takes even longer.
I tried first with RecieveEvent. I even tried to fill the buffer untill it would fill the line, but again, same result. Then I tried with Timer that invokes every 300 ms and reads a line. Still the same problem.
So my question is, how to read and process up to date data from serial port?

When reading, the serial port will buffer data. This will introduce a small delay (but we're talking milliseconds, not tens of seconds). Most serial device drivers will allow you to configure the buffering, too, if it's really critical.
If you call ReadLine, you could introduce more delay, as it will wait until it receives a newline before it returns any data. Are you sure that your device is sending good newlines? Use a terminal emulator program to see exactly what the device is actually sending, as device documentation is often terrible!
I would Read raw data from the port, and then parse it myself. You may have to be more careful about receiving partial packets, but you remove all the middle-men from the picture, and you can be more tolerant (e.g. Not caring whether or not the data has newlines in it). Start a read and then write out the data you received to the debug console and you'll soon see what your program is receiving and how often, etc. This will also show you if the delay is in the serial port or in your processing of the messages

You may try serialPort1.readExisting(); then try parsing the data.
Good luck!

Related

Problem with ivi.visa reading binary block data

I am writing an application which communicates with a network analyser using ivi.visa from Keysight. I often work remotely where I don't have an instrument, so I decided to write an application that can respond to the SCPI commands I need. This works ok for things like "*IDN?", but when I try to receive a binary block using ReadBinaryBlockOfByte(), the call terminates when it sees a newline character in the data.
If I set TerminationCharacterEnabled to false, all reads timeout. This is mentioned in the Keysight visa.net examples, so it doesn't seem to be an option.
So how can I read binary data?

Watson IBM Speech to Text c# api

I using follow example to recognize text from audio https://gist.github.com/nfriedly/0240e862901474a9447a600e5795d500 but I need also time codes, i added at line 40 "timestamps" : true, and removed "interim_results": true as I need only final results. But it broken, after { "state": "listening" } message it takes some time and raise exception like that
"Text" received message is invalid after the call Websocket.Closeasync. Websockets.In cases closeasync, so you should only use those when you do not expect to receive other data from the remote endpoint. Use "Websockets.CloseOutputAsync" to preserve the possibility of obtaining additional data, but to close the outgoing channel.
And if i set "continuous" : false, It do only the first iteration of speech (few first words before a pause), and then repeat {"state": "listening" } and freezes.
Can you help me, how to update that example to return Timecodes?
continuous: false means "only transcribe until the first pause" - so it isn't "freezing", it's just stopping when you tell it to.
The service then sends the final results followed by the second {"state": "listening"} message to indicate that it's done sending results. The example code closes the connection after that, but it sound like you're still attempting to send audio after closing the connection.
I'm not certain, but I think that timestamps and interim_results will probably work the way you want once you set continuous: false.
Although, if you only need final results, then the HTTP interface might make more sense. It's much simpler than the WebSockets one.
Finally, as I mentioned in email, the official IBM Watson .net SDK has support for Speech to Text in the development branch right now, and should have it included in a release soon.

Continual Serial Port Reads

I'm trying to build a C# application that has one textbox that puts the data received on a selected serial port onto new lines as they come in.
I realise this isn't a specific question, but I have done a couple of hours search and can't even find out what to ask exactly from a coding point of view.
Can someone please point me in the right direction of how to read serial data continually?
look here, has examples of how to read and configure the baud rate, handshaking etc:
http://msmvps.com/blogs/coad/archive/2005/03/23/SerialPort-_2800_RS_2D00_232-Serial-COM-Port_2900_-in-C_2300_-.NET.aspx

Incomplete Serial Port Read C#

I'm trying to read bytes from a scanner hooked up to a COM port into a byte array. The Serial Port library in C# already has a Read function, this is the function I use to attempt a read. I have it setup so that the bytes read in are output to the console. I'm working with a protocol that is very predictable so I know what kind of byte array I am expecting when I pass that line in the code. However, if I run the program, I only get a single byte read in. If I re-run that same instance of the program (by sending the same read command) I get the rest of the expected bytes. Only after I run this a third time do I get all of the bytes I'm expecting. This problem is completely avoided though if I simply insert a breakpoint over the read line and step over that line. If I do this, I get a complete read every time. My question is, how can I get a complete read every time without inserting a breakpoint? I've tried using the System Pause approach to halt the execution and let the COM port scan fast enough, which did not work. I've also tried using a thread (see code below). This also did not work. Any suggestions?
t = new Thread(() => device.Read(buffer));
t.Start();
t.Join();
Again, my expected output only comes in a full-packet after re-sending the Read command a few times or by stepping over the above commands with a breakpoint. Otherwise I get my expected output in small "byte sized samples." Any help is appreciated!
This is expected behaviour with byte streams. Loop round the read and pump however many bytes received one-by-one into your ProtocolUnit class instance, (or whatever), until it is complete and verified.
I recently posted a similar question found here:
SerialPort.DataReceived Returning Strange Results
The problem is, as you know, the program tries to read from the buffer without any guarantee that the device is finished issuing whatever command it's running. My advice is to implement the first answer in this post:
Reading from the serial port in C#
My implementation is as follows in the DataReceived event:
void serialPort_DataReceived(object s, SerialDataReceivedEventArgs e)
{
byte[] data = new byte[serialPort.BytesToRead];
serialPort.Read(data, 0, data.Length);
Console.Write(System.Text.Encoding.UTF8.GetString(data));
}
And just to wire it up in the code:
serialPort.DataReceived += serialPort_DataReceived;
The best approach to put in while loop and also give 10 millisecond of sleep time in between of byte read. This will give 10 milliseconds to scanner to write data on COM port. Actually, Problem happens when you connect scanner in network port.
You can also write delegate or event which will notify when data is completely read from scanner.

Receiving Invalid Data from Serial Port using SerialPort.ReadExisting()

I have written a program in .NET that listens to a particular Serial Port and processes the data that is being received. I wrote a test program using com0com (the Null-modem emulator) and my program was working fine. I even tested it with HyperTerminal and that seemed to work fine too.
However when I interfaced the software with the original device (an output received from a control system), the data received was garbled. It contained special characters. The same device when connected with Hyper Terminal produced the desired output. I changed the baud rates, parity etc but the data received was the same set of garbage characters.
I have used the DataReceived event of the SerialPort component and used the following line of code to capture data:
string data = portRecieve.ReadExisting();
Can somebody tell me where am i missing out? In the current environment, the output from the device is directly connected with a dot matrix printer which prints whatever is received on the port. The printer seems to catch what is being sent but my code couldn't.
If you ever encountered a similar scenario, Please share your findings.
Thanks
How did you set
SerialPort.DiscardNull
SerialPort.Encoding
And maybe show us an example of the special chars you are receiving.
I can think of the following reasons why the data might apperar garbled:
If there is a bad physical connection, you can sometimes just get garbage (rather than nothing at all). Try unplugging and replugging the leads - and check that you have the correct lead (e.g. do you need a nullmodem?). It looks as though you have this covered by checking in HyperTerminal.
If the baud rate, stop bits, parity are not correct - sounds like you have this one covered
You are trying to receive the data as a string. If it is not sent as plain text, or if your encoding is wrong, then it could easily appear garbage-like. Try using a binary receive and examine the raw data that you are receiving. This will tell you whether the data is just wrong or the .net conversion is screwing it up - eliminate the middle man!
It sounds to me like the device is putting the printer into some special graphics mode. If so, there is likely to be escape sequences in the data being sent to the printer, ie. character sequences starying with an escape (27, 0x1B) character.
In this case, you'll have to look at the printer manual to see what the commands do. Alternatively, you might be able to tell the device to use a simple ASCII only printer, rather than a intellifent one.

Categories

Resources