[RESOLVED] Serial Port to Textbox/Label and TCP/IP-VBForums
Results 1 to 23 of 23

Thread: [RESOLVED] Serial Port to Textbox/Label and TCP/IP

  1. #1

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Resolved [RESOLVED] Serial Port to Textbox/Label and TCP/IP

    First Time Post, not sure if I'm on Administrator Approval, my previous post did not show, sorry if repost.

    Okay, So I'm a former VB6 user, trying to convert to the new VB.NET world. So forgive me. I've googled a little bit just confused on the concepts. I have a serial port I'm trying to capture data, got that working, just need to output it on screen for operator to monitor and then, I will be doing some conversion to TCP/IP parsing it for the other machine to handle the data correctly.

    Any assistance is greatly appreciated, especially with the TCP/IP Stuff listed below. But more importantly I'm trying to learn the concept of why I cannot change a label once it is in a thread, threading seemed to be the best way of capturing this data as it is timer data, and is sending strings at 1200 baud. Here is my code, if someone can assist. Thanks!

    Code:
    Imports System.Net
    Imports System.Net.Sockets
    Imports System.Text
    Imports System.IO.Ports
    Imports System.Threading
    
    Public Class GlobalVariables
        Public Shared Time As String = "0.0"
    End Class
    
    Class MainWindow
    
        Dim _client As TcpClient
        Private comOpen As Boolean = False
        Private readBuffer As String = String.Empty
        Private ByteToRead As String = String.Empty
        Private Bytenumber As String = String.Empty
        Private charToRead As String = String.Empty
        Private byteEnd(2) As Char
    
    
        Public Shared Sub btnConnectCOM_Click(sender As Object, e As RoutedEventArgs) Handles btnConnectCOM.Click
            MessageBox.Show("COM Button Status")
    
    
    
    
    
            'com1.ReadTimeout = 2000
    
            '  Do
            Dim readThread As New Thread(AddressOf Read)
            readThread.Start()
                readThread.Join()
            'Loop
    
    
        End Sub
    
    
        Public Shared Sub Read()
            Dim com1 = New SerialPort()
            Dim returnStr As String = ""
            Dim readThread As New Thread(AddressOf Read)
            Try
                com1.BaudRate = "1200"
                com1.PortName = "COM3"
                com1.NewLine = Chr(13)
                com1.ReadTimeout = 500
    
    
                com1.Open()
                Dim Incoming As String = ""
                Do
                    Incoming = com1.ReadLine()
                    GlobalVariables.Time = Incoming
    
                    returnStr = Incoming
                    ' Format and send string to VIZ for updates
                    updateText()
    
                    'Console.WriteLine(returnStr)
                    'com1.DiscardOutBuffer()
                    'Threading.Thread.Sleep(50)
                Loop
    
            Catch ex As TimeoutException
                MessageBox.Show(ex.Message)
            Finally
                If com1 IsNot Nothing Then com1.Close()
            End Try
        End Sub
    
        Public Sub updateText()
            lblInput.Content = Label
        End Sub

  2. #2
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    39,722

    Re: Serial Port to Textbox/Label and TCP/IP

    Welcome to VBForums

    Threading is a good idea for this kind of thing... but it does cause problems for dealing with controls, because they are owned by the main UI thread.

    As such what you need to do is basically ask the UI thread to do the work, which you can do using Invoke, eg:
    Code:
        Public Sub updateText()
            If Me.InvokeRequired Then 
                Me.Invoke(New MethodInvoker(AddressOf updateText)) 
            Else 
                lblInput.Content = Label
            End If
        End Sub
    What happens when you call this routine is that it checks whether it is running on the UI thread, and if it isn't (indicated by InvokeRequired) then re-run itself on the UI thread.


    Quote Originally Posted by ShawnLyons View Post
    First Time Post, not sure if I'm on Administrator Approval, my previous post did not show, sorry if repost.
    You are on approval I'm afraid (our system automatically does it to some people, to help prevent spam), but as that applies to all your posts (for now) nobody else saw a duplicate. Unfortunately how long it will take for your posts to appear depends on how soon a moderator pops by, so it can be several hours sometimes.

  3. #3

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    I'm not sure that code worked. It compiled with errors. Do I have to import a specific library? And also the label control is still not accessible. It is not declared or may be inaccessible due to its protection level.

  4. #4
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,622

    Re: Serial Port to Textbox/Label and TCP/IP

    Quote Originally Posted by ShawnLyons View Post
    I'm not sure that code worked. It compiled with errors. Do I have to import a specific library? And also the label control is still not accessible. It is not declared or may be inaccessible due to its protection level.
    What errors?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  5. #5
    Super Moderator si_the_geek's Avatar
    Join Date
    Jul 2002
    Location
    Bristol, UK
    Posts
    39,722

    Re: Serial Port to Textbox/Label and TCP/IP

    The documentation ( https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx ) shows that it is in System.Windows.Forms, which I now see you may not be using... it may be better for you to use something like Control.Invoke instead: https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx

    Quote Originally Posted by ShawnLyons View Post
    And also the label control is still not accessible. It is not declared or may be inaccessible due to its protection level.
    I assume you are referring to one of the things on the line "lblInput.Content = Label", but as neither of them appear anywhere else in your code I can't tell which it would be, or how to fix it.

  6. #6

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    Name:  Untitled.jpg
Views: 78
Size:  23.7 KB

  7. #7
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,622

    Re: Serial Port to Textbox/Label and TCP/IP

    Quote Originally Posted by ShawnLyons View Post
    Name:  Untitled.jpg
Views: 78
Size:  23.7 KB
    Errr.....that's not a WinForms application is it. That looks like a WPF application. I've never done WPF but I think it has some kind of dispatcher class or system that can invoke calls on the UI.

    The code si posted is meant for a WinForms application. The idea is that when you need to manipulate controls, you invoke such methods on the UI thread from another thread. Controls have thread affinity which means you can only change their properties on the thread in which they were created which is more often than not, the UI thread. WPF would work the same way but it probably uses different methods to do it. You just have to find the WPF version of the code that si posted.
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  8. #8

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    I did a little research this helped, but not the end solution.

    https://stackoverflow.com/questions/...d-methodinvoke

    I had to change my updateText routine From Public Shared Sub to Public Sub to get the red squiggly line to go away, but in the thread worker sub the updateText Routine is shown as a red squiggle line with Cannot Refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
    Last edited by ShawnLyons; Jan 6th, 2018 at 03:06 PM. Reason: clarification

  9. #9
    Angel of Code Niya's Avatar
    Join Date
    Nov 2011
    Posts
    5,622

    Re: Serial Port to Textbox/Label and TCP/IP

    Quote Originally Posted by ShawnLyons View Post
    I did a little research this helped, but not the end solution.

    https://stackoverflow.com/questions/...d-methodinvoke

    I had to change my updateText routine From Public Shared Sub to Public Sub to get the red squiggly line to go away, but in the thread worker sub the updateText Routine is shown as a red squiggle line with Cannot Refer to an instance member of a class from within a shared method or shared member initializer without an explicit instance of the class.
    Unless this there is some special WPF nuance I'm unaware of, none of those methods should be shared, especially not your event handlers. Why did you make them shared in the first place?
    Treeview with NodeAdded/NodesRemoved events | BlinkLabel control | Calculate Permutations | Object Enums | ComboBox with centered items | .Net Internals article(not mine) | Wizard Control | Understanding Multi-Threading | Simple file compression | Demon Arena


    C++ programmers will dismiss you as a cretinous simpleton for your inability to keep track of pointers chained 6 levels deep and Java programmers will pillory you for buying into the evils of Microsoft. Meanwhile C# programmers will get paid just a little bit more than you for writing exactly the same code and VB6 programmers will continue to whitter on about "footprints". - FunkyDexter

    There's just no reason to use garbage like InputBox. -jmcilhinney

  10. #10

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    Making a little progress, here's my updated code. Getting closer to a solution. (I Think)

    Code:
     
        Public Sub Read()
            Console.WriteLine("Executed Read From Port")
            Dim com1 = New SerialPort()
            Dim returnStr As String = ""
            Dim readThread As New Thread(AddressOf Read)
    
            Try
                com1.BaudRate = "1200"
                com1.PortName = "COM3"
                com1.NewLine = Chr(13)
                com1.ReadTimeout = 500
    
    
                com1.Open()
                Dim Incoming As String = ""
                Do
                    Incoming = com1.ReadLine()
                    GlobalVariables.Time = Incoming
    
                    returnStr = Incoming
                    ' Format and send string to VIZ for updates
                    updateText()
    
                   ' Console.WriteLine(returnStr)
                    'com1.DiscardOutBuffer()
                    'Threading.Thread.Sleep(50)
                Loop
    
            Catch ex As TimeoutException
                MessageBox.Show(ex.Message)
            Finally
                If com1 IsNot Nothing Then com1.Close()
            End Try
    
    
        End Sub
       Public Sub updateText()
            Console.WriteLine("Execute Update Text")
            ' Dispatcher.Invoke(DispatcherPriority.Normal, New Action(AddressOf newText))
            ' Dispatcher.Invoke(DispatcherPriority.Normal, DirectCast(Function() lblTime.Content = GlobalVariables.Time End Function))
            Dispatcher.BeginInvoke(Function() lblTime.Content = GlobalVariables.Time)
            '  If Not Dispatcher.CheckAccess Then
            ' MlblTime.Content = "time"
            'Else
            'lblTime.Content = "BLAH"
            'End If
        End Sub
    
        Private Sub newText()
            lblTime.Content = GlobalVariables.Time
            Console.WriteLine(GlobalVariables.Time)
        End Sub
    The dispatcher code fails to execute.

  11. #11
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,316

    Re: Serial Port to Textbox/Label and TCP/IP

    Too bad Sitten Spynne is offline. He's pretty much the expert on WPF and Threading.
    I don't think I have the time at the moment to try my hand at WPF to work things out. Most likely I would be doing the type of searches you're doing and by the time I figured something out, you'll be further down the road with others help.

  12. #12

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    ugh, I feel like nOOb, Maybe cause I am one. Next time I won't use WPF. I guess that is the general consensus. Okay, any help appreciated at this point.

  13. #13
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,023

    Re: Serial Port to Textbox/Label and TCP/IP

    why have you chosen to ignore si the geeks post? Thats the answer :/

  14. #14
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,023

    Re: Serial Port to Textbox/Label and TCP/IP

    I understand the need to make something fun but you are bypassing simple basics. IE you don't understand the difference between a sub or a function.

    Regardless of anything lets make it, even more, simpler based on you even attempting whats kindly offered to you.

    vb Code:
    1. Public Class Form1
    2.  
    3.  
    4.     Public Sub updateText()
    5.         Me.Label1.Invoke(Sub()
    6.                              Console.WriteLine("Execute Update Text")
    7.                              ' update what ever
    8.                          End Sub)
    9.     End Sub
    10.  
    11.  
    12. End Class

  15. #15
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,316

    Re: Serial Port to Textbox/Label and TCP/IP

    He's doing a WPF project. I think your code and Si's original are for winForm.

    I was curious enough to do a quick try of updating a label from a thread, since I don't do any WPF programming yet.
    Here is my test case and it worked fine. It just uses a button and a label. You click the button to start the thread, and click it again to stop the thread. All the thread does is update the label at 10 hz.
    Code:
    Imports System.Threading
    
    Class MainWindow
        Private readThread As Thread
        Private activeThread As Boolean
    
        Private Sub Button1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles Button1.Click
            If activeThread Then
                activeThread = False
            Else
                activeThread = True
                readThread = New Thread(AddressOf Read)
                readThread.Start()
            End If
        End Sub
    
        Private Sub Read()
            Dim counter As Long
            Do While activeThread
                Thread.Sleep(100)
                counter += 1
                Dispatcher.Invoke(Sub() Label1.Content = counter.ToString)
            Loop
        End Sub
    End Class
    Last edited by passel; Jan 6th, 2018 at 05:15 PM.

  16. #16

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    I just saw his post, and tried some sample code to see what happens.

    Inherits System.Windows.Forms.Form creates a squiggle line when I put it in the main window class.
    Also MethodInvoker creates a red squiggle line as well. It is as if those aren't valid for the library that I'm building from.

    I apologize, I'm trying to understand and grasp the concept, it has been a LONG time since I've done VB programming. It's like riding a bike, right? Only the handlebars are reversed and a left is a right and a right is a left.

    Apologies for sounding like nOOb here.

  17. #17

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    He's doing a WPF project. There is no Me.

    I was curious enough to do a quick try of updating a label from a thread, since I don't do any WPF programming yet.
    Here is my test case and it worked fine. It just uses a button and a label. You click the button to start the thread, and click it again to stop the thread. All the thread does is update the label at 10 hz.
    So, just to make sure this is a Non-WPF programming example, like others I have seen across the internet?
    Just trying to make sure it isn't something wrong I'm doing on my end of the code.
    I do not have a Dispatcher class available in my code hinting.

  18. #18
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,316

    Re: Serial Port to Textbox/Label and TCP/IP

    Quote Originally Posted by ShawnLyons View Post
    ugh, I feel like nOOb, Maybe cause I am one. Next time I won't use WPF. I guess that is the general consensus. Okay, any help appreciated at this point.
    Actually, there is a strong percentage that say if you are new to vb.net then you probably should start learning wpf rather than winforms.
    There is a bit of learning curve either way, and if you go with winforms first, you still have a second learning curve to move to wpf.
    wpf is arguably the better technology, but most of us went from VB6 to VB.Net before wpf came about, so use winforms by default.
    I feel that going from VB6 to winforms probably feels less foreign, and you'll likely find more help for winforms on this forum, but I wouldn't discount wpf, even if I haven't made the effort myself, yet (and I'm old so may not make the effort unless a wpf project falls into my lap at work).

  19. #19
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,316

    Re: Serial Port to Textbox/Label and TCP/IP

    Quote Originally Posted by ShawnLyons View Post
    So, just to make sure this is a Non-WPF programming example, like others I have seen across the internet?
    Just trying to make sure it isn't something wrong I'm doing on my end of the code.
    I do not have a Dispatcher class available in my code hinting.
    No, the short code I posted is a wpf programming example, my first try at a wpf program from scratch, I think. I just pulled a couple of pieces from your code in your first post (launching the thread), and code from you later post, invoking with the Dispatcher.

    A non-WPF programming example, i.e. a Console or Winform program would not have the Dispather class. If you've switched to using a winform project, then you would do the code as si-the-geek or ident has shown.

  20. #20
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,316

    Re: Serial Port to Textbox/Label and TCP/IP

    Just to reiterate what my example is suppose to help with.
    Your original question was about not being able to update the label with the wpf code in your first post.
    I think if you continued with your first code and changed your updateText sub to the following, that code would update the label.
    Code:
        Public Sub updateText()
            Dispatcher.Invoke(Sub() lblInput.Content = Label) 
        End Sub

  21. #21

    Thread Starter
    New Member
    Join Date
    Jan 2018
    Posts
    12

    Re: Serial Port to Textbox/Label and TCP/IP

    it worked! I had to remove the .join function for the thread and now its hapily updating the label! Happy Happy Joy Joy! Thanks passel and others for leading me on the right path!

  22. #22
    Sinecure devotee
    Join Date
    Aug 2013
    Location
    Southern Tier NY
    Posts
    4,316

    Re: Serial Port to Textbox/Label and TCP/IP

    Yes, that makes sense. I saw the .Join and knew that using .Join would pause the GUI thread until the "joined" thread exited, but didn't think about it keeping the GUI thread from updating the label (or doing much of anything else).
    Last edited by passel; Jan 7th, 2018 at 02:32 AM.

  23. #23
    Bad man! ident's Avatar
    Join Date
    Mar 2009
    Location
    Cambridge
    Posts
    5,023

    Re: Serial Port to Textbox/Label and TCP/IP

    Quote Originally Posted by passel View Post
    Too bad Sitten Spynne is offline. He's pretty much the expert on WPF and Threading.
    The guy I owe a lot too. Jesus, it's scary to think it's nearly Ten years ago I posted a project for review on another forum and he replied. At the time I did not understand much really due to my lack of caring to learn I just wanted it to work. A working application is the fun part when you have no incentive.He ripped apart my obvious amazing skills of copying and pasting and taught me the values of respecting others code.
    I was a full-time carpenter, still am. But after taking a year at evening college improving my maths grade. I set about doing my degree in computer science. Start to finish including my college took just under 7 years. Working fulltime then evening study. I now have the pleasure of adding BSc before my initials because of his guidance.

    Guess what... I'm still a carpenter and have no intention of quitting just happy I did it.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Featured


Click Here to Expand Forum to Full Width