Reading from Serial Port always times out - vb.net

I am writing software for a POS terminal. This terminal has a printer that is attached to a cash drawer. I need to send a code to the printer, and listen for what is returned to determine whether or not the cash drawer is open. Using MSComm, I had logic that worked in VB6, so I know the actual Hex code I am sending is correct.
This code always returns "Error: Serial Port read timed out". I do not know what I am doing wrong with the read portion. Please advise, how do I listen for what the port is sending back as a response?
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
' Receive strings from a serial port.
Dim returnStr As String = ""
Dim x As Integer = 0
Dim com3 As IO.Ports.SerialPort = Nothing
logfile.WriteLine("STARTCASHDRAWERSTATUSCHECK")
Try
com3 = My.Computer.Ports.OpenSerialPort("COM3")
com3.WriteLine(ChrW(&H1B) & ChrW(&H75) & ChrW(&H0))
com3.BaudRate = SetPortBaudRate(9600)
com3.Parity = IO.Ports.Parity.None
com3.DataBits = SetPortDataBits(8)
com3.StopBits = SetPortStopBits(1)
com3.Handshake = IO.Ports.Handshake.RequestToSend
com3.ReadTimeout = 10000
Do
x = x + 1
Dim Incoming As String = com3.ReadLine()
logfile.WriteLine(x & "incoming" & Incoming & "x")
If Incoming Is Nothing Then
logfile.WriteLine("Button2resultEXITDO" & x)
Exit Do
Else
returnStr &= Incoming & vbCrLf
End If
If x > 10 Then
Exit Do
End If
Loop
Catch ex As TimeoutException
returnStr = "Error: Serial Port read timed out."
Finally
If com3 IsNot Nothing Then com3.Close()
End Try
logfile.WriteLine("Button2result:" & returnStr)
End Sub
Thanks in advance!

Related

How to find IPV4 from hostname / worksation Name ijn VB.net

Does anybody know how to grab the ipV4 of a machine connected over a LAN network in VB.NET? and output it via a textbox to look like a console window?
I have 3 text boxes, so 1 if for hostname/ws input and the second should show the ip address that had been grabbed and the 3rd to act as a console window to output CMD text
the code i currently have is:
Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
Dim textvar As String = txtWS.Text
Dim Command As String
Try
Command = "Ping" & " " & txtWS.Text
Shell("cmd.exe /k" & Command, 1, True)
'Get IP Address of the Host
Dim Hostname As IPHostEntry = Dns.GetHostEntry(txtWS.Text)
Dim ip As IPAddress() = Hostname.AddressList
txtIP.Text = ip(0).ToString
Catch ex As Exception
MsgBox("Unable to Ping Hostname or Workstation! Please try again, or try via IP Address." & vbCrLf & "Error: " & ex.Message, MsgBoxStyle.Critical)
End Try
End Sub
This works great for pinging but does not always return the right IP address i need to specify it to be the IPv4 every time and i want to output the console text in a textbox inside my app instead of the cmd window i have seen a few questions like this but nothing answered that incorporate these 2 functions

Background Worker Not Clearing Resources

I'm currently working on an application that fetches some information from a database using a BW. It uses a stores number, referred to as IDP and searches the correct database. It works perfectly for my needs. However, each time it runs it's adding anywhere between 10-300 KBs to RAM, it is not releasing this memory once it completes. Since this code can be ran hundreds of times a day by numerous different people on a virtual machine with limited resources I really need it to release any memory it uses. Can anyone see where I'm going wrong?
Note: I'm self-taught and I'm doing this as more of a hobby that helps me out at work and not actually employed to do this, as I'm sure some of you will be happy to know once seeing my newbie code.
Public Sub KickoffStoreBrief() 'Called when txtIDP (text box) text changes
Dim args As BW_GetStoreBriefVariables = New BW_GetStoreBriefVariables()
args.Current_IDP = txtIDP.Text.Trim
If BW_GetStoreBrief.IsBusy Then
MsgBox("Worker busy!")
Else
BW_GetStoreBrief.RunWorkerAsync(args)
End If
End Sub
Private Sub BW_GetStoreBrief_DoWork(sender As Object, e As DoWorkEventArgs) Handles BW_GetStoreBrief.DoWork
Dim args As BW_GetStoreBriefVariables = DirectCast(e.Argument, BW_GetStoreBriefVariables) 'Convert the generic Object back into a MyParameters object
Using DatabaseConnection As New SqlConnection(args.ConnectionString)
Dim command As New SqlCommand(SQL CODE IS HERE, DatabaseConnection)
command.CommandTimeout = 20
'Attempt to open the connection
command.Connection.Open()
Dim reader As SqlDataReader = command.ExecuteReader()
Dim dt As New DataTable()
dt.Load(reader)
reader = Nothing
'Check if returned anything
If dt.Rows.Item(0).Item(0) = Nothing Or dt.Rows.Item(0).Item(0).ToString = "False" Or dt.Rows.Item(0).Item(0).ToString = "" Then
'Branch not found.
GoTo Ender
End If
'Prefix 0's infront of the IDP as required
Dim CompleteIDPNumber As String = ""
If dt.Rows.Item(0).Item(0).ToString.Length < 4 Then
If dt.Rows.Item(0).Item(0).ToString.Length = 2 Then
CompleteIDPNumber = "00" & dt.Rows.Item(0).Item(0).ToString
ElseIf dt.Rows.Item(0).Item(0).ToString.Length = 3 Then
CompleteIDPNumber = "0" & dt.Rows.Item(0).Item(0).ToString
Else
CompleteIDPNumber = dt.Rows.Item(0).Item(0).ToString
End If
Else
CompleteIDPNumber = dt.Rows.Item(0).Item(0).ToString
End If
'Populate strings
Dim StoreName As String = CompleteIDPNumber & " - " & dt.Rows.Item(0).Item(1).ToString.Trim
Dim UISupports As Integer = 20 'This is the amount of characters that will fit in label space
If StoreName.Length > UISupports Then
StoreName = StoreName.Substring(0, UISupports).ToString.Trim & "..." & " (" & dt.Rows.Item(0).Item(3).ToString.Trim & ")"
Else
StoreName = StoreName & " (" & dt.Rows.Item(0).Item(3).ToString.Trim & ")"
End If
args.Brief_StoreName = StoreName
StoreName = Nothing 'We no longer need this, release it from memory
UISupports = Nothing 'We no longer need this, release it from memory
CompleteIDPNumber = Nothing 'We no longer need this, release it from memory
If dt.Rows.Item(0).Item(2) = 0 Or dt.Rows.Item(0).Item(2).ToString.Trim = "0" Then
args.Brief_POSNumber = "IS"
Else
args.Brief_POSNumber = dt.Rows.Item(0).Item(2).ToString.Trim
End If
args.Brief_Category = dt.Rows.Item(0).Item(3).ToString 'CAT
args.Brief_STCamera = dt.Rows.Item(0).Item(4).ToString 'Counter
args.Brief_Franch = dt.Rows.Item(0).Item(5).ToString
Ender:
e.Result = args
'Close connection
dt.Dispose()
command.Connection.Close()
command.Dispose()
End Using
End Sub
Private Sub BW_GetStoreBrief_RunWorkerCompleted(sender As Object, e As RunWorkerCompletedEventArgs) Handles BW_GetStoreBrief.RunWorkerCompleted
If e.Error IsNot Nothing Then
ListBox1.Items.Insert(0, Now.ToString("HH:mm:ss") & " | Error | Unable to connect to store DB.")
lblNotFound.Text = "Unable to connect to database."
Panel_NotFound.Visible = True
Panel_NotFound.BringToFront()
ErrorLogger.LogError(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Error.Message, 0)
ElseIf e.Cancelled Then
Else
' Access variables through args
Dim args As BW_GetStoreBriefVariables = DirectCast(e.Result, BW_GetStoreBriefVariables) 'Convert the generic Object back into a MyParameters object
If args.Brief_StoreName = "" Then
ListBox1.Items.Insert(0, Now.ToString("hh:mm:ss") & " | Notice | IDP " & args.Current_IDP & " not found in database.")
'show warning panel
lblNotFound.Text = "Store not found in database."
Panel_NotFound.Visible = True
Panel_NotFound.BringToFront()
GoTo Ender
Else
'Store found update UI
lblBranchInfo_StoreName.Text = args.Brief_StoreName
lblBranchInfo_POSNumber.Text = args.Brief_POSNumber
lblBranchInfo_CameraType.Text = args.Brief_STCamera
Panel_NotFound.Visible = False
Panel_NotFound.SendToBack()
End If
args = Nothing
End If
Ender:
btnStoreDetails.Enabled = True
End Sub
As you can see i've tried to make sure I'm not leaving anything behind, but the memory keeps jumping up and doesn't go down. Overall we're talking about 35MBs being used when this codes been ran only a few times and nothing else is happening with the program/form. Because this is on a remote virtual machine the program can be open for days without being closed, and with the memory usage increasing each time it will become a very big issue. Any help would be appreciated.

Closing my application After Exception shows using try,catch method VB.NET

I have function that check internet connection before my application continue working, using ping sometimes my connection are limited and that make my program crash. i want to close my application when it happen. can you help me ?
this is my sample code
If My.Computer.Network.IsAvailable Then
Try
Dim pingreq As Ping = New Ping()
Dim pinging As PingReply = pingreq.Send("www.google.com")
Dim latency As Integer = pinging.RoundtripTime
Dim status = pinging.ToString
Catch err As PingException
write_log(Date.Now.ToString("dd:MM:yyyy - HH:mm:ss") & "||" & "Connection Error" & err.ToString() & err.Message)
If Not err Is Nothing Then
Timer1.Stop()
Me.Close()
constat = 0
End If
End Try
Else
Timer1.Stop()
Me.Close()
End If

Serial port acting weird after hibernate/resume?

Guys I am having a weird problem with my vb.net application after the computer goes into hibernate mode and resumes. Before it goes into sleep mode I close all my serial ports and set it to nothing...
Private Sub SystemEvents_PowerModeChanged(ByVal sender As Object, ByVal e As PowerModeChangedEventArgs)
oEventLog.WriteEntry("Power change detected: " & e.Mode.ToString)
txtStatus.AppendText("Power change detected: " & e.Mode.ToString & vbCrLf)
If e.Mode <> PowerModes.Resume Then
Try
If Input IsNot Nothing Then
Input.Dispose()
Input.Close()
Input = Nothing
End If
If Output IsNot Nothing Then
Output.Dispose()
Output.Close()
Output = Nothing
End If
Catch
txtStatus.AppendText(Err.Description)
End Try
Else
initilizeSerialPorts()
End If
End Sub
When the computer resumes I initialize my serial ports again. The problem is when I try to open them again it says they are already in use. So I loaded up process explorer to see what has it open and it's still my application! So it seems closing them and setting them to nothing does nothing. If I close my application and re-run it everything works just fine.
Private Function initilizeSerialPorts() As Boolean
If Input IsNot Nothing Then
Input.Dispose()
Input.Close()
Input = Nothing
End If
If Output IsNot Nothing Then
Output.Dispose()
Output.Close()
Output = Nothing
End If
Input = New SerialPort(cmboInput.SelectedItem.ToString)
Output = New SerialPort(cmboOutput.SelectedItem.ToString, Input.BaudRate, Input.Parity, Input.DataBits, Input.StopBits)
Me.Refresh()
****MSGBOX HERE MAKES IT WORK?!!****
Try
If Not Input.IsOpen Then
Input.Open()
Else
MsgBox("Unable to open the serial port " & Input.PortName)
Return False
End If
Catch
MsgBox("Unable to initalize serial port " & Input.PortName & vbCrLf & "Error: " & Err.Number.ToString & " " & Err.Description)
End Try
Try
If Not Output.IsOpen Then
Output.Open()
Else
MsgBox("Unable to open the serial port " & Output.PortName)
Return False
End If
Catch
MsgBox("Unable to initalize serial port " & Output.PortName & vbCrLf & "Error: " & Err.Number.ToString & " " & Err.Description)
End Try
Return True
End Function
Ok here is the kicker...if I put a message box before I open my port again it works? No message box and I get a failed to open port message it's in use. Any ideas why this might be happening?
Thanks in advance

UDP SocketException - Only one usage of each socket address is normally permitted

As much as there are many questions on here that are very similar, none of the supplied answers have helped me, which makes me sad :(
I've got a very large management system that I've been tasked to write some UDP packet sending/receiving for. I'd already written a prototype and all was well, so I started merging my code into said system. However, I've now got a (not show-stopping, but annoying) SocketException popping up:
System.Net.Sockets.SocketException occurred
ErrorCode=10048
Message=Only one usage of each socket address (protocol/network address/port) is normally permitted
NativeErrorCode=10048
Source=System
StackTrace:
at System.Net.Sockets.Socket.DoBind(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.Sockets.Socket.Bind(EndPoint localEP)
at System.Net.Sockets.UdpClient..ctor(Int32 port, AddressFamily family)
at System.Net.Sockets.UdpClient..ctor(Int32 port)
at Goose.Job.DeviceServerUDPReceiver.InitialiseReceiverClient() in C:\WORK\Trunk\GooseOrders\Classes\SheetCounter\DeviceServerUDPReceiver.vb:line 39
Here is the UDPReceiver class - Which is responsible for just sitting in a loop and waiting for responses from the Device Servers we've got dotted about the place.
Public Class DeviceServerUDPReceiver : Implements IDisposable
'///////////////////////////////////////////////////////////////////////////////
' CONSTANTS
'///////////////////////////////////////////////////////////////////////////////
Private Const TIBBO_DEVICE_REPLY_CMD_START As Integer = 0
Private Const TIBBO_DEVICE_REPLY_CMD_END As Integer = 3
Private Const TIBBO_MESSAGE_REPLY_DIVIDER As String = "_"
Private Const TIBBO_DEVICE_REPLY_OK As String = "OK"
'///////////////////////////////////////////////////////////////////////////////
' MEMBER VARIABLES
'///////////////////////////////////////////////////////////////////////////////
Public _ReceivingClient As System.Net.Sockets.UdpClient
Public _iReceivingPort As Integer = 2002
Public _thReceivingThread As System.Threading.Thread
Public _bClosing As Boolean
'///////////////////////////////////////////////////////////////////////////////
' EVENTS
'///////////////////////////////////////////////////////////////////////////////
Public Event GotDeviceResponse(ByVal sResponse As String)
Public Event FoundNewDevice(ByVal TibboObject As TibboDevice)
'///////////////////////////////////////////////////////////////////////////////
' METHODS
'///////////////////////////////////////////////////////////////////////////////
' Initialises the UDP receiver client on the specified port number. Then runs
' a listening thread constantly waiting to receive udp messages
Public Sub InitialiseReceiverClient()
Try
' TODO - FIX SOCKET EXCEPTION HERE - NOT THREAD ISSUE - THIS IS DUE TO
' THE SOCKET NOT BEING CLOSED. BUT SEEING HOW UDP IS CONNECTIONLESS .... ?!
_ReceivingClient = New System.Net.Sockets.UdpClient(_iReceivingPort)
Dim thStartThread As Threading.ThreadStart = New Threading.ThreadStart(AddressOf SitAndReceive)
_thReceivingThread = New Threading.Thread(thStartThread)
_thReceivingThread.IsBackground = True
_thReceivingThread.Start()
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine("Socket Exception: " & ex.Message)
Finally
End Try
End Sub
' The endless loop listener thread. Will sit and wait for udp packets to
' process
Private Sub SitAndReceive()
Dim epEndPoint As System.Net.IPEndPoint = New System.Net.IPEndPoint(System.Net.IPAddress.Any, _iReceivingPort)
' infinite loop to listen for udp messages
While (_bClosing = False)
Try
Dim sMessage As String = ""
Dim byData() As Byte
byData = _ReceivingClient.Receive(epEndPoint)
sMessage = System.Text.Encoding.ASCII.GetString(byData)
Console.WriteLine(sMessage)
ProcessIncomingUDPDataMessage(sMessage)
Catch ex As System.Net.Sockets.SocketException
Console.WriteLine(ex.Message)
End Try
End While
End Sub
' close the connection to the receiving udp socket
Public Sub Close()
_bClosing = True
End Sub
' Processes incoming udp packets for answeres from the device servers
Private Sub ProcessIncomingUDPDataMessage(ByVal sMessage As String)
' UDP Data packet from Tibbo devices is set out as follows
'
' CMD_ANSWER
' Where "CMD" = The command the device is replying too and
' "ANSWER" = It's reply
Select Case sMessage.Substring(TIBBO_DEVICE_REPLY_CMD_START, TIBBO_DEVICE_REPLY_CMD_END)
Case TibboDevice.DEVICE_COMMAND_ATO
'/////////////////////////////////////////////////////////////////////////
' Any Tibbo's out there reply message
'/////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sMacAddress As String = s(2) ' the replying devices' mac address
Dim sIpAddress As System.Net.IPAddress = System.Net.IPAddress.Parse(s(3)) ' ip
Dim sNetBiosName As String = s(1) ' netbios name
Dim iTibboStatus As TibboDevice.ETIIBO_DEVICE_STATE = TibboDevice.ETIIBO_DEVICE_STATE.TIBBO_DEVICE_STATE_BAD ' status
' set this device status depending on the reply
If s(4) = TIBBO_DEVICE_REPLY_OK Then
iTibboStatus = TibboDevice.ETIIBO_DEVICE_STATE.TIBBO_DEVICE_STATE_OK
End If
' create a new tibbo device to pass back to the main form
Dim Tibbo As TibboDevice = New TibboDevice(sMacAddress, sIpAddress, sNetBiosName, iTibboStatus)
' raise event to add this to our list
RaiseEvent FoundNewDevice(Tibbo)
Case TibboDevice.DEVICE_COMMAND_STS
'//////////////////////////////////////////////////////////////////////////
' Status reply message
'//////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' format our string nicely
sResult &= "Mac Address: " & vbTab & vbTab & s(1)
sResult &= Environment.NewLine & "IP Address: " & vbTab & vbTab & s(2)
sResult &= Environment.NewLine & "Device Name: " & vbTab & vbTab & s(3)
sResult &= Environment.NewLine & "TiOS FW: " & vbTab & vbTab & s(4)
sResult &= Environment.NewLine & "Goose SC FW: " & vbTab & vbTab & s(5)
sResult &= Environment.NewLine & "System Uptime: " & vbTab & vbTab & s(6)
sResult &= Environment.NewLine & "System Time: " & vbTab & vbTab & s(7)
sResult &= Environment.NewLine & "System Status: " & vbTab & vbTab & s(8)
RaiseEvent GotDeviceResponse(sResult)
Case TibboDevice.DEVICE_COMMAND_ASC
'////////////////////////////////////////////////////////////////////////////
' Average sheet count message
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
RaiseEvent GotDeviceResponse(sResult)
Case TibboDevice.DEVICE_COMMAND_NAM
'////////////////////////////////////////////////////////////////////////////
' Changed device name reply message
' Device will reply NAM_[NEWNAME] - once it's set it's new name
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
RaiseEvent GotDeviceResponse(sResult)
Case TibboDevice.DEVICE_COMMAND_IDX
'////////////////////////////////////////////////////////////////////////////
' Device responds with it's device id
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' TODO - do something with the result
Case TibboDevice.DEVICE_COMMAND_RBT
'////////////////////////////////////////////////////////////////////////////
' Device is going down for a reboot - not much to do here, we have to wait
'////////////////////////////////////////////////////////////////////////////
Case TibboDevice.DEVICE_COMMAND_BUZ
'////////////////////////////////////////////////////////////////////////////
' Device has played it's buzz sound - ignore
'////////////////////////////////////////////////////////////////////////////
Case TibboDevice.DEVICE_COMMAND_FSH
'////////////////////////////////////////////////////////////////////////////
' Device flashed it's LEDs - ignore
'////////////////////////////////////////////////////////////////////////////
Case TibboDevice.DEVICE_COMMAND_AIP
'////////////////////////////////////////////////////////////////////////////
' Device replies with it's actual ip address
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' TODO - do something with the result
Case TibboDevice.DEVICE_COMMAND_CBC
'////////////////////////////////////////////////////////////////////////////
' Device replies with it's current box count
'////////////////////////////////////////////////////////////////////////////
Dim s() As String = sMessage.Split(TIBBO_MESSAGE_REPLY_DIVIDER)
Dim sResult As String = ""
' TODO - do something with the result
Case TibboDevice.DEVICE_COMMAND_STP
'////////////////////////////////////////////////////////////////////////////
' Device has been stopped - won't reply. Only way to bring it back to life
' is to press the 'reset' button on the actual unit - ignore
'////////////////////////////////////////////////////////////////////////////
End Select
End Sub
Protected Overridable Overloads Sub Dispose(disposing As Boolean)
If (disposing) Then
' free managed objects
'_ReceivingClient = Nothing
_bClosing = True
End If
End Sub
Public Overloads Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
End Class
Now, all I'm doing in the main form, is: When my listener form is closed - I want to close the listener down (obviously)... For this, I'm using Dispose(). However, when someone wants to start it up again, said exception occurs on the byData = _ReceivingClient.Receive(epEndPoint) line in the SitAndReceive procedure.
Since UDP is transaction based and its sockets (possibly theoretically) can't be in a CLOSE_WAIT state, what is stopping me from closing it down and then immediately relaunching the listener?
I must admit I'm new to UDP sockets, so far however, I've found them a joy to work with and even though this exception wouldn't crash an end-users software (with a simple try/catch), it does have me intrigued and I'd like to understand why it's happening.
Any help is very much appreciated.
Managed to figure this out in the end. Apparently if you want to have more than one connection to a socket, you have to manually configure it, like so:
Dim endPoint = New System.Net.IPEndPoint(0, _iReceivingPort)
_ReceivingClient = New System.Net.Sockets.UdpClient()
_ReceivingClient.ExclusiveAddressUse = False
_ReceivingClient.Client.SetSocketOption(Net.Sockets.SocketOptionLevel.Socket, Net.Sockets.SocketOptionName.ReuseAddress, True)
_ReceivingClient.Client.Bind(endPoint)
Works now, so I'm happy.