none
Autoconnect to COMM port. RRS feed

  • Question

  • I wanted com ports to be autoconnected . I wrote a Autoconnect i code which COMM port code, it was working so far. BUT, i start getting app's crashes especially in Windows7, more rare in Win10. Those crashes doesnt thrown any exceptions etc... it just close the apps. WHile debug it also throw any line, it just get into "stop mode" and closing the app. Whats the problem in the code? 

     Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    
            Connected = False
       autoconnect()
        End Sub
     Private Sub autoconnect()
    
            For Each sp As String In My.Computer.Ports.SerialPortNames
                Try
                    spObj = New SerialPort(sp, 115200, Parity.None, 8, StopBits.One)
                    spObj.ReadTimeout = 5000
                    '    spObj.ReceivedBytesThreshold = 6
                    spObj.WriteTimeout = 5000
                    spObj.Open()
    
                    Dim ListeningWatch As New Stopwatch
                    Dim serialMessage As String
    
                    Dim BytesToSend(1) As Byte
                    Dim OutBuffer
                    BytesToSend(0) = Hex(99)             ' call Dump eeprom (44)
                    BytesToSend(1) = 0                   'dummy
                    OutBuffer = BytesToSend
    
                    ' Bytes are outputted in the order of their Index Number(Index)!
    
                    spObj.Write(OutBuffer, 0, OutBuffer.length)
    
                    ListeningWatch.Start()
                    While ListeningWatch.ElapsedMilliseconds < 5000 And ListeningWatch.IsRunning
                        serialMessage = spObj.ReadExisting()
                        'RichTextBox1.Text = serialMessage
                        If serialMessage.Contains("000001020") And serialMessage.Length = 12 Then
                            ListeningWatch.Stop()
    
                            Connected = True
                            Timer1.Enabled = False
                            DeviceStatus.Text = "SN: " & serialMessage                       
                            Exit For
                        End If
                    End While
                Catch ex As Exception
                    spObj.Dispose()
                End Try
            Next
            If Connected = False Then
                DeviceStatus.Text = "SN: Not connected"
            End If
        End Sub

    Saturday, April 28, 2018 10:48 AM

All replies

  •  The first thing I would suggest doing is setting these options at the very top of your code.

    Option Strict On
    Option Explicit On
    Option Infer Off
    

     

     You will see at least a few different errors in your code that need to be corrected.  Such as the following line that I can see right off the bat.  The old HEX function returns a String type so,  you are trying to assign a String to the Byte array.  A String is not the same thing as a Byte.

                    BytesToSend(0) = Hex(99)             ' call Dump eeprom (44)
    

     

     I am not sure what value you need to send but,  99 converted to a hexadecimal value is 63.  However,  you have (44) written in it's comment.  So,  I am not sure what value you are looking for but,  if you need to send just a single byte then it would look something like one of these...

            BytesToSend(0) = 99
    
            'or this
            BytesToSend(0) = &H63
    



    If you say it can`t be done then i`ll try it

    Saturday, April 28, 2018 10:09 PM
  • In debug you don't see any error occur? Typically you would get a message popup advising what the error(s) are in debug mode. Without knowing all of those errors how can the code be corrected?

    La vida loca

    Saturday, April 28, 2018 11:20 PM
  •  The first thing I would suggest doing is setting these options at the very top of your code.

    Option Strict On
    Option Explicit On
    Option Infer Off

     

     You will see at least a few different errors in your code that need to be corrected.  Such as the following line that I can see right off the bat.  The old HEX function returns a String type so,  you are trying to assign a String to the Byte array.  A String is not the same thing as a Byte.

                    BytesToSend(0) = Hex(99)             ' call Dump eeprom (44)
    

     

     I am not sure what value you need to send but,  99 converted to a hexadecimal value is 63.  However,  you have (44) written in it's comment.  So,  I am not sure what value you are looking for but,  if you need to send just a single byte then it would look something like one of these...

            BytesToSend(0) = 99
    
            'or this
            BytesToSend(0) = &H63



    If you say it can`t be done then i`ll try it

    Yeah, fixed. But crashes still the thing.
    Sunday, April 29, 2018 5:13 AM
  • In debug you don't see any error occur? Typically you would get a message popup advising what the error(s) are in debug mode. Without knowing all of those errors how can the code be corrected?

    La vida loca

    Yes, no any error occur. This is my Event Viewer Log when app crashed:

    Имя журнала:   Application
    Источник:      .NET Runtime
    Дата:          28.04.2018 18:40:02
    Код события:   1026
    Категория задачи:Отсутствует
    Уровень:       Ошибка
    Ключевые слова:Классический
    Пользователь:  Н/Д
    Компьютер:     HV-service-ПК
    Описание:
    Application: SD CARD Car Master [beta].exe
    Framework Version: v4.0.30319
    Description: The process was terminated due to an unhandled exception.
    Exception Info: System.ObjectDisposedException
    Stack:
       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()
    
    Xml события:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name=".NET Runtime" />
        <EventID Qualifiers="0">1026</EventID>
        <Level>2</Level>
        <Task>0</Task>
        <Keywords>0x80000000000000</Keywords>
        <TimeCreated SystemTime="2018-04-28T07:40:02.000000000Z" />
        <EventRecordID>533</EventRecordID>
        <Channel>Application</Channel>
        <Computer>HV-service-ПК</Computer>
        <Security />
      </System>
      <EventData>
        <Data>Application: SD CARD Car Master [beta].exe
    Framework Version: v4.0.30319
    Description: The process was terminated due to an unhandled exception.
    Exception Info: System.ObjectDisposedException
    Stack:
       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()
    </Data>
      </EventData>
    </Event>
    
    Имя журнала:   Application
    Источник:      Application Error
    Дата:          28.04.2018 18:31:18
    Код события:   1000
    Категория задачи:(100)
    Уровень:       Ошибка
    Ключевые слова:Классический
    Пользователь:  Н/Д
    Компьютер:     HV-service-ПК
    Описание:
    Имя сбойного приложения: SD CARD Car Master [beta].exe, версия: 1.0.0.0, отметка времени: 0x5ae2a828
    Имя сбойного модуля: KERNELBASE.dll, версия: 6.1.7601.17514, отметка времени 0x4ce7b8f0
    Код исключения: 0xe0434352
    Смещение ошибки: 0x0000b760
    Идентификатор сбойного процесса: 0xc9c
    Время запуска сбойного приложения: 0x01d3dec2dcbdc3d0
    Путь сбойного приложения: C:\Users\HV-service\Desktop\SD CARD Car Master [beta].exe
    Путь сбойного модуля: C:\Windows\system32\KERNELBASE.dll
    Код отчета: 238f20b0-4ab6-11e8-b866-001b3822ff72
    Xml события:
    <Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
      <System>
        <Provider Name="Application Error" />
        <EventID Qualifiers="0">1000</EventID>
        <Level>2</Level>
        <Task>100</Task>
        <Keywords>0x80000000000000</Keywords>
        <TimeCreated SystemTime="2018-04-28T07:31:18.000000000Z" />
        <EventRecordID>531</EventRecordID>
        <Channel>Application</Channel>
        <Computer>HV-service-ПК</Computer>
        <Security />
      </System>
      <EventData>
        <Data>SD CARD Car Master [beta].exe</Data>
        <Data>1.0.0.0</Data>
        <Data>5ae2a828</Data>
        <Data>KERNELBASE.dll</Data>
        <Data>6.1.7601.17514</Data>
        <Data>4ce7b8f0</Data>
        <Data>e0434352</Data>
        <Data>0000b760</Data>
        <Data>c9c</Data>
        <Data>01d3dec2dcbdc3d0</Data>
        <Data>C:\Users\HV-service\Desktop\SD CARD Car Master [beta].exe</Data>
        <Data>C:\Windows\system32\KERNELBASE.dll</Data>
        <Data>238f20b0-4ab6-11e8-b866-001b3822ff72</Data>
      </EventData>
    </Event>

    Sunday, April 29, 2018 5:15 AM
  • Seems like problem is here 

    Exception Info: System.ObjectDisposedException
    Stack:
       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()

    Sunday, April 29, 2018 5:15 AM
  • In your Catch statement, try changing it to:

    spObj?.Close()

    Also, replace your "And" keywords in the While and If statements with "AndAlso" so that you get the expected behavior.

    It might also be worth examining the exception message to see what is actually failing.


    Reed Kimble - "When you do things right, people won't be sure you've done anything at all"

    • Proposed as answer by Stanly Fan Wednesday, May 2, 2018 1:27 AM
    Sunday, April 29, 2018 1:30 PM
    Moderator