how to use serial port in a service application environment constantly listening for data

930 views Asked by At

Ive written a service application that listens to a port for any communication that may come through, our lab will run a certain test which will send serial data down every couple hours or so. the service is runs picks up the data fine for a few hours and then mysteriously stops. the system eventlog says the service terminated unexpectedly. and in the application event log it has a more descriptive .NET error,

Application: BondTestService.exe Framework Version: v4.0.30319 Description: The process was terminated due to an unhandled exception. Exception Info: System.ObjectDisposedException at System.Runtime.InteropServices.SafeHandle.DangerousAddRef(Boolean ByRef) at System.StubHelpers.StubHelpers.SafeHandleAddRef(System.Runtime.InteropServices.SafeHandle, Boolean ByRef) at Microsoft.Win32.UnsafeNativeMethods.GetOverlappedResult(Microsoft.Win32.SafeHandles.SafeFileHandle, System.Threading.NativeOverlapped*, Int32 ByRef, Boolean) at System.IO.Ports.SerialStream+EventLoopRunner.WaitForCommEvent() at System.Threading.ThreadHelper.ThreadStart_Context(System.Object) at System.Threading.ExecutionContext.RunInternal(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object, Boolean) at System.Threading.ExecutionContext.Run(System.Threading.ExecutionContext, System.Threading.ContextCallback, System.Object) at System.Threading.ThreadHelper.ThreadStart()

i was reading how services behave and how serial ports behave, so correct me if im wrong if the there is a 2 hour gap or so inbetween tests, the service will assume that its not running and stop itself?

I also read after reading the buffer from the serial port i append to a string builder object like below and do what i need to the string, then what happens to the serial port does it just stay open waiting for next value or do i have to close it and reopen it in order to refresh it?

Not sure how to handle this as it needs to be open waiting for the lab tester to send his data at any given time.

Imports System
Imports System.Data.SqlClient
Imports System.IO.Ports
Imports System.Net.Mime
Imports Microsoft.Win32
Imports System.IO
Imports System.Text.RegularExpressions
Imports BondTestService.PI
Imports PCA.Core.Configuration

Public Class Bond
Dim WithEvents serialPort As New IO.Ports.SerialPort
Public Delegate Sub myDelegate()
Public RawString As New System.Text.StringBuilder
Public value As String
Public BondTest As Integer = 10

 #Region "Commport Traffic and Configuration Validations"
 Public Sub StartListening()

    If serialPort.IsOpen Then
        serialPort.Close()
        ErrorLog2(Now.ToString & "Port Closed because StartListening method started over")
    End If

    Try
        With serialPort
            .PortName = Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("commport")
            .BaudRate = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("baudrate"))
            If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("parity") = 0 Then
                .Parity = Parity.None
           End If
            If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("stopbits") = 1 Then
                .StopBits = StopBits.One
            End If
            .DataBits = CInt(Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("bytesize"))
            .Handshake = Handshake.None
            If Registry.LocalMachine.OpenSubKey("SOFTWARE\Wow6432Node\AUTOLABDEVICESERVICE\bondtest", True).GetValue("RtsControl") = 1 Then
                .RtsEnable = True
            Else
                .RtsEnable = False
           End If
        End With
        serialPort.Open()

        'debug
        'ErrorLog2("Listening to COM 19, SerialPort has been Opened")

    Catch ex As Exception
         ErrorLog2(Now.ToString & ex.tostring)
    End Try
End Sub

Public Function Filelocator() As String

    ' Dim filePath As String = IO.Path.Combine(Application.StartupPath, "bondtest.bat")
    Dim filePath As String = IO.Path.Combine("C:\Program Files (x86)\PIPC\Interfaces\Lab", "BondTest.bat")
    'Dim reader As New System.IO.StreamReader(filePath)
    Dim LineNumber = 4
    Using file As New StreamReader(filePath)
        ' Skip all preceding lines: '
        For i As Integer = 1 To LineNumber - 1
            If file.ReadLine() Is Nothing Then
                ErrorLog2("LineNumber")
            End If
        Next
        ' Attempt to read the line you're interested in: '
        Dim line As String = file.ReadLine()
        If line Is Nothing Then
            ErrorLog2("LineNumber")
        End If
        Return line
    End Using
End Function

Private Sub serialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort.DataReceived
    Try
        If GetBondInterfaceStatus = 1 Then
            UPdateVariable()
        Else
            exit Sub
        End If
    Catch ex As Exception
        Errorlog2(Ex.Tostring)
    End Try
End Sub



#End Region

#Region "String Handling"
Public Sub UPdateVariable()
    With RawString
        .Append(serialPort.ReadLine())
    End With
    try
        ErrorLog2(now.ToString & RawString.ToString)
        InsertTestDataDEBUG(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()), RawString.tostring)
        InsertTestData(GetRecordID, BondTest, BondTestType.ToUpper.ToString, GetBondPosition(), StringParser(RawString.ToString()))
        RawString.Clear()
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
End Sub

Public Function StringParser(RawString As String)As Double ()
    Dim Moisture = RawString
    Dim pattern As String = "[0-9],"
    Dim regex As New Regex(pattern)
    Dim Counter As Integer = 0
    Dim dblValues(1) As Double
    Dim values As String() = Moisture.Split(New Char() {" "c})


    for i = 0 to values.Count - 1
        if regex.IsMatch(values(i)) Then
            dblValues(Counter) = CDbl(values(i).Substring(0,1))
            Counter = Counter + 1
        Elseif values(i) = "" Then
            continue for
        else
            if Double.TryParse(values(i), dblValues(Counter)) Then
                Counter = Counter + 1 
            End If
        End If

    Next
    Return dblValues
End Function

#End Region

#Region "SQL Statements"
Private Sub InsertTestData(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double)
    Dim InsertQuery As String = ""
    Dim conn As New BondSQLConnection("PaperTests")
   ' Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)

    conn("@RecordID") = RecordID
    conn("@Test") = BondTest
    conn("@TestType") = TestType
    conn("@TestPos") = TestPos
    conn("@TestData") = dataArray(1)
    conn("@TestDateTime") = now.tostring

    InsertQuery = "INSERT INTO PaperTests.dbo.PaperTestValues(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp) VALUES (@RecordID, @Test, @TestType, @TestPos, @TestData, @TestDateTime)"
    Try
        conn.ExecuteNonQuery(InsertQuery)
        IncrementTestPosition
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try

End Sub

Private Sub InsertTestDataDEBUG(RecordID As Integer, BondTest As Integer, TestType As String, TestPos As Integer, dataArray() As Double, rawString As String)
    Dim InsertQuery As String = ""
    Dim conn As New BondSQLConnection("PaperTests")

    conn("@RecordID") = RecordID
    conn("@Test") = BondTest
    conn("@TestType") = TestType
    conn("@TestPos") = TestPos
    conn("@TestData") = dataArray(1)
    conn("@RawString") = rawString
    conn("@TestDateTime") = now.tostring

    InsertQuery = "INSERT INTO PaperTests.dbo.InterfaceTesting(ReelRecordID, Test, TestLocation, TestPosition, TestValue, TestTimeStamp, RawValue) VALUES (@RecordID, @Test, @TestType, @TestPos, @TestData, @TestDateTime, @RawString)"
    Try
        conn.ExecuteNonQuery(InsertQuery)
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try

End Sub

Private Sub IncrementTestPosition()
    Dim tempPosition As Integer = GetBondPosition()
    Dim FrontOriginalMax = 5
    Dim CenterOriginalMax = 15
    Dim BackOriginalMax = 25
    Dim FrontRetestOrWinderMax = 10
    Dim CenterRetestOrWinderMax = 20
    Dim BackRetestOrWinderMax = 30

    If tempPosition = FrontOriginalMax Then
        tempPosition = 11
    else if tempPosition = CenterOriginalMax Then
        tempPosition = 21
    else if tempPosition = BackOriginalMax Then
        tempPosition = 1
    Else If tempPosition = FrontRetestOrWinderMax then
        tempPosition = 1
    Else If tempPosition = CenterRetestOrWinderMax then
        tempPosition = 1
    Else If tempPosition = BackRetestOrWinderMax then
        tempPosition = 1
    else 
        tempPosition = tempPosition + 1
    End If
    SetBondPosition(tempPosition.tostring)
End Sub

#End Region

#Region "Get PiValues"
Private Function GetRecordID() As Int64
    Dim RecordID As Int32 = 0
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        RecordID = piserver.GetCurrentValue("PAPERLAB:PaperLabReelSelected")
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return RecordID
End Function

Private Function GetBondPosition() As Int64
    Dim BondPos As Int32 = 0
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        BondPos = CInt(piserver.GetCurrentValue("PAPERLAB:SBOND.POS"))
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return BondPos
End Function
Private Sub SetBondPosition(pos As String) 
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
       piserver.WriteValue("PAPERLAB:SBOND.POS", pos)
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
End Sub

Private Function BondTestType() As String
    Dim TestType As String = ""
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        TestType = piserver.GetCurrentValue("M1:BOND.TYPE")
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return TestType
End Function

Private Function BondReelLoc() As String
    Dim ReelLoc As String = ""
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        ReelLoc = piserver.GetCurrentValue("M1:BOND.ReelLoc")
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return ReelLoc
End Function

Private Function GetBondInterfaceStatus() As Integer
    Dim Status As Integer = 0
    Try
        Dim piserver As New PIServer("valpi", "piadmin", "fatb0y",True)
        Status = CInt(piserver.GetCurrentValue("PAPERLAB:BOND_INTERFACE.S"))
    Catch ex As Exception
        ErrorLog2(ex.ToString())
    End Try
    Return Status
End Function

#End Region

#Region "Debug"

    Private Sub ErrorLog(RecordID As Int32, BondTest As Integer, ReelLoc As String, TestType As String, StartingTestPos As Integer, dataArray() As Double)
    Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
    Dim NameOfFile As String = "BondTest Debug File"
    Dim TestPos = StartingTestPos + (CInt(dataArray(0)) - 1)

    If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
        Using sw As StreamWriter =  New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)

          '  For i = 0 To dataArray.Count -1 
                sw.WriteLine(" ")
                sw.WriteLine(RecordID & "   " & BondTest & "    " & ReelLoc & "    " & TestType  & "   " & TestPos & "   " & dataArray(1).ToString)
              '  TestPos = TestPos + 1
          '  Next
        End Using
    else
        File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
        Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
            'For i = 0 To dataArray.Count -1 
                sw.WriteLine(" ")
                sw.WriteLine(RecordID & "   " & BondTest & "    " & ReelLoc & "    " & TestType  & "   " & TestPos & "   " & dataArray(1).ToString)
              '  TestPos = TestPos + 1
            'Next
        End Using
    End If
End Sub

Private Sub ErrorLog2(dataArray as string)
    Dim SavePath As String = "C:\Program Files (x86)\PIPC\Interfaces\Lab"
    Dim NameOfFile As String = "BondTest Debug File"
   ' Dim TestPos = StartingTestPos

    If System.IO.File.Exists(SavePath & "\" & NameOfFile & ".txt") Then
        Using sw As StreamWriter = New StreamWriter(SavePath & "\" & NameOfFile & ".txt", True)
                sw.WriteLine(" ")
                sw.WriteLine(dataArray)
        End Using
    else
        File.Create(SavePath & "\" & NameOfFile & ".txt").Dispose()
        Using sw As StreamWriter = File.CreateText(SavePath & "\" & NameOfFile & ".txt")
                sw.WriteLine(" ")
                sw.WriteLine(dataArray)
        End Using
    End If
End Sub

#End Region

This is a screenshot of the errors:

errors

Thanks in advance

2

There are 2 answers

0
Giovanni On BEST ANSWER

Update: So as Timmy was saying the connection was getting disposed by garbage collection. so i declared the object as a shared variable in the class

Shared Dim WithEvents serialPort as IO.Ports.SerialPort

and in the OnStart method i initiated it as a new Serial port and rocked on. has not throw any errors since garbage collection wont disposed of it. Hope this helps somebody having a similar issue.

2
Timmy_A On

Normally, after opening the serial port in .NET it stays opened for arbitrary time. I've written several .NET applications were serial ports are used for months or years without app or computer restart and they work well.

According to the exception info you posted it looks like that serial port has been disposed. There are several possible reasons.

  1. Using bad driver or HW, that disconnects your serial port. I've been using many USB-to-RS232 converters and some of them had bad drivers so sometimes ports were randomly disconnected and ObjectDisposedException was thrown. In earlier Windows editions (XP) the OS even 'blue-screened'. Here is more info about such situation where ObjectDisposedException is thrown.

This is a known problem with SerialPort. Device removal causes an uncatchable exception in a background thread it uses (WaitForCommEvent). The only solutions are to not use SerialPort or create a .config file that puts unhandled exception trapping mode back to .NET 1.1 behavior.

  1. The USB cable of your RS232 converter is manually disconnected. If you do this, most drivers normally disconnect all handles to your serial port and .NET throws ObjectDisposedException.

  2. Also check your power management settings on your USB port if USB-to-RS232 converter is used.Power Management Try to uncheck this option on USB device to which converter is connected.

  3. SW bug in your code.

It's always advisable (especially if converter used) to try more types of converters just to be sure there is no problem in HW device/driver.