Skip to content

Instantly share code, notes, and snippets.

@prucha
Created March 5, 2018 18:22
Show Gist options
  • Save prucha/1478aaddb45d445a1ace1178e6425187 to your computer and use it in GitHub Desktop.
Save prucha/1478aaddb45d445a1ace1178e6425187 to your computer and use it in GitHub Desktop.
C# <-> Serial Comm
//Socket Code can be used to read serial data being relayed via tinkerproxy.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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.Net.Sockets;
using System.IO;
using System.Net;
using System.Management.Instrumentation;
using System.Windows.Threading;
namespace SocketClient
{
// Reference:
// http://www.redmondpie.com/socket-programming-an-instant-messenger-prereq./
public partial class Window1 : Window
{
private byte[] _dataBuffer = new byte[10];
private IAsyncResult _result;
public AsyncCallback _pfnCallBack;
public Socket _clientSocket;
public delegate void SerialDataPosted(System.String e);
//-----------------------------------------
// Properties / Inline Classes
//-----------------------------------------
public class SocketPacket
{
public System.Net.Sockets.Socket thisSocket;
public byte[] dataBuffer = new byte[1];
}
//-----------------------------------------
// Methods
//-----------------------------------------
public Window1()
{
InitializeComponent();
Init();
}
private void Init()
{
App.Current.Exit += new ExitEventHandler(Current_Exit);
UpdateGUI(false);
textBox_IP.Text = GetIP();
}
private string GetIP()
{//Get the IP address of the hosting computer
String hostName = Dns.GetHostName(); //helper function - System.Net
IPHostEntry host;
host = Dns.GetHostByName(hostName); // Find host by name
// Grab the first IP addresses
String ip_address = "127.0.0.1"; //default localhost address
foreach (IPAddress ip in host.AddressList)
{
ip_address = ip.ToString();
return ip_address;
}
return ip_address;
}
private void OpenSocketConnection()
{
// See if we have text on the IP and Port text fields
if (textBox_IP.Text == "" || textBox_Port.Text == "")
{
MessageBox.Show("IP Address and Port Number are required to connect to the Server\n");
return;
}
try
{
UpdateGUI(false);
// Create the socket instance
_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
// Cet the remote IP address
IPAddress ip = IPAddress.Parse(textBox_IP.Text);
int portNum = System.Convert.ToInt16(textBox_Port.Text);
// Create the end point
IPEndPoint ipEnd = new IPEndPoint(ip, portNum);
// Connect to the remote host
_clientSocket.Connect(ipEnd);
if (_clientSocket.Connected)
{
UpdateGUI(true);
//Wait for data asynchronously
WaitForData();
}
}
catch (SocketException se)
{
string str;
str = "\nConnection failed, is the server running?\n" + se.Message;
MessageBox.Show(str);
UpdateGUI(false);
}
}
private void CloseSocketConnection()
{
if (_clientSocket != null)
{
_clientSocket.Close();
_clientSocket = null;
UpdateGUI(false);
}
}
private void UpdateGUI(bool connected)
{
button_Connect.IsEnabled = !connected;
button_Disconnect.IsEnabled = connected;
string connectStatus = connected ? "Connected" : "Disconnected";
label_Status.Content = connectStatus;
}
private void WaitForData()
{
try
{
if (_pfnCallBack == null)
{
_pfnCallBack = new AsyncCallback(OnDataReceived);
}
SocketPacket theSocPkt = new SocketPacket();
theSocPkt.thisSocket = _clientSocket;
// Start listening to the data asynchronously
_result = _clientSocket.BeginReceive(theSocPkt.dataBuffer,
0, theSocPkt.dataBuffer.Length,
SocketFlags.None,
_pfnCallBack,
theSocPkt);
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
public void OnDataReceived(IAsyncResult asyn)
{
try
{
SocketPacket theSockId = (SocketPacket)asyn.AsyncState;
int iRx = theSockId.thisSocket.EndReceive(asyn);
char[] chars = new char[iRx + 1];
System.Text.Decoder d = System.Text.Encoding.UTF8.GetDecoder();
int charLen = d.GetChars(theSockId.dataBuffer, 0, iRx, chars, 0);
System.String szData = new System.String(chars);
this.Dispatcher.Invoke(DispatcherPriority.Normal,
new SerialDataPosted(OutputString), szData);
}
catch (ObjectDisposedException)
{
System.Diagnostics.Debugger.Log(0, "1", "\nOnDataReceived: Socket has been closed\n");
}
catch (SocketException se)
{
MessageBox.Show(se.Message);
}
}
void OutputString(System.String e)
{
textBox_Output.Text += e.TrimEnd("\0".ToCharArray());//a null char needs to removed from the end
WaitForData();
}
//-----------------------------------------------
// Event Handlers
//-----------------------------------------------
void Current_Exit(object sender, ExitEventArgs e)
{
CloseSocketConnection();
}
private void button_Connect_Click(object sender, RoutedEventArgs e)
{
OpenSocketConnection();
}
private void button_Disconnect_Click(object sender, RoutedEventArgs e)
{
CloseSocketConnection();
}
private void button_Clear_Click(object sender, RoutedEventArgs e)
{
textBox_Output.Text = ""; //Clear output
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment