Serial Port Data Received only working when breakpoint set - vb.net

I have a program that starts an ultrasonic wind gauge and then requests the reading after 5 seconds. When I put a breakpoint in the Data Received handler the data being returned from the wind gauge is processed correctly, however if I do not have the breakpoint in place the data is ignored. The code is as follows (startWG is called when F2 is pressed on the keyboard)
Dim WGCom As New SerialPort
Private Function initWG() As Boolean
Dim WGPort = My.Settings.WGCom
If Not (WGCom.IsOpen) Then
Try
WGCom.PortName = "COM" & WGPort
WGCom.Parity = Parity.Even
WGCom.DataBits = 7
WGCom.StopBits = StopBits.One
WGCom.Handshake = Handshake.None
'WGCom.ReadTimeout = 3000
WGCom.WriteTimeout = 50000
WGCom.Open()
Catch ex As InvalidOperationException
MessageBox.Show(ex.Message)
Catch ex As UnauthorizedAccessException
MessageBox.Show(ex.Message)
Catch ex As System.IO.IOException
MessageBox.Show(ex.Message)
End Try
End If
If (WGCom.IsOpen) Then
Return True
Else
Return False
End If
End Function
#If (WGPort > 0) Then
#End If
'What to do with the wind gauge data when it is received.
Public Sub DataReceivedHandler(
sender As Object,
e As SerialDataReceivedEventArgs)
Dim sp As SerialPort = CType(sender, SerialPort)
Dim indata As String = sp.ReadExisting()
'MsgBox("Seen Data from WG " & indata)
If (indata.Length 0) Then
reading = indata.Substring(plus - 1, 5)
read = True
End If
Catch ex As Exception
End Try
Try
minus = InStr(indata, "-")
If (minus > 0) Then
reading = indata.Substring(minus - 1, 5)
read = True
End If
Catch ex As Exception
End Try
If (read) Then
WGReading = reading
' MsgBox(reading)
WGHasRead = True
read = False
plus = 0
minus = 0
Dim forClass As New WGReads
forClass.Reading = reading
SerialLog.WGReadings.Add(forClass)
RaiseEvent PropertyChanged("DataReceivedHandler", New PropertyChangedEventArgs("LastWG"))
WGFill(wgfield, hjevent)
End If
End Sub
Public Sub WGStart(wg() As String, hjevents As hjCompetition)
wgfield = wg
hjevent = hjevents
If (initWG()) Then
AddHandler WGCom.DataReceived, AddressOf DataReceivedHandler
Dim initBuffer(9) As Byte
initBuffer(0) = &H1
initBuffer(1) = &H13
initBuffer(2) = &H43
initBuffer(3) = &H57
initBuffer(4) = &H49
initBuffer(5) = &H2
initBuffer(6) = &H30
initBuffer(7) = &H35
initBuffer(8) = &H4
Try
WGCom.Write(initBuffer, 0, initBuffer.Length)
Catch ex As System.TimeoutException
End Try
'After init wait for the wind gauge to catch up
System.Threading.Thread.Sleep(100)
Dim outputBuffer1(9) As Byte
outputBuffer1(0) = &H1
outputBuffer1(1) = &H13
outputBuffer1(2) = &H43
outputBuffer1(3) = &H57
outputBuffer1(4) = &H53
outputBuffer1(5) = &H2
outputBuffer1(6) = &H30
outputBuffer1(7) = &H30
outputBuffer1(8) = &H4
Try
WGCom.Write(outputBuffer1, 0, outputBuffer1.Length)
Catch ex As System.TimeoutException
End Try
'Wait for the wind gauge to finish
wait(5500)
'Add a handler for when data is received from the Wind Gauge
AddHandler WGCom.DataReceived, AddressOf DataReceivedHandler
'Get the reading from the wind gauge
Dim getBuffer(9) As Byte
getBuffer(0) = &H1
getBuffer(1) = &H13
getBuffer(2) = &H43
getBuffer(3) = &H57
getBuffer(4) = &H4F
getBuffer(5) = &H2
getBuffer(6) = &H30
getBuffer(7) = &H30
getBuffer(8) = &H4
Try
WGCom.Write(getBuffer, 0, getBuffer.Length)
Catch ex As System.TimeoutException
End Try
'closeCom()
End If
End Sub
It doesn't matter where the breakpoint in the Data Received handler is but as long as there is one. If the breakpoint is in the WGStart Sub it doesn't work either.
Surely a breakpoint should not change the way the program executes?
Thanks in advance for your help.

Adding in a wait(100) has fixed the issue. The code for the wait sub is as follows for others looking for a solution to similar issues
Private Sub wait(ByVal interval As Integer)
Dim sw As New Stopwatch
sw.Start()
Do While sw.ElapsedMilliseconds < interval
' Allows UI to remain responsive
Application.DoEvents()
Loop
sw.Stop()
End Sub

Related

Can I send data using the same TCP port?

I have a TCP listener working but doesn't send anything. To get this TCP listener working I have a thread in a endless loop.
Now I need to answer to some specific packets and also be able to send data when the user request it using the same port that the TCP listener is using. The remote device keeps the connection open to be able to receive new data.
So, I must to create a new TCP client to send data to the current connected client or use the current listener socket?
Public Sub StopServer()
TcpOpen = False
Server.Stop()
ServerThread = Nothing
End Sub
Public Sub InitServer(ByVal Port As Integer)
Server = New TcpListener(IPAddress.Any, Port)
ServerThread = New Thread(AddressOf ConnectionListener)
ServerThread.IsBackground = True
ServerThread.Start()
TcpOpen = True
End Sub
Private Sub ConnectionListener()
Server.Start()
While True
If TcpOpen Then
If Server.Pending Then
Dim client As TcpClient = Server.AcceptTcpClient()
Dim T As New Thread(AddressOf StartTcpClient)
client.ReceiveBufferSize = 128000
T.IsBackground = True
T.Start(client)
Else
System.Threading.Thread.Sleep(10)
End If
Else
Exit While
End If
End While
End Sub
Private Sub StartTcpClient(ByVal client As TcpClient)
Dim bytesRead As Integer
Dim RxBuffer(1500) As Byte 'Original 1024
Dim RxDataStr As String = ""
Dim TxBuffer(1500) As Byte
Dim TxDataStr As String = ""
Dim TempData As String
Dim DataReceived As Boolean = False
Dim TimeX As Integer = 0
Dim RemoteIP As Net.IPEndPoint = client.Client.RemoteEndPoint
Dim RemoteIPStr As String = RemoteIP.Address.ToString
WriteRTBLog("Se inicio una nueva conexion TCP con la IP " & RemoteIPStr, Color.DarkViolet)
WriteRTBLog("Esperando datos...", Color.Black)
client.ReceiveTimeout = 30000
Try
While True
If client.GetStream.DataAvailable Then
bytesRead = client.GetStream.Read(RxBuffer, 0, RxBuffer.Length)
TimeX = 0 'Reset timer
If bytesRead > 0 Then
TempData = System.Text.ASCIIEncoding.UTF8.GetString(RxBuffer, 0, bytesRead) 'UTF8
RxDataStr += TempData
If Not DataReceived Then
DataReceived = True
WriteRTBLog("Se estan recibiendo datos...", Color.Purple)
End If
If RxDataStr.Contains("<") Then
'Process data
TxDataStr = AnswerProcessor(RxDataStr)
'New code- trying to send data
If TxDataStr.Length > 5 Then
TxBuffer = System.Text.Encoding.ASCII.GetBytes(TxDataStr)
client.Client.Send(TxBuffer)
End If
RxDataStr = "" 'Clean buffer
End If
End If
Else
If Not client.Connected Then
Exit While 'Close connection
Else
System.Threading.Thread.Sleep(10)
End If
End If
End While
If RxDataStr.Length > 0 Then
WriteRTBLog(String.Format("Se recibieron {0} bytes desde {1}", RxDataStr.Length.ToString, RemoteIPStr), Color.ForestGreen)
If Not client.Connected Then
WriteRTBLog("Conexion cerrada", Color.Black)
End If
End If
Catch ex As Exception
client.Close()
WriteRTBLog("Error en la conexion a " & RemoteIPStr, Color.Red)
WriteRTBLog(ex.Message, Color.Red)
WriteRTBLog(ex.StackTrace, Color.Red)
If RxDataStr.Length > 0 Then
' Create the file.
Dim PathX As String = Application.StartupPath & "\TCP_File_err" & CLng(DateTime.UtcNow.Subtract(New DateTime(1970, 1, 1)).TotalMilliseconds) & ".TCP"
Using fs As FileStream = File.Create(PathX)
Dim data As Byte() = New ASCIIEncoding().GetBytes(RxDataStr)
' Add some information to the file.
fs.Write(data, 0, data.Length)
End Using
WriteRTBLog(String.Format("Se recibieron {0} bytes desde {1} y se guardaron en {2}.", RxDataStr.Length.ToString, RemoteIPStr, PathX), Color.ForestGreen)
End If
End Try
End Sub
So, I must to create a new TCP client to send data to the current connected client or use the current listener socket?
No, neither. Use the socket you accepted that's connected to the client.

vb.net SerialPort writing and receiving

I have an issue with reading the results of a serialport communication.
If have multiple functions, which are executing different commands on my device and also receiving and process the sent results on slightly different ways.
If i call the functions all at once, its not working 100% reliable. If i call only one of these functions, all of them working perfectly. Im assuming, thinks going a little to fast for the slow serialPort communication, so some functions dont get propper results when calling all "at once"
Code which calls 3 functions (Error on different Positions: "Index out of (array) range" or "CRC incorrect")
Private Sub btn_initialize_Click(sender As Object, e As EventArgs) Handles btn_initialize.Click
Dim actual_mw As Double
Dim attenuated As Integer
'open (virtual)COMport
If rfid.init_serialport(cb_com.SelectedItem.ToString) = True Then
flp_data.Visible = True
lbl_snr_data.Text = rfid.get_serial_number()
lbl_type_data.Text = rfid.get_reader_type
Dim collection As MatchCollection = Regex.Matches(rfid.get_attennuation, "\d+")
attenuated = collection(1).Value
If attenuated = 0 Then
lbl_leistung_data.Text = "100mW / 100mW"
Else
actual_mw = 100 - (10 ^ (attenuated / 10))
lbl_leistung_data.Text = Math.Round(actual_mw, 2) & "mW / 100mW"
End If
Else
MsgBox("Error! COM-Schnittstelle konnte nicht initialisiert werden!", MsgBoxStyle.Critical, "Error")
End If
End Sub
Intialize and Dispose SerialPort
Public Class RFE
Private RF_CHECKSUM As Byte
Private device_output() As Byte
Private data() As Byte
Private device_input() As Byte
Private sp As SerialPort
Public Function init_serialport(portName As String) As Boolean
Try
sp = New SerialPort
sp.PortName = portName
sp.BaudRate = 9600
sp.Parity = Parity.None
sp.DataBits = 8
sp.StopBits = StopBits.One
sp.Handshake = Handshake.None
sp.ReadTimeout = 500
sp.WriteTimeout = 500
sp.Open()
If sp.IsOpen Then
Return True
Else
Return False
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
Public Function disp_serialport()
Try
sp.Dispose()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
Functions
Public Function get_serial_number() As String
Try
Dim serial_number As String
ReDim data(8)
data(0) = RF_START_BYTE0
data(1) = RF_START_BYTE1
data(2) = RF_START_BYTE2
data(3) = RF_COMMAND_START_BYTE
data(4) = RF_READER_COMMON
data(5) = RF_GET_SERIAL_NUMBER
data(6) = RF_LENGTH_START_BYTE
data(7) = &H0
data(8) = RF_CHECKSUM_START_BYTE
RF_CHECKSUM = Hex(calc_xor(data, 1))
device_input = data
Array.Resize(device_input, data.Length + 1)
device_input(9) = "&H" & RF_CHECKSUM
sp.Write(device_input, 0, device_input.Length)
ReDim device_output(sp.BytesToRead)
sp.Read(device_output, 0, device_output.Length - 1)
If calc_xor(device_output, 3) <> device_output(14) Then
MsgBox("CRC incorrect!", MsgBoxStyle.Critical, "Error")
Form1.Close()
End If
serial_number = Hex(device_output(9)).PadLeft(2, "0") & "-" & Hex(device_output(10)).PadLeft(2, "0") & "-" & Hex(device_output(11)).PadLeft(2, "0") & "-" _
& Hex(device_output(12)).PadLeft(2, "0")
device_output = Nothing
data = Nothing
RF_CHECKSUM = Nothing
sp.DiscardInBuffer()
sp.DiscardOutBuffer()
Return serial_number
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Function
The other functions are structure-vise the same, only the sent bytes and the processing of the result is slightly different.
As I said, im assueming the problem is the transaction of the signals (possibly in both directions) so the SerialPort and/or Device cant handle things fast enough.
What do I have to do so that the communication runs reliably/sequentially?
Maybe DataReceivedHandler could fix the Problem? But for every function I call, the processing of the result is different, how do I implement this in the DataReceivedHandler then (if the Handler could fix the Problem)?
Thank you all!

data still saving on zero

in my code the data is saving if no.of days to complete=0.I want it should not happen
in my code a msg comes "time to complete and time to acknowledged can be only be posiitve" but still data saves.i dont want it to be saved !!
Protected Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Try
Dim i As Integer
If gvBanckmark.Rows.Count > 0 Then
For i = 0 To gvBanckmark.Rows.Count - 1
Dim lblBenchMarkID As Label = CType(gvBanckmark.Rows(i).FindControl("lblBenchMarkID"), Label)
Dim lblSubCategoryId As Label = CType(gvBanckmark.Rows(i).FindControl("lblSubCategoryId"), Label)
Dim ddlFrequencyTypeAcknowledge As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeAcknowledge"), DropDownList)
Dim ddlFrequencyTypeComplete As DropDownList = CType(gvBanckmark.Rows(i).FindControl("ddlFrequencyTypeComplete"), DropDownList)
Dim txtTimeToAcknowledge As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToAcknowledge"), TextBox)
Dim txtTimeToComplete As TextBox = CType(gvBanckmark.Rows(i).FindControl("txtTimeToComplete"), TextBox)
Dim objBenchMark As BO.BenchMark = New BO.BenchMark()
objBenchMark.BuildingID = Convert.ToInt32(ddlBuilding.SelectedValue)
objBenchMark.CategoryID = Convert.ToInt32(ddlCategory.SelectedValue)
objBenchMark.SubCategoryID = Convert.ToInt32(lblSubCategoryId.Text.ToString())
objBenchMark.FrequencyTypeToAcknowledge = ddlFrequencyTypeAcknowledge.SelectedValue.ToString()
objBenchMark.FrequencyTypeToComplete = ddlFrequencyTypeComplete.SelectedValue.ToString()
objBenchMark.TimeToAcknowledge = Convert.ToInt32(txtTimeToAcknowledge.Text.ToString())
objBenchMark.TimeToComplete = Convert.ToInt32(txtTimeToComplete.Text.ToString())
If lblBenchMarkID.Text.ToString() = 0 Then
objBenchMark.BenchMarkID = 0
objBenchMark.CreateByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.InsertBechMarkData(objBenchMark)
Else
objBenchMark.BenchMarkID = Convert.ToInt32(lblBenchMarkID.Text.ToString())
objBenchMark.ModifiedByUserId = UserWrapper.GetCurrentUser().ContactID
BO.BenchMark.UpdateBechMarkData(objBenchMark)
End If
Next i
End If
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"
Catch ex As Exception
lblError.Text = ex.Message
lblError.Visible = True
End Try
End Sub
Your data is not being saved, but the message telling you the data has been saved is being presented, despite it's saved or not.
Move thses lines inside the if-end if:
lblError.Visible = True
lblError.Text = "<a cssClass=""messageGood"">Benchmark data has been saved sucessfully.</a>"

File upload using Threading

I have written a code to upload a file using thread.I have place a simple file upload control and a button on a page.The code looks like this-
Protected Sub btnUpload_Click(ByVal sender As Object,
ByVal e As EventArgs) Handles btnUpload.Click
Dim timeStart As TimeSpan = Nothing
Dim timeEnd As TimeSpan = Nothing
Dim timeDiff As TimeSpan = Nothing
Dim ex As Exception = Nothing
Dim FileNameWithoutExtension As String = String.Empty
Try
Dim objTh As Thread = Nothing
objTh = New Thread(AddressOf SaveFileByBuffering)
timeStart = DateTime.Now.TimeOfDay
objTh.IsBackground = True
FileNameWithoutExtension = System.IO.Path.GetFileName(FldUploadThreading.FileName)
objTh.Start("New_" + FileNameWithoutExtension)
objTh.Name = "ARAThreadFileBuffer"
objTh.Join()
timeEnd = DateTime.Now.TimeOfDay
timeDiff = timeEnd - timeStart
Catch exThAbort As ThreadAbortException
ex = exThAbort
Catch exTh As ThreadStartException
ex = exTh
Catch exCommon As Exception
ex = exCommon
End Try
End Sub
the method to be called using thread:
Public Function SaveFileByBuffering(ByVal lstrFilePath As String)
Dim bufferSize As Integer = 512
Dim buffer As Byte() = New Byte(bufferSize - 1) {}
Dim pathUrl As String = ConfigurationManager.AppSettings("strFilePath").ToString()
Dim uploadObj As UploadDetail = New UploadDetail()
uploadObj.IsReady = True
uploadObj.FileName = lstrFilePath
uploadObj.ContentLength = Me.FldUploadThreading.PostedFile.ContentLength
Me.Session("UploadXDetail") = uploadObj
Dim Upload As UploadDetail = DirectCast(Me.Session("UploadXDetail"), UploadDetail)
Dim fileName As String = Path.GetFileName(Me.FldUploadThreading.PostedFile.FileName)
Using fs As New FileStream(Path.Combine(pathUrl, lstrFilePath), FileMode.Create)
While Upload.UploadedLength < Upload.ContentLength
Dim bytes As Integer = Me.FldUploadThreading.PostedFile.InputStream.Read(buffer, 0, bufferSize)
fs.Write(buffer, 0, bytes)
Upload.UploadedLength += bytes
End While
End Using
End Function
There are two issues:
When some one clicks on the same button simultaneously the thread behavior works in a different way , some time page crashes.
When this process i have tested on multiuser environment with 60 users and file size is 25 MB each user the page crashed.
I have .net 3.5 so i have no choice with advance version of file upload in 2010 or later version.

System.FormatException On ConvertFromBase64String

This is such a great place to ask questions!
I'm facing one problem.
I'm trying to send an image from an AutoIT client over to a server that is written in VB.NET
Here is the code for the AutoIT Client:
TCPStartup()
$MainSocket = TCPConnect("127.0.0.1", 9832)
$PATH = _ScreenCapture_Capture("")
$Data2Send = "RemoteDESK|" & _Base64Encode(HBITMAP_To_Bytes($PATH)) & "<EOF>"
TCPSend($MainSocket, $Data2Send)
And here is the code for the VB.NET server:
Data handler:
Private Sub GotInfo(ByVal Data As String, ByVal Sender As Socket)
Dim Cut() As String = Data.Split("|")
Select Case Cut(0)
Case "RemoteDESK"
Dim ImgString As String = Cut(1)
PictureBox1.Image = B64ToImage(ImgString)
End Select
End Sub
Base 64 String to Image Fucntion:
Private Function B64ToImage(ByVal B64 As String) As Image
Dim ByAr() As Byte = Convert.FromBase64String(B64) 'Exception Happens here
Dim img As Image
Dim MS As New MemoryStream(ByAr)
Try
img = Image.FromStream(MS)
Catch ex As Exception
Return Nothing
End Try
Return img
End Function
The OnReceive Sub:
Private Sub OnReceive(ByVal ar As IAsyncResult)
Dim Content As String = String.Empty
Dim State As StateObject = DirectCast(ar.AsyncState, StateObject)
Dim Handler As Socket = State._MySocket
Try
Dim BytesRead As Integer = Handler.EndReceive(ar)
If BytesRead > 0 Then
State._SB.Append(Encoding.ASCII.GetString(State.Data))
Content = State._SB.ToString
If Content.IndexOf("<EOF>") > -1 Then
Dim ReadContent As String = Content.Remove(Content.IndexOf("<EOF>"))
RaiseEvent GotInfo(ReadContent, State._MySocket)
Else
Handler.BeginReceive(State.Data, 0, State.BufferSize, SocketFlags.None, New AsyncCallback(AddressOf OnReceive), State)
End If
End If
Catch ex As Exception
RaiseEvent ClientDC(Handler)
End Try
End Sub
Alright, so now I used a text comparing tool, and every time on line 53, the received string has changed, as in the the 2 lines of text are on the same line compared to the autoit's output.
The autoit output is the readable one.