Detect COM device insertion from .NET application - c#

I'm looking for a way to detect when COM device is plugged into PC. I'm not limited to .NET but final application is written in .NET.
Best option would be to connect to some event, if exists.
But in reality I can even list all devices in a loop.
Checking for new devices in a loop is acceptable as a delay of few seconds is not a real problem and application does it only one in a whole lifetime.

I can read this question 2 different ways:
1. How to I detect when a USB->Serial adapter has been inserted.
In this case you could do SerialPort.GetPortNames in a loop and see when that changes
2. How do I detect when I'm connected to a device through my serial port.
There is no surefire way to be able to determine when something is connected to the com port without sending data. There are some additional pins that are meant to be used in this way, but it really depends on the cabling involved. See this post for more details on the types of cables, benefits, and drawbacks.
If you can guarantee the pinout of the cable and that the device you're connecting sets DTR high, then this may be a viable approach.
If not, then you may have to poll each com port and send some data and see if you get any response.

Related

How to grab COM signal? Common principles

I have a device that's connected to a PC via COM-port in WinForms.
Do I get Signal always when device switches on?
Does device send information to COM port, or must I send a command to device for it to begin transmission of data?
What are the common principles?
What are the common principles?
This is extremely broad. You'd have to read the RS232 spec, or whichever serial spec the device adheres to (which could even be RS485). For the remainder of your questions, let's assume it's RS232, which is the most common by far. Wikipedia has some good information once you get to the part that you actually care about; see the "Data and control signals" section. The article refers to the PC/host/Data Terminal as the DTE, and the device as the DCE.
Do I get Signal always when device switches on?
Some devices will inform you that they are ready by holding DSR high. The host may be expected to set DTR high before the device will do anything.
From http://www.tldp.org/HOWTO/Serial-HOWTO-19.html#ss19.2:
Only 3 of the 9 pins have a fixed assignment: transmit, receive and
signal ground. This is fixed by the hardware and you can't change it.
But the other signal lines are controlled by software and may do (and
mean) almost anything at all. However they can only be in one of two
states: asserted (+12 volts) or negated (-12 volts). Asserted is "on"
and negated is "off". For example, Linux software may command that DTR
be negated and the hardware only carries out this command and puts -12
volts on the DTR pin. A modem (or other device) that receives this DTR
signal may do various things. If a modem has been configured a certain
way it will hang up the telephone line when DTR is negated. In other
cases it may ignore this signal or do something else when DTR is
negated (turned off).
Does device send information to COM port, or must I send a command
Depends on the device. Some devices are silent until data is requested. Some send data to the host as soon as power is applied. Devices should include documentation about what pins they use, and what expected follows should be. I've seen device documentation that provides flowcharts with regard to pins going high.

using multiple network interfaces to broadcast fractions of data in each(load-balancing / bonding)

the question is :
how to send data over multiple internet connections avilable on current pc?
possibly-partially simlilar to This Post
though my idea is(like raid-0 is using multiple hdd's , to take advatage of multiple nic's)
actually multiple internet connections/accounts to maximize
the throughoutput of the upload bandwidth (which usually has 1/8 of the total bandwidth)
the concept i am trying to implement is to use the fastest protocol, regardless the data integrity
so i could send data from one point to the other (having a "client" part of application to handle the data... check for integrity while putting data back to one piece)
or maybe just use tcp if it does not worth it (handling the integrity in application level to increase speed)
i know there's an existing application Called "Connectify" that calimes to do someting similar,
though my idea was to make something little different and i need to understand the basics
so i could start this project for testing and development.
...thanks in advance !
As a generalization of the approach you will need to take in this case would be to create multiple TCP Clients bound to the individual network adapters in your machine. You can iterate through each of the adapters available, test to make sure that they have a connection to the outside world, then add them to a collection where then for each packet of data you want to transmit, you send the packet out.
See http://msdn.microsoft.com/en-us/library/3bsb3c8f.aspx on how to bind TCPClient to individual IPEndPoints.
Because of the nature of the way TCP operates, you will have to construct essentially a wrapper for each packet of data which also includes an order id to ensure that packets received out of order (which will happen most of the time in this case), can be pieced back together again.
Let me know if you need any more help understanding things.

Persisting 140 TCP connections?

We are currently investigating the most efficient way of communicating between 120-140 embedded hardware devices running on the .NET Micro framework and a server.
Each embedded device needs to send to, and request information from the server on a fairly regular basis all in real time through TCP.
My question is this: Would it be better to initialise 140 TCP connections to the server, and then hang on to these connections, or initialise a new connection for each requests to and from the devices? Would holding on to and managing 140 TCP connections put a lot of strain on the server?
When the server detects new data in the database it needs to send this new info to 1..* devices (information is targeted to specific devices), if I held on to the 140 connections I would need to do a lookup for the correct connection each time I needed to send information instead of just sending to an IP:PORT associated with the new data.
I guess another possibly stupid question would be is it actually possibly to hang on to 140 TCP connections on a single port?
Any suggestions/comments are appreciated!
In general you are better maintaining the connections for as long as possible. If you have each device opening a connection each time it sends a message you can end up effectively DoS'ing the server as it ends up with lots of sockets in the TIME_WAIT state taking up space in it's tables.
I worked on a system where there were a bunch of clients talking to a server and while they could be turned on and off regularly, it was still better to maintain the connection (and re-establish it when it had dropped and a new message needed to be sent). You may end up needing to write slightly more complex code, but I've found it to be well worth the effort for the reduced load on the server.
Modern operating systems may have bigger buffers than the ones I actually encountered the DoS effect on, but it's fundamentally not the best idea to be using lots of connections like that.
Things can get relatively complicated on the client side, especially when the device tends to go to sleep transparently to the application because that means connections will time out while the app thinks they are still open. When we did this we ended up with relatively complex network code because we needed to deal with the fact that the sockets could (and would) fail as a matter of course and we simply needed to setup a new connection and re-attempt sending the message. You just tuck this code away into your libraries and forget about it once it's done though.
In actual fact in practice our initial application had even more complex code because it was dealing with a network library that was semi-aware of the stop start nature of the devices and tried to resend failed messages, sometimes meaning that the same message got sent twice. We ended up doing an extra layer of communication on top in order to ensure duplicates got rejected. If you're using C# or regular BSD style sockets you shouldn't have that problem though I'm guessing. This was a proprietary library that managed the reconnects but caused headaches with the resends and it's inappropriate default time-outs.
You usually can connect much more than 140 "clients" to a server (that is with decent network / HW / RAM)...
I recommend always to test this sort of thing with real scenarios (load etc.) to decide since there are aspects like network (performance, stability...), HW (server RAM etc.) and SW (what does the server exactly do?) that can only be checked by you.
Depending on the protocol you could/should even put some timeout/reconnect mechanism in there.
The lookup you mean would be really fast - just use ConcurrentDictionary to hold the needed information with IP:PORT as the key (assuming the server runs on a full .NET 4).
For some references see:
http://msdn.microsoft.com/en-us/library/dd287191.aspx
http://geekswithblogs.net/BlackRabbitCoder/archive/2011/02/17/c.net-little-wonders-the-concurrentdictionary.aspx
EDIT - as per comments:
Holding on to a TCP/IP connection doesn't take much processing client-side... it costs a bit of memory. I would recommend to do a small test (1-2 clients) to check this assumption for your specific case.
If you are talking about a system with hardware devices then I suggest to go with closing the connection every time the client finishes sending data.
To make sure the client gets some update from the server, the client can wait for a 5 second period for any data to arrive from the server. If the data is received within/before this timeframe, then close the connection and process the data. If not, close the connection and wait after sending next set of data.
This way scaling becomes much easier. Keeping the connections open always leads to strain on the resources and in my opinion is not necessary unless it is some life-saving device like heart rate monitor, oxygen supply monitor etc.,

Internet communication between programs, without worry in C#?

I want to provide a direct connection between two instances of my program, which are located on two different computers.
I already have the means to obtain the IP addresses, but how do I make a connection between my programs and have no trouble with the firewall or ports?
I need to send serialized objects through the connection.
Edit2: The specific term is peer-to-peer connection.
Edit: I see I need to explain the "no trouble" part.
First, when a program attempts to communicate to the internet, the annoying Windows Firewall permission dialog opens.
On Windows 7, you have two checkboxes:
1. Allow on private (home/work) networks, which is checked by default and, sometimes, cannot be unchecked.
2. Allow on public networks, which is either checked or unchecked by default...
NO ONE I know makes sure that all the check boxes are checked. NO ONE.
This can interrupt the program sometimes in bad ways, without people knowing!
Next... Most people are behind a router and routers usually block all the requests to undefined ports, unless the rules are changed.
Nobody will accept to add these rules just to use a program. Nobody.
You can use WCF for this purpose.
It doesn't solve 'all' network problems though, but I doubt any technology would.
It kind of sounds like you're looking for a way to bypass firewalls so that your users won't have to deal with that kind of stuff while using your program.
If that's indeed the case, think about it this way. Would the Windows Firewall be good at its job if it allowed you (or anyone else) to do that?
What you might want to do is open up a port using TCP and send serialized objects over it to a target listener, which knows how to decode those bits back to objects.
If you need that port open, your users will have to allow that. If they're running a firewall that blocks it, then that firewall needs to be properly configured to allow your program to interact with the target computer.
You can use TcpClient, TcpListener (System.Net) and BinaryFormatter (System.Runtime.Serialization) to send serialized objects over TCP.
Remember you need to specify your custom classes as [Serializable].
So, using a TcpClient and a TcpListener works... as long as I forward the ports on the listener's router.
So this is not an option.
I ended up using my database to queue commands and check for them every once in a while, and dequeue them when necessary.
For the moment, I cannot find any good answer.

Serial data logging

I have a device connected to my computer that sends serial data to the computer every 5 mins. I want to write a basic program to capture this serial data every 5 mins and put it into a database. I was hoping to use C# because I have used C# with databases before and found it quite easy.
Can anybody offer me any advice on how I might do this, I really have no idea where to start and I know in theory it sounds easy but when I started it I actually found it really hard.
Using C#, you can use the System.IO.Ports namespace to communicate over the serial ports - there's a nice article here.
Alternatively, you can use Python and the pySerial module. I've written an app to communicate over the serial port using pySerial - it's quite easy to use, and can run on many different operating systems including OSX and Windows (I'm assuming you're using Windows). Python also has built-in support for SQLite.
The problem with capturing data on a serial port is that serial ports aren't thread-safe, so if there is more than one listener, data will be corrupted.
If you are absolutely sure that you're the only one listening for data on this port, .NET has a built-in wrapper, System.IO.Ports.SerialPort, which you can use to connect to COM1, COM2, etc. You'll need to know the rate in bits/sec at which this device sends data (its baud rate), its error-checking (parity) protocol, and the format of the data it is sending (you'll get it as a byte array, which you must convert byte-by-byte into data you can work with). Then, your program should be able to open the port and listen for DataReceived events with a handler that will read and digest the data. Again, it's VERY important that you never have two threads trying to read at once; the easiest way is to set a volatile boolean indicating that a handler is reading data; if another handler is ever spawned while a previous one is still running, the first thing the new one should do is read that value, and since it's set, exit the new handler immediately.

Categories

Resources