Cannot send midi note out using NAudio and teVirtualMIDI - c#

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!

Related

How to send messages from Cloud to Device with IOT Hub?

I have tried to receive cloud to device message through IOT Hub using the steps mentioned in the link below:
https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-c2d
I have attached the code that I am using and the result I am getting.
In the simulated device app, I am calling this method "ReceiveMessageAsync()".
I have updated the screenshot of the output that I am getting.
After entering the "Enter", I am not getting any output.
After decoding the code, I could see that in the ReceiveMessageAsync() method, I am getting receivedMessage == null.
Please help me with this code and suggest the changes that I should make to make it work perfectly.
=======================================
public async void ReceiveMessageAsync()
{
try
{
Message receivedMessage = await _deviceClient?.ReceiveAsync();
if(receivedMessage == null)
{
ReceivedMessage = null;
return;
}
ReceivedMessage = Encoding.ASCII.GetString(receivedMessage.GetBytes());
if(double.TryParse(ReceivedMessage, out var requestedNoise))
{
ReceivedNoiseSetting = requestedNoise;
}
else
{
ReceivedNoiseSetting = null;
}
await _DeviceClient?.CompleteAsync(receivedMessage);
}
catch (NullReferenceException ex)
{
System.Diagnostics.Debug.WriteLine("The DeviceClient is null.");
}
}
==================================================
using System;
using Ststem.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;
using System.Linq;
namespace SendCloudToDevice
{
internal class Program
{
static ServiceClient serviceClient;
static string connectionString = "<connectionString>";
static string targetDevice = "<deviceID>";
public static async Task Main(String[] args)
{
console.WriteLine("Send Cloud to device Message");
serviceClient = ServiceClient.CreateFromConnectionString(connectionString);
ReceiveFeedbackAsync();
Console.WriteLine("Press any key to send C2D mesage.");
Console.ReadLine();
sendCloudToDeviceMessageAsync().Wait();
Console.ReadLine();
}
private async static Task SendCloudToDeviceMessageAsync()
{
var commandMessage = new Message(Encoding.ASCII.GetBytes("Cloud to device message."));
commandMessage.Ack = DeliveryAcknowledgement.Full;
await serviceClient.sendAsync(targetDevice,commandMessage);
}
private async static void ReceiveFeedbackAsync()
{
var feedbackReceiver = serviceClient.GetFeedbackReceiver();
Console.WriteLine("\n Receiving c2d feedback from service");
while (true)
{
var feedbackBatch = await feedbackReceiver.ReceiveAsync();
if(feedbackBatch == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received feedback: {0}",string.Join(", ", feedbackBatch.Recorfds.Select(f => f.StatusCode)));
Console.ResetColor();
await feedbackReceiver.CompleteAsync(feedbackBatch);
}
}
}
}
[1]: https://i.stack.imgur.com/sS8N0.jpg![enter image description here](https://i.stack.imgur.com/THylN.jpg)
If you just want to send messages to a device and get messages from a device, try the code below:
using System;
using System.Threading.Tasks;
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices;
using System.Linq;
using System.Text;
namespace SendCloudToDevice
{
internal class Program
{
public static void Main(String[] args)
{
var deviceConnStr = "";
var serviceClientStr = "";
//sned a new message from could to device
var serviceClient = ServiceClient.CreateFromConnectionString(serviceClientStr);
var messageContent = "Hello! This is a message from Cloud!";
var commandMessage = new Microsoft.Azure.Devices.Message(Encoding.ASCII.GetBytes(messageContent));
serviceClient.SendAsync("<deviceID here>", commandMessage).GetAwaiter().GetResult();
Console.WriteLine("sent message to device,content : "+ messageContent);
//device receive messages from cloud
var deviceClient = DeviceClient.CreateFromConnectionString(deviceConnStr);
Console.WriteLine("\nReceiving cloud to device messages from service");
while (true)
{
var receivedMessage = deviceClient.ReceiveAsync().GetAwaiter().GetResult();
if (receivedMessage == null) continue;
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("Received message: {0}",
Encoding.ASCII.GetString(receivedMessage.GetBytes()));
Console.ResetColor();
deviceClient.CompleteAsync(receivedMessage).GetAwaiter().GetResult();
}
}
}
}
Result:
You can also send messages from Portal:

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.

Visual Studio 2013 C# compile with /main

I'm new to programming and I'm trying to write a code for a port scanner. When I click Build I'm getting the following error messages...I realize it's the same error just in two different locations, but I figured it would hurt to list both:
Error 1 Program 'c:\Users\pat_000\Documents\Visual Studio 2013\Projects\WpfApplication2\WpfApplication2\obj\Debug\WpfApplication2.exe' has more than one entry point defined: 'PortScanner.Program.Main(string[])'. Compile with /main to specify the type that contains the entry point.
Error 2 Program 'c:\Users\pat_000\Documents\Visual Studio 2013\Projects\WpfApplication2\WpfApplication2\obj\Debug\WpfApplication2.exe' has more than one entry point defined: 'WpfApplication2.App.Main()'. Compile with /main to specify the type that contains the entry point.
Here is my code:
enter code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Threading;
using System.Net.Sockets;
using System.Net;
namespace PortScanner
{
class Program
{
static bool stop = false;
static int startPort;
static int endPort;
static List<int> openPorts = new List<int>();
static object consoleLock = new object();
static int waitingForResponses;
static int maxQueriesAtOneTime = 100;
static void Main(string[] args)
{
begin:
Console.WriteLine("Enter the IP Address of the target:");
string ip = Console.ReadLine();
IPAddress ipAddress;
if (!IPAddress.TryParse(ip, out ipAddress))
goto begin;
startP:
Console.WriteLine("Enter the starting port to start scanning on:");
string sp = Console.ReadLine();
if (!int.TryParse(sp, out startPort))
goto startP;
endP:
Console.WriteLine("Enter the end port:");
string ep = Console.ReadLine();
if (!int.TryParse(ep, out endPort))
goto endP;
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("");
Console.WriteLine("Press any key to stop scanning...");
Console.WriteLine("");
Console.WriteLine("");
ThreadPool.QueueUserWorkItem(StartScan, ipAddress);
Console.ReadKey();
stop = true;
Console.WriteLine("Press any key to exit...");
Console.ReadKey();
}
static void StartScan(object o)
{
IPAddress ipAddress = o as IPAddress;
for (int i = startPort; i < endPort; i++)
{
lock (consoleLock)
{
int top = Console.CursorTop;
Console.CursorTop = 7;
Console.WriteLine("Scanning port: {0} ", i);
Console.CursorTop = top;
}
while (waitingForResponses >= maxQueriesAtOneTime)
Thread.Sleep(0);
if (stop)
break;
try
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
s.BeginConnect(new IPEndPoint(ipAddress, i), EndConnect, s);
Interlocked.Increment(ref waitingForResponses);
}
catch (Exception)
{
}
}
}
static void EndConnect(IAsyncResult ar)
{
try
{
DecrementResponses();
Socket s = ar.AsyncState as Socket;
s.EndConnect(ar);
if (s.Connected)
{
int openPort = Convert.ToInt32(s.RemoteEndPoint.ToString().Split(':')[1]);
openPorts.Add(openPort);
lock (consoleLock)
{
Console.WriteLine("Connected TCP on port: {0}", openPort);
}
s.Disconnect(true);
}
}
catch (Exception)
{
}
}
static void IncrementResponses()
{
Interlocked.Increment(ref waitingForResponses);
PrintWaitingForResponses();
}
static void DecrementResponses()
{
Interlocked.Decrement(ref waitingForResponses);
PrintWaitingForResponses();
}
static void PrintWaitingForResponses()
{
lock (consoleLock)
{
int top = Console.CursorTop;
Console.CursorTop = 8;
Console.WriteLine("Waiting for responses from {0} sockets ", waitingForResponses);
Console.CursorTop = top;
}
}
}
}
namespace WpfApplication2
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
You obviously want to write a ConsoleApplication. You picked WpfApplication. Copy your whole code, create a new project based on ConsoleApplication and paste your code there.
And try to get rid of the gotos; it's not BASIC. You could easily make a single function for all your three uses.
Try looking in your other solution files to see if there's another Main() defined somewhere else that is just confusing the compiler.
In a WPF application, Main() is automatically created for you. Since you also provided your own, that is why you are getting the conflict. To fix this:
Right-click App.xaml in the solution explorer, select Properties
Change 'Build Action' to 'Page'

Socket Timeout at runtime [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Hey guys I am new at the subject of Sockets
and I really need you help.
I am doing system of server and clients (like chat)
but something diffrent, I am doing it with Windows Form Application
in my server : I have list of sockets of all pepole that connect to the server, that already get acception from the server.
And I wanna to do a Timer that every X seconds it will runs on my List and check if the person is still connection I mean in that , that the person still connect on the internet and still can get packages and if not to remove him from the list.
someone can help me in c# how do it??
now at the server if someone is Exit the program Or if the internet is logout how i can check if the Client is out
and if yes so Close his connection?
i Read about TimeOut but how use it??? if it usfull?
Server:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Server
{
public partial class Form1 : Form
{
Socket sck;
static List<Socket> acc;
static List<Thread> thr;
//List<UserAt> thr;
static int port = 9000;
static IPAddress ip;
static Thread NewCon;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
acc = new List<Socket>();
//thr = new List<UserAt>();
thr = new List<Thread>();
NewCon = new Thread(getNewConnection);
//Console.WriteLine("please enter your host port ");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
ip = IPAddress.Parse("127.0.0.1");
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Bind(new IPEndPoint(ip, port));
sck.Listen(0);
NewCon.Start();
}
/// <summary>
/// get new connection from client
/// </summary>
public void getNewConnection()
{
while (true)
{
acc.Add(sck.Accept());
var t = new Thread(() => ReciveMessage(acc.Count-1));
t.Start();
thr.Add(t);
/* UserAt a = new UserAt();
a.index = acc.Count - 1;
a.thread = new Thread(() => ReciveMessage(a.index));
a.thread.Start();
thr.Add(a);
* */
}
}
public void ReciveMessage(int index)
{
while (true)
{
try
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = acc[index].Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
//MessageBox.Show(Encoding.Default.GetString(Buffer));
//listBox1.Items.Add(Encoding.Default.GetString(Buffer));
SetText(Encoding.Default.GetString(Buffer));
}
catch
{
// thr[index].thread.Abort();
/*thr.RemoveAt(index);
for (int i = index+1; i < thr.Count;i++ )
{
thr[i].index -= 1;
}*/
break;
}
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.listBox1.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.listBox1.Items.Add(text);
}
}
public string getIp()
{
IPHostEntry host;
string localIP = "?";
host = Dns.GetHostEntry(Dns.GetHostName());
foreach (IPAddress ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
localIP = ip.ToString();
}
}
return localIP;
}
}
}
Client
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Client
{
public partial class Form1 : Form
{
static string name = "";
static int port = 9000;
static IPAddress ip;
static Socket sck;
public Form1()
{
InitializeComponent();
}
public void ReciveMessage()
{
while (true)
{
Thread.Sleep(500);
byte[] Buffer = new byte[255];
int rec = sck.Receive(Buffer, 0, Buffer.Length, 0);
Array.Resize(ref Buffer, rec);
SetText(Encoding.Default.GetString(Buffer));
//MyChat.Items.Add(Encoding.Default.GetString(Buffer));
}
}
delegate void SetTextCallback(string text);
private void SetText(string text)
{
// InvokeRequired required compares the thread ID of the
// calling thread to the thread ID of the creating thread.
// If these threads are different, it returns true.
if (this.MyChat.InvokeRequired)
{
SetTextCallback d = new SetTextCallback(SetText);
this.Invoke(d, new object[] { text });
}
else
{
this.MyChat.Items.Add(text);
}
}
private void Login_Click(object sender, EventArgs e)
{
name = UserName.Text;
ip = IPAddress.Parse("127.0.0.1");
string inputPort = "9000";
try
{
port = Convert.ToInt32(inputPort);
}
catch
{
port = 9000;
}
try
{
sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sck.Connect(new IPEndPoint(ip, port));
ReciveMes.Enabled = true;
byte[] conmsg = Encoding.Default.GetBytes("<" + name + ">" + " connected");
sck.Send(conmsg, 0, conmsg.Length, 0);
SendToServer.Enabled = true;
}
catch
{
MessageBox.Show("חיבור נכשל");
}
}
private void SendToServer_Click(object sender, EventArgs e)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + MyMessage.Text);
sck.Send(sdata, sdata.Length, 0);
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if(SendToServer.Enabled)
{
byte[] sdata = Encoding.Default.GetBytes("<" + name + ">" + "Is Quit");
sck.Send(sdata, sdata.Length, 0);
}
}
}
}

Send and receive over serial port doesn't work

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

Categories

Resources