Send and receive over serial port doesn't work - c#

I am new at programming.
I am making a terminal program for some testing, the program has to send and receive data over serial-null modem. I found an example at MSDN: http://msdn.microsoft.com/en-us/library/y2sxhat8.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-2
But I cant get it to work. Here is what I have now:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO.Ports;
using System.Threading;
namespace Terminal_0._0._0._2
{
class Program
{
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
SerialPort _serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = "COM8";
_serialPort.BaudRate = 115200;
_serialPort.Parity = Parity.None;
_serialPort.DataBits = 8;
_serialPort.StopBits = StopBits.One;
_serialPort.Handshake = Handshake.None;
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
var _continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
}
I get this error:
Expected class, delegate, enum, interface, or struct
on line: 66
Column: 19
Thanks in advance.

As far as I can tell, there may be several things causing it not to work.
First of all, the Read method is outside the Program scope, resulting in it not working.
Secondly, moving it inside won't work either, until you also make "_continue" and "_serialPort" fields (outside methods).
Reworked code (removed redundant 'using' statements):
using System;
using System.IO.Ports;
using System.Threading;
namespace Terminal_0._0._0._2
{
class Program
{
private static bool _continue;
private static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
var readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort
{
PortName = "COM8",
BaudRate = 115200,
Parity = Parity.None,
DataBits = 8,
StopBits = StopBits.One,
Handshake = Handshake.None,
ReadTimeout = 500,
WriteTimeout = 500
};
// Allow the user to set the appropriate properties.
// Set the read/write timeouts
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
}
}
Since I don't have any serial devices, I can't test it, but the compiler compiled it without errors.
Thanks
Bjarke

Related

Cannot send midi note out using NAudio and teVirtualMIDI

I am trying to send a Midi Note On message out to DAW software using NAudio, with a virtual port created by teVirtualMIDI. I am able to see the "device" created by teVirtualMIDI in Ableton Live 10, but have been unsuccessful in receiving any information in Live. My sound is turned up, and I never see Live's Midi meter move. The Code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NAudio.Midi;
using TobiasErichsen.teVirtualMIDI;
namespace BDBConsole_1_0
{
public class BDBMidiClient
{
public static ConsoleKeyInfo cKi;
public static TeVirtualMIDI port;
static MidiOut midiOut;
int midiOutIndex;
//public static List<MidiEvent> noteEvent;
static void Main(string[] args)
{
CreateMidiPort();
}
public static void CreateMidiPort()
{
TeVirtualMIDI.logging(TeVirtualMIDI.TE_VM_LOGGING_MISC | TeVirtualMIDI.TE_VM_LOGGING_RX | TeVirtualMIDI.TE_VM_LOGGING_TX);
string portName = "BDB Client";
//port = new TeVirtualMIDI(portName, 65535, TeVirtualMIDI.TE_VM_FLAGS_INSTANTIATE_BOTH);
port = new TeVirtualMIDI(portName);
Console.WriteLine("New Midi Port Opened...");
Console.ReadKey();
EnumerateMidiOutDevices();
Thread thread = new Thread(new ThreadStart(SendNextMidiOutMessage));
thread.Start();
//SendNextMidiOutMessage();
}
public static void EnumerateMidiOutDevices()
{
int noOutDevices = MidiOut.NumberOfDevices;
Console.WriteLine("No. of Midi Out Devices..." + noOutDevices);
Console.ReadKey();
string deviceOutOne = MidiOut.DeviceInfo(1).ProductName;
Console.WriteLine("Device One..." + deviceOutOne);
Console.ReadKey();
}
public static void SendNextMidiOutMessage()
{
midiOut = new MidiOut(deviceNo: 0);
//events = new List<MidiEvent>();
int channel = 1;
int note = 64;
var noteOnEvent = new NoteOnEvent(0, channel, note, 127, 1000);
try
{
//while (true) loop here before
do
{
Console.WriteLine("Send Midi Note...");
cKi = Console.ReadKey();
midiOut.Send(noteOnEvent.GetAsShortMessage());
Console.WriteLine("Note Sent...");
cKi = Console.ReadKey();
} while (cKi.Key != ConsoleKey.Escape);
port.shutdown();
Console.WriteLine("Midi Port Closed...");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine("thread aborting: " + ex.Message);
}
}
}
}
Any Help with this would be greatly appreciated!

How to use c# methods with serial port in asp .net core?

I have a task to create web app with ASP .NET core 2.0 where you can communicate with modem and send SMS using AT command. I have a piece of code which can send messages using Serial Port but ASP doesn't have this library so how can I use this code in ASP .NET?
Method:
private SerialPort _serialPort;
public void SendSms()
{
Console.WriteLine("Write phone number");
string phoneNr = Console.ReadLine();
Console.WriteLine("Write message");
string message = Console.ReadLine();
_serialPort = new SerialPort("COM2", 9600);
Thread.Sleep(1000);
_serialPort.Open();
Thread.Sleep(1000);
_serialPort.Write("AT+CMGF=1\r");
Thread.Sleep(1000);
_serialPort.Write("AT+CMGS=\"" + phoneNr + "\"\r\n");
Thread.Sleep(1000);
_serialPort.Write(message + "\x1A");
Thread.Sleep(1000);
_serialPort.Close();
}
Also in my app I have chat window so I want to use input box and button to write and send SMS.
<form method="post">
<input asp-for="MessageBody" id="textInput" type="text" placeholder="Enter message..." class="form-control " />
<button asp-action="SendMessage" id="sendButton" class="btn btn-primary btn-block" type="submit">Send</button>
</form>
For now SendMessage only saves message into database.
Sorry if my question is formulated not in the best way, writing here for the first time.
Can you try to add "\n" in this line.
_serialPort.Write("AT+CMGF=1\r");
It should be something like this
_serialPort.Write("AT+CMGF=1\r\n");
Here is the documentation you are looking for Serial port communication in .net core
Example from the link for completeness:
using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message));
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
// Display Port values and prompt user to enter a port.
public static string SetPortName(string defaultPortName)
{
string portName;
Console.WriteLine("Available Ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter COM port value (Default: {0}): ", defaultPortName);
portName = Console.ReadLine();
if (portName == "" || !(portName.ToLower()).StartsWith("com"))
{
portName = defaultPortName;
}
return portName;
}
// Display BaudRate values and prompt user to enter a value.
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
Console.Write("Baud Rate(default:{0}): ", defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == "")
{
baudRate = defaultPortBaudRate.ToString();
}
return int.Parse(baudRate);
}
// Display PortParity values and prompt user to enter a value.
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
Console.WriteLine("Available Parity options:");
foreach (string s in Enum.GetNames(typeof(Parity)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter Parity value (Default: {0}):", defaultPortParity.ToString(), true);
parity = Console.ReadLine();
if (parity == "")
{
parity = defaultPortParity.ToString();
}
return (Parity)Enum.Parse(typeof(Parity), parity, true);
}
// Display DataBits values and prompt user to enter a value.
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
Console.Write("Enter DataBits value (Default: {0}): ", defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == "")
{
dataBits = defaultPortDataBits.ToString();
}
return int.Parse(dataBits.ToUpperInvariant());
}
// Display StopBits values and prompt user to enter a value.
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
Console.WriteLine("Available StopBits options:");
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter StopBits value (None is not supported and \n" +
"raises an ArgumentOutOfRangeException. \n (Default: {0}):", defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == "" )
{
stopBits = defaultPortStopBits.ToString();
}
return (StopBits)Enum.Parse(typeof(StopBits), stopBits, true);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
string handshake;
Console.WriteLine("Available Handshake options:");
foreach (string s in Enum.GetNames(typeof(Handshake)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Enter Handshake value (Default: {0}):", defaultPortHandshake.ToString());
handshake = Console.ReadLine();
if (handshake == "")
{
handshake = defaultPortHandshake.ToString();
}
return (Handshake)Enum.Parse(typeof(Handshake), handshake, true);
}
}

C# changing variables from different cs file and serial reading

Hi I'm new to programming and new to even more newer at C#.
I wanted to create a second file to make everything look a bit cleaner but it doesn't work out.
It's an UWP background project for a RP3 running Windows 10 IoT core.
I want to make a webserver that can be accessed by an app but I haven't made that code yet, obviously.
Now I'm trying to figure out the connection between the Arduino and the RP. It works perfectly for the most part.
But I wanted to make it look better so I wanted to put all the sensor stuff in a different file but I can't access or change any variable.
For example, I want to change clState to true/false, I can't do that.
Another problem I have is that when the arduino sends a single string through serial, the RP receives it and it works perfectly but if I send multiple strings (for example multiple Serial.write) it receives it but my code that checks if it's correct only works for on of the strings... I suspect it has something to do with the asynchronous stuff but I don't know how to fix it. But that is less important.
rcvdText = dataReaderObject.ReadString(bytesRead);
Debug.WriteLine("Debug: Succesvol gelezen van Arduino");
Debug.WriteLine(rcvdText);
char startMarker = '<';
char endMarker = '>';
if (rcvdText.Contains(startMarker) == true && rcvdText.Contains(endMarker) == true)
{
int startIndex = rcvdText.IndexOf(startMarker) + 1;
int endIndex = rcvdText.IndexOf(endMarker) - 1;
receivedChars = rcvdText.Substring(startIndex, endIndex);
Debug.WriteLine(receivedChars);
CheckNewData();
}
All help is very much appreciated! :)
Sorry the indentation failed when copying... And I think I didn't follow the naming convention...
This is the main file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Http;
using Windows.ApplicationModel.Background;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
using System.Diagnostics;
using System.Threading.Tasks;
using Windows.Networking.Sockets;
using Windows.ApplicationModel.AppService;
using Windows.Storage.Streams;
using System.Runtime.InteropServices.WindowsRuntime;
namespace ArduinoData
{
public sealed class StartupTask : IBackgroundTask
{
//public bool clState;
public ArduinoConnect test2 = new ArduinoConnect();
BackgroundTaskDeferral serviceDeferral;
public void Run(IBackgroundTaskInstance taskInstance)
{
serviceDeferral = taskInstance.GetDeferral();
BackgroundTaskDeferral arduinoDeferral = taskInstance.GetDeferral();
//ArduinoConnect test = new ArduinoConnect();
test2.WatchDevice();
Test();
test2.clState = false;
}
}
}
And this is ArduinoConnect.cs
using System;
using System.Linq;
using Windows.Devices.Enumeration;
using Windows.Devices.SerialCommunication;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Storage.Streams;
namespace ArduinoData
{
public sealed class ArduinoConnect
{
DataReader dataReaderObject = null;
private SerialDevice serialPort = null;
private CancellationTokenSource ReadCancellationTokenSource;
private string rcvdText;
private string receivedChars;
//variabelen voor status
private bool clState;
private bool phPlusState;
private bool phMinState;
private bool pompState;
private bool lampenState;
private bool warmteState;
private bool vulState;
private bool waterState;
private byte dekState;
public void WatchDevice()
{
UInt16 vid = 0x2341;
UInt16 pid = 0x0001;
string aqs = SerialDevice.GetDeviceSelectorFromUsbVidPid(vid, pid);
var Watcher = DeviceInformation.CreateWatcher(aqs);
Watcher.Added += new TypedEventHandler<DeviceWatcher, DeviceInformation>(DeviceAdded);
Watcher.Removed += new TypedEventHandler<DeviceWatcher, DeviceInformationUpdate>(OnDeviceRemoved);
Watcher.Start();
}
private async void DeviceAdded(DeviceWatcher watcher, DeviceInformation device)
{
Debug.WriteLine("Debug: Apparaat gevonden! :)");
try
{
serialPort = await SerialDevice.FromIdAsync(device.Id);
Debug.WriteLine("Debug: " + device.Name + " verbonden!!! :D");
serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
serialPort.BaudRate = 9600;
serialPort.Parity = SerialParity.None;
serialPort.StopBits = SerialStopBitCount.One;
serialPort.DataBits = 8;
serialPort.Handshake = SerialHandshake.None;
Debug.WriteLine("Debug: Seriële poort succesvol geconfigureerd! :D");
ReadCancellationTokenSource = new CancellationTokenSource();
}
catch
{
Debug.WriteLine("Debug: Fout bij Seriële poort configureren. :(");
}
Listen();
}
private async void Listen()
{
try
{
Debug.WriteLine("Debug: Listen() function");
if (serialPort != null)
{
dataReaderObject = new DataReader(serialPort.InputStream);
// keep reading the serial input
while (true)
{
await ReadAsync(ReadCancellationTokenSource.Token);
}
}
}
catch (TaskCanceledException)
{
Debug.WriteLine("Reading task was cancelled, closing device and cleaning up");
CloseDevice();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
// Cleanup once complete
if (dataReaderObject != null)
{
dataReaderObject.DetachStream();
dataReaderObject = null;
}
}
}
private async Task ReadAsync(CancellationToken cancellationToken)
{
Task<UInt32> loadAsyncTask;
uint ReadBufferLength = 1024;
// If task cancellation was requested, comply
cancellationToken.ThrowIfCancellationRequested();
// Set InputStreamOptions to complete the asynchronous read operation when one or more bytes is available
dataReaderObject.InputStreamOptions = InputStreamOptions.Partial;
using (var childCancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken))
{
// Create a task object to wait for data on the serialPort.InputStream
loadAsyncTask = dataReaderObject.LoadAsync(ReadBufferLength).AsTask(childCancellationTokenSource.Token);
// Launch the task and wait
UInt32 bytesRead = await loadAsyncTask;
if (bytesRead > 0)
{
rcvdText = dataReaderObject.ReadString(bytesRead);
Debug.WriteLine("Debug: Succesvol gelezen van Arduino");
Debug.WriteLine(rcvdText);
char startMarker = '<';
char endMarker = '>';
if (rcvdText.Contains(startMarker) == true && rcvdText.Contains(endMarker) == true)
{
int startIndex = rcvdText.IndexOf(startMarker) + 1;
int endIndex = rcvdText.IndexOf(endMarker) - 1;
receivedChars = rcvdText.Substring(startIndex, endIndex);
Debug.WriteLine(receivedChars);
CheckNewData();
}
}
}
}
private void CheckNewData()
{
switch (receivedChars)
{
case "CL_STATE=0" :
clState = false;
break;
case "CL_STATE=1" :
clState = true;
break;
case "PHPLUS_STATE=0" :
phPlusState = false;
break;
case "PHPLUS_STATE=1" :
phPlusState = true;
break;
case "POMP_STATE=0" :
pompState = false;
break;
case "POMP_STATE=1" :
pompState = false;
break;
case "LAMPEN_STATE=0" :
lampenState = false;
break;
case "LAMPEN_STATE=1" :
lampenState = true;
break;
case "VUL_STATE=0" :
vulState = false;
break;
case "VUL_STATE=1" :
vulState = true;
break;
case "WATER_STATE=0" :
waterState = false;
break;
case "WATER_STATE=1" :
waterState = true;
break;
case "DEK_STATE=0" :
dekState = 0;
break;
case "DEK_STATE=1" :
dekState = 1;
break;
case "DEK_STATE=2" :
dekState = 2;
break;
case "REFRESH=1" :
Debug.WriteLine("Debug: Refresh uitgevoerd!");
break;
default:
Debug.WriteLine("Debug: Fout commando!");
break;
}
}
private void OnDeviceRemoved(DeviceWatcher sender, DeviceInformationUpdate device)
{
Debug.WriteLine("Debug: Apparaat losgekoppeld.");
try
{
CancelReadTask();
CloseDevice();
}
catch(Exception ex)
{
Debug.WriteLine("Debug: " + ex.Message);
}
}
private void CancelReadTask()
{
if (ReadCancellationTokenSource != null)
{
if (!ReadCancellationTokenSource.IsCancellationRequested)
{
ReadCancellationTokenSource.Cancel();
}
}
}
private void CloseDevice()
{
if (serialPort != null)
{
serialPort.Dispose();
}
serialPort = null;
rcvdText = "";
}
}
}
EDIT
I have a new problem with this code I had the same problem sometimes with my old code above...
Error
Exception thrown: 'System.ArgumentOutOfRangeException' in System.Private.CoreLib.ni.dll
Index and length must refer to a location within the string.
Parameter name: length
I can't paste it correctly, it's annoying...
if (bytesRead > 0)
{
rcvdText = dataReaderObject.ReadString(bytesRead);
Debug.WriteLine("Debug: Succesvol gelezen van Arduino");
Debug.WriteLine(rcvdText);
//char startMarker = '<';
//char endMarker = '>';
int i = 0;
foreach (var ch in rcvdText)
{
//if (ch != '\u+003C') continue;
if (ch == '\u003C')
{
StartIndex = i + 1;
Debug.WriteLine(StartIndex);
}
if (ch == '\u003E')
{
EndIndex = i - 1;
Debug.WriteLine(EndIndex);
receivedChars = rcvdText.Substring(StartIndex, EndIndex);
Debug.WriteLine(receivedChars);
StartIndex = 0;
EndIndex = 0;
}
i++;
Debug.WriteLine("test");
}
Debug.WriteLine("finished");
}
And the Debug output:
Debug: Succesvol gelezen van Arduino
<WATER_STATE=1>
<WATER_STATE=0>
1
test
test
test
test
test
test
test
test
test
test
test
test
test
test
13
WATER_STATE=1
test
test
test
18
test
test
test
test
test
test
test
test
test
test
test
test
test
test
30
Exception thrown: 'System.ArgumentOutOfRangeException' in System.Private.CoreLib.ni.dll
test2
Index and length must refer to a location within the string.
Parameter name: length
test2
The program '[2888] backgroundTaskHost.exe' has exited with code -1 (0xffffffff).
EDIT2 I figured it out, I'm an idiot...
But I wanted to make it look better so I wanted to put all the sensor
stuff in a different file but I can't access or change any variable.
For example, I want to change clState to true/false, I can't do that.
You can using auto-implementing properties like this:
public bool clState { get; set; }
More information you can reference here.

Way to close TCP Connection and Exit Application

This is a TCP Program which receives data from a TCP connection, then parse it and transfer it to another TCP connection. When I exit application, it doesn't work. It will remain as a process in the system.
As I am not a very experienced developer, can someone please help me to find the error in this code..
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Net.Sockets;
using System.IO;
using System.Threading;
namespace Machine_Feeder
{
public partial class FeederControlMonitor : Form
{
TcpListener Listener = null;
public string Status = string.Empty;
public Thread T = null;
public FeederControlMonitor()
{
InitializeComponent();
}
private void FeederControlMonitor_Load(object sender, EventArgs e)
{
txtStatus.Text = "Feeder waiting for data...";
ThreadStart Ts = new ThreadStart(StartReceiving);
T = new Thread(Ts);
T.Start();
}
public void StartReceiving()
{
ReceiveTCP(9100);
}
public void ReceiveTCP(int portN)
{
try
{
Listener = new TcpListener(IPAddress.Any, portN);
Listener.Start();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
Console.WriteLine(ex.Message);
}
try
{
while (true)
{
Socket client = Listener.AcceptSocket();
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[10000];
int size = client.Receive(data);
ParseData(System.Text.Encoding.Default.GetString(data));
client.Close();
});
childSocketThread.Start();
}
Listener.Stop();
}
catch (Exception ex)
{
File.WriteAllText(#"C:\\Drive\\ex.txt", ex.Message);
}
}
public void ParseData(string data)
{
var useFulData = data.Substring(data.IndexOf("F1")).Replace(" ", " ");// Space
useFulData = useFulData.Remove(useFulData.IndexOf("<ETX>"));
string[] delimeters = { "<DEL>", "<ESC>" };
var listOfValues = useFulData.Split(delimeters, StringSplitOptions.None).ToList();
int pos = 0;
for (int i = 1; i < listOfValues.Count; i += 2, pos++)
{
listOfValues[pos] = listOfValues[i];
}
listOfValues.RemoveRange(pos, listOfValues.Count - pos);
txtHealthCard.Invoke((Action)delegate { txtHealthCard.Text = listOfValues[0]; });
txtCID.Invoke((Action)delegate { txtCID.Text = listOfValues[1]; });
txtMedicalFitLocation.Invoke((Action)delegate { txtMedicalFitLocation.Text = listOfValues[2]; });
txtGender.Invoke((Action)delegate { txtGender.Text = listOfValues[3]; });
txtAge.Invoke((Action)delegate { txtAge.Text = listOfValues[4]; });
txtPatientName.Invoke((Action)delegate { txtPatientName.Text = listOfValues[5]; });
MyProtocolMaker(listOfValues[5],
listOfValues[4],
listOfValues[2],
listOfValues[3],
listOfValues[8],
listOfValues[1],
listOfValues[10],
);
}
private void btnExit_Click(object sender, EventArgs e)
{
Listener.Stop();
T.Abort();
this.Close();
}
private void MyProtocolMaker(
string patientName,
string patientAge,
string mfitLocation,
string gender,
string healthCardNo,
)
{
string feederInfo = "^^^P^PI" + healthCardNo + "^PN" + patientName + "^PA" + patientAge + "^PS" + gender + "^P7" + mfitLocation +"^_SS^^^_S";
System.Net.Sockets.TcpClient clientSocket = new System.Net.Sockets.TcpClient("127.0.0.1", 8001);
NetworkStream serverStream = clientSocket.GetStream();
byte[] outStream = System.Text.Encoding.ASCII.GetBytes(feederInfo);
serverStream.Write(outStream, 0, outStream.Length);
serverStream.Flush();
serverStream.Close();
clientSocket.Close();
}
private void FeederControlMonitor_FormClosing(object sender, FormClosingEventArgs e)
{
Listener.Stop();
T.Abort();
this.Close();
}
}
}
You problem is, that you are creating threads within the thread. These threads are keeping the application alive. Try marking them as background threads: (This is red-tape solution)
var childSocketThread = new Thread(() =>
{
byte[] data = new byte[10000];
int size = client.Receive(data); // <-- the thread hangs on these and will block termination
ParseData(System.Text.Encoding.Default.GetString(data));
client.Close();
});
childSocketThread.IsBackground = true; // <---
childSocketThread.Start();
When thread are not marked as background (default), they will block application termination. You should create a list to store the client threads, so you can exit those threads nicely.
You should never abort a thread, unless there is no other way. Instead of aborting, you should exit the while loop in the thread.
As nice way is using a ManualResetEvent:
fields:
private ManualResetEvent _terminating = new ManualResetEvent(false);
in thread:
while (_terminating.WaitOne(0))
{
// thread code
}
on exit:
_terminating.Set();
T.Join();
Sidenote: TCP is streaming, so just reading 10k of bytes ones, does not guarantee a complete packet.

How to Communicate with digital scale using C#

I have a matrix d1000+ digital scale. I want it's weight in my application using c# but I have no idea how to do this. It is connected with my computer through rs232.
I am using this code but weight is shown incorrect format like 1+e00023 please tell me what can i do to correct it.
public partial class ManageSale : Form
{
private SerialPort port = new SerialPort(
"COM1", 4800, Parity.None,8, StopBits.One);
public ManageSale()
{
InitializeComponent();
port.DataReceived +=
new SerialDataReceivedEventHandler(port_DataReceived);
port.Open();
port.DtrEnable = true;
port.RtsEnable = true;
}
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
this.label1.Text = port.ReadExisting();
}
private void ManageSale_Load(object sender, EventArgs e)
{
port.WriteLine("5");
}
}
hi evryone my problem is still there plese help me to solve this problem see my code where i am wrong please tell me how to correct it.
Contact the manufacturer, and ask for the API kit. You'll probably have to link against a dll written in C / C++, using a DllImport statement. Working out the proper data types between C / C++ can be time consuming, but is doable.
See the Serial Port Api in the .Net Framework. There's an example there:
using System;
using System.IO.Ports;
using System.Threading;
public class PortChat
{
static bool _continue;
static SerialPort _serialPort;
public static void Main()
{
string name;
string message;
StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
Thread readThread = new Thread(Read);
// Create a new SerialPort object with default settings.
_serialPort = new SerialPort();
// Allow the user to set the appropriate properties.
_serialPort.PortName = SetPortName(_serialPort.PortName);
_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
_serialPort.Parity = SetPortParity(_serialPort.Parity);
_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);
// Set the read/write timeouts
_serialPort.ReadTimeout = 500;
_serialPort.WriteTimeout = 500;
_serialPort.Open();
_continue = true;
readThread.Start();
Console.Write("Name: ");
name = Console.ReadLine();
Console.WriteLine("Type QUIT to exit");
while (_continue)
{
message = Console.ReadLine();
if (stringComparer.Equals("quit", message))
{
_continue = false;
}
else
{
_serialPort.WriteLine(
String.Format("<{0}>: {1}", name, message) );
}
}
readThread.Join();
_serialPort.Close();
}
public static void Read()
{
while (_continue)
{
try
{
string message = _serialPort.ReadLine();
Console.WriteLine(message);
}
catch (TimeoutException) { }
}
}
public static string SetPortName(string defaultPortName)
{
string portName;
Console.WriteLine("Available Ports:");
foreach (string s in SerialPort.GetPortNames())
{
Console.WriteLine(" {0}", s);
}
Console.Write("COM port({0}): ", defaultPortName);
portName = Console.ReadLine();
if (portName == "")
{
portName = defaultPortName;
}
return portName;
}
public static int SetPortBaudRate(int defaultPortBaudRate)
{
string baudRate;
Console.Write("Baud Rate({0}): ", defaultPortBaudRate);
baudRate = Console.ReadLine();
if (baudRate == "")
{
baudRate = defaultPortBaudRate.ToString();
}
return int.Parse(baudRate);
}
public static Parity SetPortParity(Parity defaultPortParity)
{
string parity;
Console.WriteLine("Available Parity options:");
foreach (string s in Enum.GetNames(typeof(Parity)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Parity({0}):", defaultPortParity.ToString());
parity = Console.ReadLine();
if (parity == "")
{
parity = defaultPortParity.ToString();
}
return (Parity)Enum.Parse(typeof(Parity), parity);
}
public static int SetPortDataBits(int defaultPortDataBits)
{
string dataBits;
Console.Write("Data Bits({0}): ", defaultPortDataBits);
dataBits = Console.ReadLine();
if (dataBits == "")
{
dataBits = defaultPortDataBits.ToString();
}
return int.Parse(dataBits);
}
public static StopBits SetPortStopBits(StopBits defaultPortStopBits)
{
string stopBits;
Console.WriteLine("Available Stop Bits options:");
foreach (string s in Enum.GetNames(typeof(StopBits)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Stop Bits({0}):", defaultPortStopBits.ToString());
stopBits = Console.ReadLine();
if (stopBits == "")
{
stopBits = defaultPortStopBits.ToString();
}
return (StopBits)Enum.Parse(typeof(StopBits), stopBits);
}
public static Handshake SetPortHandshake(Handshake defaultPortHandshake)
{
string handshake;
Console.WriteLine("Available Handshake options:");
foreach (string s in Enum.GetNames(typeof(Handshake)))
{
Console.WriteLine(" {0}", s);
}
Console.Write("Handshake({0}):", defaultPortHandshake.ToString());
handshake = Console.ReadLine();
if (handshake == "")
{
handshake = defaultPortHandshake.ToString();
}
return (Handshake)Enum.Parse(typeof(Handshake), handshake);
}
}

Categories

Resources