Best way to create a UDP network for Android
I recently asked a question regarding threading on Android (Google Daydream specific) which wasn't performing as expected. I was using a thread for communication to transfer information between an embedded system, and once the communication failed (i.e. the embedded system turned off, or any other 'can't transmit/receive' reason) the thread would abort and would attempt to reconnect to the embedded system until a connection is made again.
This works perfectly running in Unity (5.6) on Windows, but once ported to Android the thread seems to just hang once the network goes down and won't acknowledge that the thread has died. The Update() function continues to loop, but it's not until I leave the scene that the thread dies and the code continues to perform as expected (see my other post here).
I'm trying a new idea now where I'm assuming it's not the threading code which is problematic, or Android's inability to handle threads (as I've had no indication from anyone that what I'm doing can't be done on Android) but perhaps the handling of networks on Android or my UDP code.
I've got my UDP code below and I wanted to see if anyone saw anything which immediately looks wrong:
using UnityEngine;
using System;
using System.Net;
using System.Net.Sockets;
public class UDPConn : MonoBehaviour {
Socket sock;
IPEndPoint destEnd;
IPEndPoint endPoint;
EndPoint sender;
// Bool for connection status
public bool socketReady = false;
// Receive timeout (ms).
int rxTimeout = 1000;
byte[] msg;
// Try to initiate connection.
public bool setupSocket(int conPort)
{
try
{
String hostName = "";
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
hostName = ip.ToString();
}
}
System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse(hostName);
endPoint = new IPEndPoint(ipaddress, conPort);
System.Net.IPAddress remoteIP = System.Net.IPAddress.Parse("192.168.20.2");
destEnd = new IPEndPoint(remoteIP, conPort);
sender = (EndPoint)destEnd;
sock = new Socket(endPoint.Address.AddressFamily, SocketType.Dgram, ProtocolType.Udp);
sock.Bind(endPoint);
sock.ReceiveTimeout = rxTimeout;
// Send message to 'wake' other side.
sock.SendTo(System.Text.Encoding.ASCII.GetBytes("Connect"), sender);
// Attempt to read from the socket. This will timeout if the other side isn't active.
string readData = readSocket();
if (readData != null) {
socketReady = true;
return true;
}
else
{
socketReady = false;
return false;
}
}
catch (Exception e)
{
Debug.Log("Socket error: " + e);
return false;
}
}
// Send message to server.
public void writeSocket(string theLine)
{
if (!socketReady)
{
return;
}
sock.SendTo(System.Text.Encoding.ASCII.GetBytes(theLine), sender);
}
// Read message from server.
public string readSocket()
{
try
{
msg = new Byte[256];
sock.ReceiveFrom(msg, ref sender);
String returnData = System.Text.Encoding.ASCII.GetString(msg);
return returnData;
}
catch (Exception e)
{
Debug.Log("Socket error: " + e);
return null;
}
}
// Disconnect from the socket.
public void closeSocket()
{
if (!socketReady)
{
return;
}
Debug.Log("UDPConn:closeSocket");
sock.Close();
socketReady = false;
}
}
Other than my code, I also saved the Logcat (see end of post) at the point of where I disconnected the network from the Android phone (by swiping down from the screen, disabling the WiFi). My other idea outside of the UDP code is that perhaps I need to catch some sort of network error from Android and handle it better. The first item in Logcat is the last Debug.Log message I sent within Unity, and the first cnss-daemon message is the point at which I disconnected the network. Is there anything in there that can help identify my issue?
Thanks very much for any help. Sorry for the long post.
06-30 14:07:56.150 19762 19966 I Unity : **Inside Thread Run()
06-30 14:07:56.150 19762 19966 I Unity : Stacktrace is not supported on this platform.
06-30 14:07:56.150 19762 19966 I Unity : (Filename: ./artifacts/generated/common/runtime/DebugBindings.gen.cpp Line: 51)
06-30 14:07:56.150 19762 19966 I Unity :
06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:153): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability
06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:154): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability
06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:155): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability
06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:156): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability
06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:157): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability
06-30 14:07:56.149 651 651 W cnss-daemon: type=1400 audit(0.0:158): avc: granted { net_admin } for capability=12 scontext=u:r:cnss-daemon:s0 tcontext=u:r:cnss-daemon:s0 tclass=capability
06-30 14:07:56.153 1487 1487 I wpa_supplicant: wlan0: CTRL-EVENT-DISCONNECTED bssid=de:14:5c:9c:33:94 reason=3 locally_generated=1
06-30 14:07:56.154 1487 1487 W wpa_supplicant: nl80211: Was expecting local disconnect but got another disconnect event first
06-30 14:07:56.160 1110 1455 D WifiStateMachine: WifiStateMachine: Leaving Connected state
06-30 14:07:56.164 1110 1456 D DhcpClient: doQuit
06-30 14:07:56.170 1110 1456 D ApfFilter: (wlan0): shutting down
06-30 14:07:56.171 1110 1455 D WifiNative-HAL: stopRssiMonitoring, cmdId 0
06-30 14:07:56.174 1110 19709 D DhcpClient: Receive thread stopped
06-30 14:07:56.177 1110 1459 D ConnectivityService: NetworkAgentInfo [WIFI () - 110] EVENT_NETWORK_INFO_CHANGED, going from CONNECTED to DISCONNECTED
06-30 14:07:56.177 1110 1459 D ConnectivityService: NetworkAgentInfo [WIFI () - 110] got DISCONNECTED, was satisfying 8
06-30 14:07:56.177 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:07:56.189 639 1171 D CommandListener: Setting iface cfg
06-30 14:07:56.200 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:07:56.206 1110 19707 D DhcpClient: onQuitting
06-30 14:07:56.223 1682 1752 W QCNEJ : |CORE| network lost: 110
06-30 14:07:56.224 1682 1752 W QCNEJ : |CORE| onLost: unbind the process to WIFI
06-30 14:07:56.229 1487 1487 I wpa_supplicant: wlan0: CTRL-EVENT-REGDOM-CHANGE init=USER type=COUNTRY alpha2=US
06-30 14:07:56.238 639 1171 D CommandListener: Clearing all IP addresses on wlan0
06-30 14:07:56.244 1110 1455 D WifiCountryCode: Succeeded to set country code to: US
06-30 14:07:56.244 1110 1455 D WifiStateMachine: Start Disconnecting Watchdog 11
06-30 14:07:56.245 1110 1455 D WifiNative-HAL: stopRssiMonitoring, cmdId 0
06-30 14:07:56.256 1110 1455 I WifiConnectivityManager: scheduleWatchdogTimer
06-30 14:07:56.277 2037 2453 W Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
06-30 14:07:56.282 1110 1455 I WifiConnectivityManager: Set WiFi disabled
06-30 14:07:56.283 1110 1455 D WifiNetworkAgent: NetworkAgent: NetworkAgent channel lost
06-30 14:07:56.297 639 1171 V IdletimerController: runCmd(/system/bin/ip6tables -w -t raw -D idletimer_raw_PREROUTING -i wlan0 -j IDLETIMER --timeout 15 --label 1 --send_nl_msg 1) res_ipv4=0, res_ipv6=0
06-30 14:07:56.310 2037 2453 W Settings: Setting airplane_mode_on has moved from android.provider.Settings.System to android.provider.Settings.Global, returning read-only value.
06-30 14:07:56.330 639 1171 V IdletimerController: runCmd(/system/bin/ip6tables -w -t mangle -D idletimer_mangle_POSTROUTING -o wlan0 -j IDLETIMER --timeout 15 --label 1 --send_nl_msg 1) res_ipv4=0, res_ipv6=0
06-30 14:07:56.332 1110 1459 D ConnectivityService: Sending DISCONNECTED broadcast for type 1 NetworkAgentInfo [WIFI () - 110] isDefaultNetwork=true
06-30 14:07:56.344 18824 18824 D MusicLifecycle: com.google.android.music.net.NetworkConnectivityMonitor$NetworkChangedReceiver generated event: Broadcast received with context com.google.android.music.ui.PhoneMusicApplication#e91968c and intent Intent { act=android.net.conn.CONNECTIVITY_CHANGE flg=0x4000010 (has extras) }
06-30 14:07:56.349 2393 18279 W MdnsClient_Cast: Multicast lock held. Releasing. Subtypes:"233637DE"
06-30 14:07:56.359 18824 18824 I NetworkConnectivity: Network state changed: null
06-30 14:07:56.372 2393 18279 W MdnsClient: unicast receiver thread is already dead.
06-30 14:07:56.384 18824 18824 I NetworkPolicyMonitor: Download-ability status changed to (false) unmetered wifi/eth: false mobileOrMetered: false
06-30 14:07:56.389 18824 18824 I NetworkPolicyMonitor: Stream-ability status changed to (false) unmetered wifi/eth: false mobileOrMetered: false
06-30 14:07:56.408 2393 18279 I DeviceScanner: [MDNS] notifyDevicesOffline: []
06-30 14:07:56.422 2393 18279 E Publisher: ProcessDatabaseInternal start
06-30 14:07:56.424 2393 18279 I CastMediaRouteProvider: onDevicesPublished with 0 devices
06-30 14:07:56.438 2393 18279 I CastMediaRouteProvider: Published 0 routes
06-30 14:07:56.447 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:07:56.452 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:07:56.462 639 1171 E Netd : netlink response contains error (No such file or directory)
06-30 14:07:56.464 1110 1459 D NetworkNotificationManager: clearing notification tag=ConnectivityNotification:110 event=NO_INTERNET
06-30 14:07:56.490 2393 14149 W Herrevad: [660] rwh.b: Invalid mccmnc
06-30 14:07:56.495 2393 14149 W Herrevad: [660] rwh.b: Invalid mccmnc
06-30 14:07:56.525 18824 18935 W NetworkBandwidthMonitor: Unsuccessful attempt to get a Network Quality Client prediction (quality==null)
06-30 14:07:56.552 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:07:56.557 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:07:56.673 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:07:56.677 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:07:56.732 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:07:56.737 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:07:59.732 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:07:59.752 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:08:00.872 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:08:00.877 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:08:02.680 2164 2181 W GvrApi : GvrApi.shutdown() should be called to ensure resource cleanup
06-30 14:08:04.847 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:08:04.852 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
06-30 14:08:21.718 1110 1670 E : E/int izat_xtra::XtraDataRequest::doDownloadXtraData(const string &, string &):177][XTRA2] DNS resolution on xtrapath3.izatcloud.net failed.
06-30 14:08:24.766 2037 19816 W ctxmgr : [NetworkStateProducer]No state change for network connection context
06-30 14:08:26.012 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK OFF using UART driver's ioctl()
06-30 14:08:26.017 1930 1930 I WCNSS_FILTER: ibs_msm_serial_clock_vote: vote UART CLK ON using UART driver's ioctl()
Related
I'm trying to communicate with the GC420t via serial port in c#.
I need to get the status of the printer.
I want to send the command ~HQES and receive the status.
I'm able to write commands: I've tryied to print succesfully some qrcodes.
But when I write the status info command I don't get any answer.
This is my test code:
//define serial port
static SerialPort _serialPort = new SerialPort("COM7", 9600, Parity.None, 8, StopBits.One);
public Serial()
{
try
{
_serialPort.Open();
WriteCommand();
ReadStatus();
}
catch (Exception ex)
{
_serialPort.Close();
}
}
public void WriteCommand()
{
string qrcode = "^XA^FO,20,20^BQ,2,10^FDD03048F,LM,N0123456789,A12AABB,B0006qrcode^FS^XZ";
string statusInfo = " ~HQES";
_serialPort.Write(statusInfo);
}
public void ReadStatus()
{
_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
}
private static void DataReceivedHandler(
object sender,
SerialDataReceivedEventArgs e)
{
SerialPort sp = (SerialPort)sender;
string indata = sp.ReadExisting();
Console.WriteLine("Data Received:");
Console.Write(indata);
}
EDIT:
It will be fine for me also to be able to get that info on request:
WriteCommand();
int timeout = 3000;
while (timeout > 0)
{
Thread.Sleep(10);
timeout--;
// Timeout
string status = _serialPort.ReadExisting();
}
You should check ifs the printer configured to use any form of handshaking? Particularly XON/XOFF or DTR .
Ref page 24 of User Guide. https://www.uline.com/PDF/IH-7246VND.PDF
In the event the link breaks - the relevant text is
"The printer has a DCE serial communication port for hardware compatibility with legacy 888 printers. The required cable must have a nine-pin "D" type (DB-9P) male connector on one end which plugs into the mating (DB-9S) serial port located on the back of the printer. The other end of this signal interface cable connects to a serial port on the host computer. The cable is a Null-Modem (cross-over signal connections) cable. For pinout information, refer to Appendix A.
The serial port communication settings between the printer and host (typically a PC) must match for reliable communication. The Bits per second (or Baud rate) and Flow control are the most common settings that get changed. The host (typically a Windows PC) needs to have the data Flow control changed to match the printer's default communication method: Hardware and is noted by the Host Handshake setting DTR/Xon/Xoff. This combined hardware (DTR) and software (Xon/Xoff) mode may need to change depending{ upon use with non-Zebra application software or the serial cable variation in use."
You need to hook up the DataReceived handler before you make any calls, otherwise it might have answered before you hook it up.
Move ReadStatus up 1 line so that it comes straight after the constructor.
_serialPort.Open();
ReadStatus();
WriteCommand();
A field device (Loxone miniserver) is sending measurements in UDP packets to the public adress of an azure VM and to my local machine, both on port 1234(changed for integrity). On my local machine in the same network as the field device I implemented a test receiver in C# which gets the packets correctly.
On an already running application on an azure VM I added the same receiver code as in the local machine and got no UDP packets.
What I already did on the azure management platform:
- Allowed the incoming port 1234 in the network configuration
- Switched off the firewall
For testing I tried following:
- Implemented a UDP sender on the application in the azure VM which sends on broadcast-IP to port 1234 -> this works!
- Added a packet monitor to the network-interface -> here I see both packages, the internal broadcast and the field device
//Receiver-Code reduced to relevant parts
class Program{
public static void Main(string[] args){
program.Run();
}
public void Run(){
var sync = new LoxoneSyncProcess();
while(true){
sync.readUDP();
Thread.sleep(10000);
}
}
}
class LoxoneSyncProcess{
public LoxoneSyncProcess(){
private UDPSocket c = new UDPSocket();
c.Client(1234);
}
public void readUDP(){
String buffer = c.getDatBuf();
Console.WriteLine(buffer);
//process buffer
}
}
public class UDPSocket{
private Socket _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
private const int bufSize = 8 * 1024;
private State state = new State();
private EndPoint epFrom = new IPEndPoint(IPAddress.Any, 0);
private AsyncCallback recv = null;
private String datBuf = "";
public class State
{
public byte[] buffer = new byte[bufSize];
}
public String getDatBuf()
{
String temp = datBuf;
datBuf = "";
return temp;
}
public void Client(int port)
{
_socket.Bind(new IPEndPoint(IPAddress.Any, port));
Receive();
}
private void Receive()
{
_socket.BeginReceiveFrom(state.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv = (ar) =>
{
State so = (State)ar.AsyncState;
int bytes = _socket.EndReceiveFrom(ar, ref epFrom);
_socket.BeginReceiveFrom(so.buffer, 0, bufSize, SocketFlags.None, ref epFrom, recv, so);
datBuf += Encoding.ASCII.GetString(so.buffer, 0, bytes);
//Console.WriteLine("RECV: {0}: {1}, {2}", epFrom.ToString(), bytes, Encoding.ASCII.GetString(so.buffer, 0, bytes));
}, state);
}
}
The code is working, I receive self sent UDP packets to port 1234 on Broadcast-IP, but not from the field device.
Are there any tables like NAT-configurations needed? Or portforewarding? Does azure support public UDP endpoints?
UDP public Endpoint is supported in Azure. Just wanted to check the size of the UDP payload that you use. If the UDP payload is > 1500 bytes then it will not work.
This is by design at the moment as we do not support fragments to public VIP endpoints right now in the vswitch. The recommendation is for customers to keep UDP datagrams to under 1500. There’s really nothing short term we could do to allow fragments through without code changes – they’re fundamentally not supported in the NAT
One thing to note is the mentioning of fragmentation according to Microsoft.
Granted the information is about TCP/IP but MTU obviously affects UDP traffic as well.
Azure and VM MTU
The default MTU for Azure VMs is 1,500 bytes. The Azure Virtual Network stack >will attempt to fragment a packet at 1,400 bytes.
Note that the Virtual Network stack isn't inherently inefficient because it >fragments packets at 1,400 bytes even though VMs have an MTU of 1,500. A >large percentage of network packets are much smaller than 1,400 or 1,500 >bytes.
Source https://learn.microsoft.com/en-us/azure/virtual-network/virtual-network-tcpip-performance-tuning
with a c# application using the function : clientUDP.joinMulticastGroup(MulticastGroup) i can add a multicast address to a specific interface. The problem is: each time i run my application i add a multicast group to the a network interface, but when the app end it remain joined, so if i run again the app switching the interface it doen't work, than i need to change multicast address and again ...again... in this way i associate a lot of multicast address to each interface.
If i run:
netsh interface ip show joins
it shows my interface with multicast joined
Interfaccia 7: Wi-Fi
Ambito Referement Ultimo Address
---------- ----------- ------ ---------------------------------
0 0 SÌ 224.0.0.1
0 0 SÌ 224.0.0.3
0 0 SÌ 224.0.0.121
0 2 SÌ 224.0.0.251
0 1 SÌ 224.0.0.252
0 0 SÌ 224.0.0.253
0 0 SÌ 224.168.100.2
0 2 SÌ 224.237.248.235
0 0 SÌ 224.237.248.237
0 0 SÌ 239.255.255.3
0 3 SÌ 239.255.255.250
The question is: HOW CAN I REMOVE THIS MULTICAST JOINED FROM EACH INTERFACE ?
There is a shell command only or something i can do on c# too?
My Code (it works only first time i launch my app, than if i run a second time i need to change the multicast address):
private static readonly IPAddress GroupAddress =IPAddress.Parse("224.237.248.235");
private const int GroupPort = 64555;
private static IPEndPoint groupEP = new IPEndPoint(GroupAddress, GroupPort);
//server udp
private static UdpClient serverUDP = new UdpClient(GroupPort);
//client udp
private static UdpClient clientUDP = new UdpClient();
private static IPEndPoint remoteEpClient = null;
manage
clientUDP.JoinMulticastGroup(GroupAddress, IPAddress.Parse(LANSharingApp.umu.GetLocalIP()));
remoteEpClient = new IPEndPoint(GroupAddress, GroupPort);
serverUDP.JoinMulticastGroup(GroupAddress);
for send
clientUDP.Send(ASCIIEncoding.ASCII.GetBytes(message), ASCIIEncoding.ASCII.GetBytes(message).Length, remoteEpClient);
for receive
bytes = serverUDP.Receive(ref groupEP);
I am a linux programmer venturing into the world of C# programming using windows. I have got a virtual machine( Oracle Virtual box) which runs windows 7. I have checked the ports and it says - COM 1, COM2, etc.However, It seems like my machine doesn't recognise COM1
Here are the errors I get.
What I want to know here is that is it something with my program liking missing some extra API or is it related to my machine capability?
System.IO.IOException: The port 'COM1' does not exist.
at System.IO.Ports.InternalResources.WinIOError(Int32 errorCode, String str)
at System.IO.Ports.SerialStream..ctor(String portName, Int32 baudRate, Parity
parity, Int32 dataBits, StopBits stopBits, Int32 readTimeout, Int32 writeTimeou
t, Handshake handshake, Boolean dtrEnable, Boolean rtsEnable, Boolean discardNul
l, Byte parityReplace)
at System.IO.Ports.SerialPort.Open()
at EFTPOS_SHIM_APP.SerialPortMessenger.SerialPortMessengerStart() in C:\Users
\shreyas\Dropbox\POS_SHIM_EFTPOS_APP\EFTPOS_SHIM_APP\EFTPOS_SHIM_APP\SerialPortM
essenger.cs:line 31
Here is the code -
class SerialPortMessenger
{
private SerialPort port;
public void SerialPortMessengerStart()
{
Console.WriteLine(System.IO.Ports.SerialPort.GetPortNames());
port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
// attach a method to be called when there is data coming on to the port's buffer
port.DataReceived += new SerialDataReceivedEventHandler(portDataReceivedHandler);
// Begin Communication
try
{
port.Open();
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
Application.Run();
}
private void portDataReceivedHandler(object sender, SerialDataReceivedEventArgs e)
{
Console.WriteLine(port.ReadExisting());
}
}
Is it possible that your machine does not have a "COM1"? You can use the following code from https://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames(v=vs.110).aspx to check available COM ports:
using System;
using System.IO.Ports;
namespace SerialPortExample
{
class SerialPortExample
{
public static void Main()
{
// Get a list of serial port names.
string[] ports = SerialPort.GetPortNames();
Console.WriteLine("The following serial ports were found:");
// Display each port name to the console.
foreach(string port in ports)
{
Console.WriteLine(port);
}
Console.ReadLine();
}
}
}
Alternatively you can just inspect your computer's Device Manager under "Ports (COM & LPT)" to see available ports on your machine.
You can edit the following line:
port = new SerialPort("COM1", 9600, Parity.None, 8, StopBits.One);
and change the "COM1", to whatever your comport number is. In the long run it would be best to store the COMx value in a settings file, since it will change from machine to machine.
Edit:
You mentioned that you are running on a virtual machine. Have you correctly added COM ports to the virtual machine? See this article: https://forums.virtualbox.org/viewtopic.php?f=7&t=26860 on "How to: Add a Serial Port in Windows XP and 7 Guest."
I am working on a project for sending hex data continuously to serial com ports from my computer and then from com ports to LEDs (RGB lights) through RS232 USB cable. Sometimes it works for 10 -15 hours and alternate days it gets stopped sending data to ports.
I am using DMX 512 controller, RS232 USB cable with FTDI driver and c# language for coding to send data with SerialPort class.
Here is my code:
public static GO ()
{
try
{
dmx = new Dmx(2, 0);
Thread mTh1 = new Thread(() => dmx.Start(RGBdata1, RGBdata2, RGBdata3));
Global.tmrStarted = true; // test it,ok
mTh1.Start();
}
}
This is my start method where I send data to 3 ports
while (Global.tmrStarted)
{
Break();
Thread.Sleep(500);
if (m_port == null || m_port.IsOpen == false) return;
m_port.Write(new byte[] { 0 }, 0, 1);
SendData();
Break1();
if (m_port1 == null || m_port1.IsOpen == false) return;
m_port1.Write(new byte[] { 0 }, 0, 1);
SendData1();
Break2();
if (m_port4 == null || m_port4.IsOpen == false) return;
m_port4.Write(new byte[] { 0 }, 0, 1);
SendData2();
Thread.Sleep(100);
}
When it gets stopped i try to send data through click on start button but data doesn't gets sent through those com ports till i don't remove my USB cable and plug in again which works after that.
Can anyone suggest me what's real problem with communication ports.Did they get disable by sending continuously data to them .Thanks in advance
I had this problem also,
After all my research, I was find that it happen only in USB to serial COM, because power saving of windows shut them off.
See how configure it in the attached picture.