Search Results

Search found 49 results on 2 pages for 'datareceived'.

Page 1/2 | 1 2  | Next Page >

  • what causes the .NET SerialPort class DataReceived event to fire?

    - by Klay
    I understand from the MSDN docs that the event DataReceived will not necessarily fire once per byte. But does anyone know what exactly is the mechanism that causes the event to fire? Does the receipt of each byte restart a timer that has to reach, say 10 ms between bytes, before the event fires? I ask because I'm trying to write an app that reads XML data coming in from a serial port. Because my laptop has no serial ports, I use a virtual serial port emulator. (I know, I know--I can't do anything about it ATM). When I pass data through the emulated port to my app, the event fires once for each XML record (about 1500 bytes). Perfect. But when a colleague at another office tries it with two computers connected by an actual cable, the DataReceived event fires repeatedly, after every 10 or so bytes of XML, which totally throws off the app.

    Read the article

  • .NET SerialPort DataReceived event not firing

    - by Klay
    I have a WPF test app for evaluating event-based serial port communication (vs. polling the serial port). The problem is that the DataReceived event doesn't seem to be firing at all. I have a very basic WPF form with a TextBox for user input, a TextBlock for output, and a button to write the input to the serial port. Here's the code: public partial class Window1 : Window { SerialPort port; public Window1() { InitializeComponent(); port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One); port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); port.Open(); } void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { Debug.Print("receiving!"); string data = port.ReadExisting(); Debug.Print(data); outputText.Text = data; } private void Button_Click(object sender, RoutedEventArgs e) { Debug.Print("sending: " + inputText.Text); port.WriteLine(inputText.Text); } } Now, here are the complicating factors: The laptop I'm working on has no serial ports, so I'm using a piece of software called Virtual Serial Port Emulator to setup a COM2. VSPE has worked admirably in the past, and it's not clear why it would only malfunction with .NET's SerialPort class, but I mention it just in case. When I hit the button on my form to send the data, my Hyperterminal window (connected on COM2) shows that the data is getting through. Yes, I disconnect Hyperterminal when I want to test my form's ability to read the port. I've tried opening the port before wiring up the event. No change. I've read through another post here where someone else is having a similar problem. None of that info has helped me in this case. EDIT: Here's the console version (modified from http://mark.michaelis.net/Blog/TheBasicsOfSystemIOPortsSerialPort.aspx): class Program { static SerialPort port; static void Main(string[] args) { port = new SerialPort("COM2", 9600, Parity.None, 8, StopBits.One); port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); port.Open(); string text; do { text = Console.ReadLine(); port.Write(text + "\r\n"); } while (text.ToLower() != "q"); } public static void port_DataReceived(object sender, SerialDataReceivedEventArgs args) { string text = port.ReadExisting(); Console.WriteLine("received: " + text); } } This should eliminate any concern that it's a Threading issue (I think). This doesn't work either. Again, Hyperterminal reports the data sent through the port, but the console app doesn't seem to fire the DataReceived event. EDIT #2: I realized that I had two separate apps that should both send and receive from the serial port, so I decided to try running them simultaneously... If I type into the console app, the WPF app DataReceived event fires, with the expected threading error (which I know how to deal with). If I type into the WPF app, the console app DataReceived event fires, and it echoes the data. I'm guessing the issue is somewhere in my use of the VSPE software, which is set up to treat one serial port as both input and output. And through some weirdness of the SerialPort class, one instance of a serial port can't be both the sender and receiver. Anyway, I think it's solved.

    Read the article

  • C# .Net Serial DataReceived Event response too slow for high-rate data.

    - by Matthew
    Hi, I have set up a SerialDataReceivedEventHandler, with a forms based program in VS2008 express. My serial port is set up as follows: 115200, 8N1 Dtr and Rts enabled ReceivedBytesThreshold = 1 I have a device I am interfacing with over a BlueTooth, USB to Serial. Hyper terminal receives the data just fine at any data rate. The data is sent regularly in 22 byte long packets. This device has an adjustable rate at which data is sent. At low data rates, 10-20Hz, the code below works great, no problems. However, when I increase the data rate past 25Hz, there starts to recieve mulitple packets on one call. What I mean by this is that there should be a event trigger for every incoming packet. With higher output rates, I have tested the buffer size (BytesToRead command) immediatly when the event is called and there are multiple packets in the buffer then. I think that the event fires slowly and by the time it reaches the code, more packes have hit the buffer. One test I do is see how many time the event is trigger per second. At 10Hz, I get 10 event triggers, awesome. At 100Hz, I get something like 40 event triggers, not good. My goal for data rate is 100HZ is acceptable, 200Hz preferred, and 300Hz optimum. This should work because even at 300Hz, that is only 52800bps, less than half of the set 115200 baud rate. Anything I am over looking? public Form1() { InitializeComponent(); serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); } private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e) { this.Invoke(new EventHandler(Display_Results)); } private void Display_Results(object s, EventArgs e) { serialPort1.Read(IMU, 0, serial_Port1.BytesToRead); }

    Read the article

  • Datareceived Serialport event stops raising after some seconds

    - by Mario
    Hi, I was hoping someone could help me out with this problem. I have a system (VB .NET) where I must read a person's weight (RS232 Sluice) and id (Fingerprint - 2 biometric reader, rs232) and compare it to a database. I have 3 serialports in my app, one for the sluice and the other 2 are to receive the id from the fingerprint readers, both of which call the same sub to get the id from the reader. I've been testing just one reader and it seemed to work fine, I got data from the datareceived and joined it together to get the id. The problem comes at this moment: I put a finger, sends the id, if it's ok sends a message, otherwise, writes the id to a textbox. But in-between reads, if I let 5 or 10 seconds pass without putting a finger on the reader it seems like I get no data at all anymore, the datareceived event nevers gets raised but if I keep putting a finger constantly it works pretty good, this is really weird to me. I was thinking of some things: **Maybe the port gets closed somehow after some time? I never call the CLose() method **The fact both datareceived eventhandlers call the same method and delegate **Maybe the connection settings are missing something? I tested with hyperterminal and the port keeps getting info even after time without activity and I use the same config with my application, maybe I need to change more settings like DTEenable and RTSenable? Please I need some help with this issue, it's to control access so it needs to be running 24/7 thanks in advance!

    Read the article

  • DataReceived Event handler not receiving messages

    - by karthik
    I'm using the below code to receive the messages using serial port event handler. But it dosent receives any.I am not getting errors. The code breaks in "string msg = comport.Readline()" Am i doing something wrong ? public partial class SerialPortScanner : Form { private SerialPort comPort = new SerialPort(); public SerialPortScanner() { InitializeComponent(); comPort.Open(); comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); } void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (comPort.IsOpen == true) { string msg = comPort.ReadLine(); MessageBox.Show(msg); } } }

    Read the article

  • DataReceived Event handler not receiving messages using c#

    - by karthik
    I'm using the below code to receive the messages using serial port event handler. But it dosent receives any.I am not getting errors. The code breaks in "string msg = comport.Readline()" Am i doing something wrong ? public partial class SerialPortScanner : Form { private SerialPort comPort = new SerialPort(); public SerialPortScanner() { InitializeComponent(); comPort.Open(); comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); } void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { if (comPort.IsOpen == true) { string msg = comPort.ReadLine(); MessageBox.Show(msg); } } }

    Read the article

  • .NET SerialPort DataReceived event thread interference with main thread

    - by Kiran
    I am writing a serial communication program using the SerialPort class in C# to interact with a strip machine connected via a RS232 cable. When i send the command to the machine it responds with some bytes depending on the command. Like when i send a "\D" command, i am expecting to download the machine program data of 180 bytes as a continous string. As per the machine's manual, it suggests as a best practice to send an unreognized characters like comma (,) character to make sure the machine is initialized before sending the first command in the cycle. My serial communication code is as follows: public class SerialHelper { SerialPort commPort = null; string currentReceived = string.Empty; string receivedStr = string.Empty; private bool CommInitialized() { try { commPort = new SerialPort(); commPort.PortName = "COM1"; if (!commPort.IsOpen) commPort.Open(); commPort.BaudRate = 9600; commPort.Parity = System.IO.Ports.Parity.None; commPort.StopBits = StopBits.One; commPort.DataBits = 8; commPort.RtsEnable = true; commPort.DtrEnable = true; commPort.DataReceived += new SerialDataReceivedEventHandler(commPort_DataReceived); return true; } catch (Exception ex) { return false; } } void commPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { SerialPort currentPort = (SerialPort)sender; currentReceived = currentPort.ReadExisting(); receivedStr += currentReceived; } internal int CommIO(string outString, int outLen, ref string inBuffer, int inLen) { receivedStr = string.Empty; inBuffer = string.Empty; if (CommInitialized()) { commPort.Write(outString); } System.Threading.Thread.Sleep(1500); int i = 0; while ((receivedStr.Length < inLen) && i < 10) { System.Threading.Thread.Sleep(500); i += 1; } if (!string.IsNullOrEmpty(receivedStr)) { inBuffer = receivedStr; } commPort.Close(); return inBuffer.Length; } } I am calling this code from a windows form as follows: len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4) len = SerialHelperObj.CommIO(",",1,ref inBuffer, 4) If(inBuffer == "!?*O") { len = SerialHelperObj.CommIO("\D",2,ref inBuffer, 180) } A valid return value from the serial port looks like this: \D00000010000000000010 550 3250 0000256000 and so on ... I am getting some thing like this: \D00000010D,, 000 550 D,, and so on... I feel that my comm calls are getting interferred with the one when i send commands. But i am trying to make sure the result of the comma command then initiating the actual command. but the received thread is inserting the bytes from the previous communication cycle. Can any one please shed some light into this...? I lost quite some hair just trying to get this work. I am not sure where i am doing wrong

    Read the article

  • Android: handle unexpected internet disconnect while downloading data

    - by M.A. Cape
    Hi, I have here a function that downloads data from a remote server to file. I am still not confident with my code. My question is, what if while reading the stream and saving the data to a file and suddenly I was disconnected in the internet, will these catch exceptions below can really catch that kind of incident? If not, can you suggest how to handle this kind of incident? Note: I call this function in a thread so that the UI won't be blocked. public static boolean getFromRemote(String link, String fileName, Context context){ boolean dataReceived = false; ConnectivityManager connec = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE); if (connec.getNetworkInfo(0).isConnected() || connec.getNetworkInfo(1).isConnected()){ try { HttpClient httpClient = new DefaultHttpClient(); HttpGet httpGet = new HttpGet(link); HttpParams params = httpClient.getParams(); HttpConnectionParams.setConnectionTimeout(params, 30000); HttpConnectionParams.setSoTimeout(params, 30000); HttpResponse response; response = httpClient.execute(httpGet); int statusCode = response.getStatusLine().getStatusCode(); if (statusCode == 200){ HttpEntity entity = response.getEntity(); InputStream in = null; OutputStream output = null; try{ in = entity.getContent(); String secondLevelCacheDir = context.getCacheDir() + fileName; File imageFile = new File(secondLevelCacheDir); output= new FileOutputStream(imageFile); IOUtilities.copy(in, output); output.flush(); } catch (IOException e) { Log.e("SAVING", "Could not load xml", e); } finally { IOUtilities.closeStream(in); IOUtilities.closeStream(output); dataReceived = true; } } }catch (SocketTimeoutException e){ //Handle not connecting to client !!!! Log.d("SocketTimeoutException Thrown", e.toString()); dataReceived = false; } catch (ClientProtocolException e) { //Handle not connecting to client !!!! Log.d("ClientProtocolException Thrown", e.toString()); dataReceived = false; }catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); dataReceived = false; Log.d("MalformedURLException Thrown", e.toString()); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); dataReceived = false; Log.d("IOException Thrown", e.toString()); } } return dataReceived; }

    Read the article

  • NSURLConnection receives data even if no data was thrown back

    - by Anna Fortuna
    Let me explain my situation. Currently, I am experimenting long-polling using NSURLConnection. I found this and I decided to try it. What I do is send a request to the server with a timeout interval of 300 secs. (or 5 mins.) Here is a code snippet: NSURL *url = [NSURL URLWithString:urlString]; NSURLRequest *request = [NSURLRequest requestWithURL:url cachePolicy:NSURLCacheStorageAllowedInMemoryOnly timeoutInterval:300]; NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&resp error:&err]; Now I want to test if the connection will "hold" the request if no data was thrown back from the server, so what I did was this: if (data != nil) [self performSelectorOnMainThread:@selector(dataReceived:) withObject:data waitUntilDone:YES]; And the function dataReceived: looks like this: - (void)dataReceived:(NSData *)data { NSLog(@"DATA RECEIVED!"); NSString *string = [NSString stringWithUTF8String:[data bytes]]; NSLog(@"THE DATA: %@", string); } Server-side, I created a function that will return a data once it fits the arguments and returns none if nothing fits. Here is a snippet of the PHP function: function retrieveMessages($vardata) { if (!empty($vardata)) { $result = check_data($vardata) //check_data is the function which returns 1 if $vardata //fits the arguments, and 0 if it fails to fit if ($result == 1) { $jsonArray = array('Data' => $vardata); echo json_encode($jsonArray); } } } As you can see, the function will only return data if the $result is equal to 1. However, even if the function returns nothing, NSURLConnection will still perform the function dataReceived: meaning the NSURLConnection still receives data, albeit an empty one. So can anyone help me here? How will I perform long-polling using NSURLConnection? Basically, I want to maintain the connection as long as no data is returned. So how will I do it? NOTE: I am new to PHP, so if my code is wrong, please point it out so I can correct it.

    Read the article

  • threaded serial port IOException when writing

    - by John McDonald
    Hi, I'm trying to write a small application that simply reads data from a socket, extracts some information (two integers) from the data and sends the extracted information off on a serial port. The idea is that it should start and just keep going. In short, it works, but not for long. After a consistently short period I start to receive IOExceptions and socket receive buffer is swamped. The thread framework has been taken from the MSDN serial port example. The delay in send(), readThread.Join(), is an effort to delay read() in order to allow serial port interrupt processing a chance to occur, but I think I've misinterpreted the join function. I either need to sync the processes more effectively or throw some data away as it comes in off the socket, which would be fine. The integer data is controlling a pan tilt unit and I'm sure four times a second would be acceptable, but not sure on how to best acheive either, any ideas would be greatly appreciated, cheers. using System; using System.Collections.Generic; using System.Text; using System.IO.Ports; using System.Threading; using System.Net; using System.Net.Sockets; using System.IO; namespace ConsoleApplication1 { class Program { static bool _continue; static SerialPort _serialPort; static Thread readThread; static Thread sendThread; static String sendString; static Socket s; static int byteCount; static Byte[] bytesReceived; // synchronise send and receive threads static bool dataReceived; const int FIONREAD = 0x4004667F; static void Main(string[] args) { dataReceived = false; readThread = new Thread(Read); sendThread = new Thread(Send); bytesReceived = new Byte[16384]; // Create a new SerialPort object with default settings. _serialPort = new SerialPort("COM4", 38400, Parity.None, 8, StopBits.One); // Set the read/write timeouts _serialPort.WriteTimeout = 500; _serialPort.Open(); string moveMode = "CV "; _serialPort.WriteLine(moveMode); s = null; IPHostEntry hostEntry = Dns.GetHostEntry("localhost"); foreach (IPAddress address in hostEntry.AddressList) { IPEndPoint ipe = new IPEndPoint(address, 10001); Socket tempSocket = new Socket(ipe.AddressFamily, SocketType.Stream, ProtocolType.Tcp); tempSocket.Connect(ipe); if (tempSocket.Connected) { s = tempSocket; s.ReceiveBufferSize = 16384; break; } else { continue; } } readThread.Start(); sendThread.Start(); while (_continue) { Thread.Sleep(10); ;// Console.WriteLine("main..."); } readThread.Join(); _serialPort.Close(); s.Close(); } public static void Read() { while (_continue) { try { //Console.WriteLine("Read"); if (!dataReceived) { byte[] outValue = BitConverter.GetBytes(0); // Check how many bytes have been received. s.IOControl(FIONREAD, null, outValue); uint bytesAvailable = BitConverter.ToUInt32(outValue, 0); if (bytesAvailable > 0) { Console.WriteLine("Read thread..." + bytesAvailable); byteCount = s.Receive(bytesReceived); string str = Encoding.ASCII.GetString(bytesReceived); //str = Encoding::UTF8->GetString( bytesReceived ); string[] split = str.Split(new Char[] { '\t', '\r', '\n' }); string filteredX = (split.GetValue(7)).ToString(); string filteredY = (split.GetValue(8)).ToString(); string[] AzSplit = filteredX.Split(new Char[] { '.' }); filteredX = (AzSplit.GetValue(0)).ToString(); string[] ElSplit = filteredY.Split(new Char[] { '.' }); filteredY = (ElSplit.GetValue(0)).ToString(); // scale values int x = (int)(Convert.ToInt32(filteredX) * 1.9); string scaledAz = x.ToString(); int y = (int)(Convert.ToInt32(filteredY) * 1.9); string scaledEl = y.ToString(); String moveAz = "PS" + scaledAz + " "; String moveEl = "TS" + scaledEl + " "; sendString = moveAz + moveEl; dataReceived = true; } } } catch (TimeoutException) {Console.WriteLine("timeout exception");} catch (NullReferenceException) {Console.WriteLine("Read NULL reference exception");} } } public static void Send() { while (_continue) { try { if (dataReceived) { // sleep Read() thread to allow serial port interrupt processing readThread.Join(100); // send command to PTU dataReceived = false; Console.WriteLine(sendString); _serialPort.WriteLine(sendString); } } catch (TimeoutException) { Console.WriteLine("Timeout exception"); } catch (IOException) { Console.WriteLine("IOException exception"); } catch (NullReferenceException) { Console.WriteLine("Send NULL reference exception"); } } } } }

    Read the article

  • Getting unhandled error and connection get lost when a client tries to communicate with chat server in twisted

    - by user2433888
    from twisted.internet.protocol import Protocol,Factory from twisted.internet import reactor class ChatServer(Protocol): def connectionMade(self): print "A Client Has Connected" self.factory.clients.append(self) print"clients are ",self.factory.clients self.transport.write('Hello,Welcome to the telnet chat to sign in type aim:YOUR NAME HERE to send a messsage type msg:YOURMESSAGE '+'\n') def connectionLost(self,reason): self.factory.clients.remove(self) self.transport.write('Somebody was disconnected from the server') def dataReceived(self,data): #print "data is",data a = data.split(':') if len(a) > 1: command = a[0] content = a[1] msg="" if command =="iam": self.name + "has joined" elif command == "msg": ma=sg = self.name + ":" +content print msg for c in self.factory.clients: c.message(msg) def message(self,message): self.transport.write(message + '\n') factory = Factory() factory.protocol = ChatServer factory.clients = [] reactor.listenTCP(80,factory) print "Iphone Chat server started" reactor.run() The above code is running succesfully...but when i connect the client (by typing telnet localhost 80) to this chatserver and try to write message ,connection gets lost and following errors occurs : Iphone Chat server started A Client Has Connected clients are [<__main__.ChatServer instance at 0x024AC0A8>] Unhandled Error Traceback (most recent call last): File "C:\Python27\lib\site-packages\twisted\python\log.py", line 84, in callWithLogger return callWithContext({"system": lp}, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\log.py", line 69, in callWithContext return context.call({ILogContext: newCtx}, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\context.py", line 118, in callWithContext return self.currentContext().callWithContext(ctx, func, *args, **kw) File "C:\Python27\lib\site-packages\twisted\python\context.py", line 81, in callWithContext return func(*args,**kw) --- --- File "C:\Python27\lib\site-packages\twisted\internet\selectreactor.py", line 150, in _doReadOrWrite why = getattr(selectable, method)() File "C:\Python27\lib\site-packages\twisted\internet\tcp.py", line 199, in doRead rval = self.protocol.dataReceived(data) File "D:\chatserverultimate.py", line 21, in dataReceived content = a[1] exceptions.IndexError: list index out of range Where am I going wrong?

    Read the article

  • How to rebind another UDP socket port properly?

    - by Jollian
    When my client application launchs, it binds the UDP port like this: this.BindPort(5001); The BindPort method implement blow: public void BindPort(int port) { m_listener = new Socket( AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp ); IPEndPoint Point = new IPEndPoint( IPAddress.Any, Port ); m_listener.Bind( port); m_listener.BeginReceive( buff, 0, buff.Length, SocketFlags.None, new AsyncCallback( DataReceived ), buff ); } And when my server application commands client to bind to another UDP port(e.g. 5005). I call the same BindPort method in client. Then a exception occurs at DataReceived method. I think there must be a problem that I don't close the UDP port properly. But how can i close the UDP socket properly and rebind to another one. Thanks.

    Read the article

  • Will SerialPort DataRecieved Event Trigger Repeatedly..

    - by Gunner
    Suppose I read data from SerialPort whenever there is 100 or bytes available or else nothing is done. That means, the remaining data will still be available in the SerialPort Buffer. This reading is done inside the event handler of DataReceived. Now If a situation arises, when there there is, say 50 bytes in the SerilaPort Buffer and no more data comes. From what I understand, the DataReceived Event will be triggered when ever there is certain amount of bytes available for reading from the Buffer. Now, in the given scenario, If i never read those 50 bytes, will the Event get activated continuously due to the presence of these unread bytes?

    Read the article

  • Run sub on main thread from separate thread [VB.NET|SerialPort]

    - by Steven
    I'm reading data from a serial port, but the DataReceived event of SerialPort is handled on it's own thread. I want to handle this on the main thread, but simply declaring an event and raising it still results in it being processed on the SerialPort thread. I'm assuming I need to declare a delegate I can call, but I don't see how that would work. For example, I want to call Sub HandleDataReceived() on the main thread from the DataReceived thread, having HandleDataReceived() run on the main thread. How would I do this?

    Read the article

  • Moq for Silverlight doesn't raise event

    - by Budda
    Trying to write Unit test for Silverlight 4.0 using Moq 4.0.10531.7 public delegate void DataReceived(ObservableCollection<TeamPlayerData> AllReadyPlayers, GetSquadDataCompletedEventArgs squadDetails); public interface ISquadModel : IModelBase { void RequestData(int matchId, int teamId); void SaveData(); event DataReceived DataReceivedEvent; } void MyTest() { Mock<ISquadModel> mockSquadModel = new Mock<ISquadModel>(); mockSquadModel.Raise(model => model.DataReceivedEvent += null, EventArgs.Empty); } Instead of raising the 'DataReceivingEvent' the following error is received: Object of type 'Castle.Proxies.ISquadModelProxy' cannot be converted to type 'System.Collections.ObjectModel.ObservableCollection`1[TeamPlayerData]'. Why attempt to convert mock to the type of 1st event parameter is performed? How can I raise an event? I've also tried another approach: mockSquadModel .Setup(model => model.RequestData(TestMatchId, TestTeamId)) .Raises(model => model.DataReceivedEvent += null, EventArgs.Empty) ; this should raise event if case somebody calls 'Setup' method... Instead the same error is generated... Any thoughts are welcome. Thanks

    Read the article

  • Moving delegate-related function to a different thread

    - by Chris
    Hello everybody. We are developing a library in C# that communicates with the serial port. We have a function that is given to a delegate. The problem is that we want it to be run in a different thread. We tried creating a new thread (called DatafromBot) but keep using it as follows (first line): comPort.DataReceived += new SerialDataReceivedEventHandler(comPort_DataReceived); DatafromBot = new Thread(comPort_DataReceived); DatafromBot.Start(); comPort_DataReceived is defined as: Thread DatafromBot; public void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e) { ... } The following errors occur: Error 3 The best overloaded method match for 'System.Threading.Thread.Thread(System.Threading.ThreadStart)' has some invalid arguments C:...\IR52cLow\CommunicationManager.cs 180 27 IR52cLow Error 4 Argument '1': cannot convert from 'method group' to 'System.Threading.ThreadStart' C:...\IR52cLow\CommunicationManager.cs 180 38 IR52cLow Any ideas of how we should convert this to get it to compile? Please note that comPort.DataReceived (pay attention to "." instead of "_") lies within a system library and cannot be modified. Thanks for your time! Chris

    Read the article

  • how to do display text message from cellphone to textbox

    - by Jiggy Degamo
    I am just making a project automated polling system using sms but i just a beginner of serial communication i have seen a code on the net so i apply it as my guide just a simple text message and display it on the textbox it connects but the provlem is its didn't display on the textbox. here is the code below please help me why it didn't display and please give me a cite that have a tutorial of serial communication using vb.net Imports System.IO.Ports Public Class Form1 Dim inputData As String = "" Private WithEvents serialPort1 As New IO.Ports.SerialPort Public Event DataReceived As IO.Ports.SerialDataReceivedEventHandler Private Sub Form1_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed ' Close the Serial Port serialPort1.Close() End Sub Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load 'Set values for some properties serialPort1.PortName = "COM10" serialPort1.BaudRate = 2400 SerialPort1.Parity = IO.Ports.Parity.None SerialPort1.DataBits = 8 SerialPort1.StopBits = IO.Ports.StopBits.One SerialPort1.Handshake = IO.Ports.Handshake.None SerialPort1.RtsEnable = True ' Open the Serial Port SerialPort1.Open() 'Writes data to the Serial Port output buffer If SerialPort1.IsOpen = True Then SerialPort1.Write("MicroCommand") End If End Sub ' Receive data from the Serial Port 'Show received data on UI controls and do something Public Sub DoUpdate() TextBox1.Text = TextBox1.Text & inputData End Sub Private Sub serialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles serialPort1.DataReceived inputData = serialPort1.ReadExisting 'or serialPort1.ReadLine Me.Invoke(New EventHandler(AddressOf DoUpdate)) End Sub End Class

    Read the article

  • Error with threads during automatic testing on TeamCity 5

    - by yeyeyerman
    Hello, I'm having some problems executing the tests of the application I'm developing. All the tests execute normally with ReSharper and in NCover. However, the execution of one of these tests in TeamCity is generating an error. This test initializes two objects, the object under test and a simulator of a real object. Both objects will communicate throug a serial link in a representation of the real scenario. ObjectSimulator r_simulator = new ObjectSimulator(...); ObjectDriver r_driver = new ObjectDriver(...); Assert.IsTrue(r_driver.Connect() == ErrorCode.Success); The simulator just do the following in the constructor public class ObjectSimulator { ... public ObjectSimulator() { // serial port configuration m_port = new SerialPort(); m_port.DataReceived += DataReceivedEvent; } ... } The main object has two threads. The main thread of the application and a timer to refresh a watchdog timer in the real object. public ErrorCode Connect() { ... StartSynchroTimer(); Thread.Sleep(4); // to check if the timer is working properly ... } The problem is comming from the Thread.Sleep() call, as when I remove it everything works. It seems like the ObjectSimulator also sleeps and doesn't receive the DataReceived event. How can I resolve this issue?

    Read the article

  • Error with `Thread.Sleep` during automatic testing on TeamCity 5

    - by yeyeyerman
    Hello, I'm having some problems executing the tests of the application I'm developing. All the tests execute normally with ReSharper and in NCover. However, the execution of one of these tests in TeamCity is generating an error. This test initializes two objects, the object under test and a simulator of a real object. Both objects will communicate throug a serial link in a representation of the real scenario. ObjectSimulator r_simulator = new ObjectSimulator(...); ObjectDriver r_driver = new ObjectDriver(...); Assert.IsTrue(r_driver.Connect() == ErrorCode.Success); The simulator just do the following in the constructor public class ObjectSimulator { ... public ObjectSimulator() { // serial port configuration m_port = new SerialPort(); m_port.DataReceived += DataReceivedEvent; } ... } The main object has two threads. The main thread of the application and a timer to refresh a watchdog timer in the real object. public ErrorCode Connect() { ... StartSynchroTimer(); Thread.Sleep(4); // to check if the timer is working properly ... } The problem seems to be comming from the Thread.Sleep() call, as when I remove it everything works. The ObjectSimulator somehow doesn't execute the DataReceived event callback. How can I resolve this issue?

    Read the article

  • What is stopping data flow with .NET 3.5 asynchronous System.Net.Sockets.Socket?

    - by TonyG
    I have a .NET 3.5 client/server socket interface using the asynchronous methods. The client connects to the server and the connection should remain open until the app terminates. The protocol consists of the following pattern: send stx receive ack send data1 receive ack send data2 (repeat 5-6 while more data) receive ack send etx So a single transaction with two datablocks as above would consist of 4 sends from the client. After sending etx the client simply waits for more data to send out, then begins the next transmission with stx. I do not want to break the connection between individual exchanges or after each stx/data/etx payload. Right now, after connection, the client can send the first stx, and get a single ack, but I can't put more data onto the wire after that. Neither side disconnects, the socket is still intact. The client code is seriously abbreviated as follows - I'm following the pattern commonly available in online code samples. private void SendReceive(string data) { // ... SocketAsyncEventArgs completeArgs; completeArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnSend); clientSocket.SendAsync(completeArgs); // two AutoResetEvents, one for send, one for receive if ( !AutoResetEvent.WaitAll(autoSendReceiveEvents , -1) ) Log("failed"); else Log("success"); // ... } private void OnSend( object sender , SocketAsyncEventArgs e ) { // ... Socket s = e.UserToken as Socket; byte[] receiveBuffer = new byte[ 4096 ]; e.SetBuffer(receiveBuffer , 0 , receiveBuffer.Length); e.Completed += new EventHandler<SocketAsyncEventArgs>(OnReceive); s.ReceiveAsync(e); // ... } private void OnReceive( object sender , SocketAsyncEventArgs e ) {} // ... if ( e.BytesTransferred > 0 ) { Int32 bytesTransferred = e.BytesTransferred; String received = Encoding.ASCII.GetString(e.Buffer , e.Offset , bytesTransferred); dataReceived += received; } autoSendReceiveEvents[ SendOperation ].Set(); // could be moved elsewhere autoSendReceiveEvents[ ReceiveOperation ].Set(); // releases mutexes } The code on the server is very similar except that it receives first and then sends a response - the server is not doing anything (that I can tell) to modify the connection after it sends a response. The problem is that the second time I hit SendReceive in the client, the connection is already in a weird state. Do I need to do something in the client to preserve the SocketAsyncEventArgs, and re-use the same object for the lifetime of the socket/connection? I'm not sure which eventargs object should hang around during the life of the connection or a given exchange. Do I need to do something, or Not do something in the server to ensure it continues to Receive data? The server setup and response processing looks like this: void Start() { // ... listenSocket.Bind(...); listenSocket.Listen(0); StartAccept(null); // note accept as soon as we start. OK? mutex.WaitOne(); } void StartAccept(SocketAsyncEventArgs acceptEventArg) { if ( acceptEventArg == null ) { acceptEventArg = new SocketAsyncEventArgs(); acceptEventArg.Completed += new EventHandler<SocketAsyncEventArgs>(OnAcceptCompleted); } Boolean willRaiseEvent = this.listenSocket.AcceptAsync(acceptEventArg); if ( !willRaiseEvent ) ProcessAccept(acceptEventArg); // ... } private void OnAcceptCompleted( object sender , SocketAsyncEventArgs e ) { ProcessAccept(e); } private void ProcessAccept( SocketAsyncEventArgs e ) { // ... SocketAsyncEventArgs readEventArgs = new SocketAsyncEventArgs(); readEventArgs.SetBuffer(dataBuffer , 0 , Int16.MaxValue); readEventArgs.Completed += new EventHandler<SocketAsyncEventArgs>(OnIOCompleted); readEventArgs.UserToken = e.AcceptSocket; dataReceived = ""; // note server is degraded for single client/thread use // As soon as the client is connected, post a receive to the connection. Boolean willRaiseEvent = e.AcceptSocket.ReceiveAsync(readEventArgs); if ( !willRaiseEvent ) this.ProcessReceive(readEventArgs); // Accept the next connection request. this.StartAccept(e); } private void OnIOCompleted( object sender , SocketAsyncEventArgs e ) { // switch ( e.LastOperation ) case SocketAsyncOperation.Receive: ProcessReceive(e); // similar to client code // operate on dataReceived here case SocketAsyncOperation.Send: ProcessSend(e); // similar to client code } // execute this when a data has been processed into a response (ack, etc) private SendResponseToClient(string response) { // create buffer with response // currentEventArgs has class scope and is re-used currentEventArgs.SetBuffer(sendBuffer , 0 , sendBuffer.Length); Boolean willRaiseEvent = currentClient.SendAsync(currentEventArgs); if ( !willRaiseEvent ) ProcessSend(currentEventArgs); } A .NET trace shows the following when sending ABC\r\n: Socket#7588182::SendAsync() Socket#7588182::SendAsync(True#1) Data from Socket#7588182::FinishOperation(SendAsync) 00000000 : 41 42 43 0D 0A Socket#7588182::ReceiveAsync() Exiting Socket#7588182::ReceiveAsync() - True#1 And it stops there. It looks just like the first send from the client but the server shows no activity. I think that could be info overload for now but I'll be happy to provide more details as required. Thanks!

    Read the article

  • Why .NET does not allow cross-thread operations?

    - by RHaguiuda
    This question is not about what is a cross-thread operation, and how to avoid it, but why internal mechanics of .NET framework does not allow a cross-thread operation. I can`t understand why a SerialPort DataReceived event cannot update a simple text box on my form and why using delegates this is possible?

    Read the article

  • Reading Binary data from a Serial Port.

    - by rross
    I previously have been reading NMEA data from a GPS via a serial port using C#. Now I'm doing something similar, but instead of GPS from a serial. I'm attempting to read a KISS Statement from a TNC. I'm using this event handler. comport.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); Here is port_DataReceived. private void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { string data = comport.ReadExisting(); sBuffer = data; try { this.Invoke(new EventHandler(delegate { ProcessBuffer(sBuffer); })); } catch { } } The problem I'm having is that the method is being called several times per statement. So the ProcessBuffer method is being called with only a partial statment. How can I read the whole statement?

    Read the article

  • Multithreading Errors in C#

    - by Adam
    Hi. I am trying to update a text box. I thought my threading code would fix the problem, but it does not. Can anyone help with this? new Thread((ThreadStart)delegate { txtCapacitance.Text = Math.Round(capacitance, 3).ToString(); }).Start(); Gives the following error: Cross-thread operation not valid: Control 'txtCapacitance' accessed from a thread other than the thread it was created on. Note that all this is being started by a dataReceived function which is called whenever USB data is received.

    Read the article

  • Is there any performance overhead in using RaiseEvent in .net

    - by Sachin
    Is there any performance overhead in using RaiseEvent in .net I have a code which is similar to following. Dim _startTick As Integer = Environment.TickCount 'Do some Task' Dim duration As Integer = Environment.TickCount - _startTick Logger.Debug("Time taken : {0}", duration) RaiseEvent Datareceived() Above code returns Time Taken :1200 Time Taken :1400 But if remove RaiseEvent it returns Time Taken :110 Time Taken :121 I am surprised that the raiseevent is called after the logging of time taken. How it effects total time taken. I am working on Compact framework. Update: In the Eventhandler I had given a MsgBox. When I removed the message box it is now showing time taken as 110,121,etc i.e. less that 500 milliseconds. If I put the Msgbox back in eventhandler it shows 1200,1400,etc i.e. more that a second. More surprised now.(Event is raised after the logging part)

    Read the article

1 2  | Next Page >