VB.Net source code For forwarding data from EmonTx to Emoncms running on a Windows PC

This is a basic Port reader that is written in VB.net that reads the data from an EmonTx and forwards it on to emoncms, and emails you if there is an error.thats all it does nothing fancy!

I've been told it might be seen as an alternative to the NanodeRF base and the RPi "rock solid" gateway base

I thought it would be handy for someone like me who has a Windows server running 24/7 .
I found it simpler to do this than set up a Rasberry Pi. which I didn't have anyway.
You do have to set up wampserver and emoncms on your server first of course.

you do need to be running the serial sketch in the EmonTx

This is a console app to keep it lightweight.
You can convert this to a winForms project if you want to You just have to be aware that the 'Datarecieved' method will then be running in a different thread to the form. so you have to know how to do that. Just google 'VB.Net invoke'

There is code to print to the console so that on the first few runs you will know that it's working.
It just prints the data it is sending and the response from Emoncms.
it does this 4 times and then clears the console to avoid having a console with millions of lines.
This can easily be remmed out once you are confident it is running ok on your PC.

I used a USB to UART programmer which I bought from the OEM shop.to serve as my serial port.
you'll need a windows driver for it.

'I call it "Windows serial Port Forwarder"

I have attached a text file of the code as some of the formatting in this post has been mucked up

'you will need to provide your Api Key
'Your email address
'your smtpserverhost
'your email password
'at the appropriate places in the code

''Code starts here
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Imports System.Net
Imports System.IO

Module Module1

    Private Email As New MyEmailer
    Private emailCounter as integer=0
    Private DataInput As String
    Private partString As String
    Private Const comma As String = Chr(44)
    Private Const Space As String = Chr(32)
    Private Const ApiKey As String = "&apikey=Your apiKey here"   ' within the quotes
    Private Const Url As String = "http://localhost/emoncms/input/post.json?node="
    Private Const Node As String = "5" 'Change the Node if you want to
    Private Counter As Integer = 0

    Public WithEvents SerialPortCom3 As New System.IO.Ports.SerialPort("COM3")'Change Port to suite your PC

    Public Sub main()

        Try

            SerialPortCom3.BaudRate = 9600
            SerialPortCom3.Parity = Parity.None
            SerialPortCom3.DataBits = 8
            SerialPortCom3.Handshake = Handshake.None
            SerialPortCom3.Open()

        Catch ex As Exception
            Console.WriteLine("Error reading from Com Port  " & ex.ToString)
            Console.ReadKey()
            End

        Finally
            Console.WriteLine("Com Port : open")

            Console.WriteLine("Please Press any key to Start!")
            Console.ReadKey()
            Threading.Thread.Sleep(Threading.Timeout.Infinite)
        End Try
    End Sub

    Private Sub SerialPort3_DataReceived(ByVal sender As Object, ByVal e As _                                                                                  System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPortCom3.DataReceived
        Try
            ReceivedText(SerialPortCom3.ReadLine()) 'Automatically called every time a data is received at the serialPort
        Catch ex As Exception
            Console.WriteLine("Error reading from Com Port :" & ex.ToString)
            Console.WriteLine("Please Press any key to continue!")
            Console.ReadKey()
            End
        End Try

    End Sub

    Private Sub ReceivedText(ByVal Input As String)

        Try
            Counter += 1

            Dim trimmed As String = Input.TrimEnd()
           
             Input = trimmed.Replace(Space, comma) 'Do not need this if you alter the sketch to print comma's instead of spaces
            'Input = trimmed ' but if you don't use last line you must have this one instead
  
            Dim outputUrl As String = Url & Node & "&csv=" & Input & ApiKey & vbCrLf

            Try
                Dim request As WebRequest = WebRequest.Create(outputUrl) '' creates an instance of a webrequest class
                request.Proxy = Nothing

                ' Send the 'WebRequest' and wait for response.
                Dim response As WebResponse = request.GetResponse() 'this actually sends the data

                Dim responsestream As System.IO.Stream = response.GetResponseStream
                Dim streamreader As New System.IO.StreamReader(responsestream)
                Dim Check As String = streamreader.ReadToEnd
                streamreader.Close()
                If Check <> "ok" Then 'The response from Emoncms is 'ok'
                    emailCounter += 1
                    If emailCounter < 2 Then 'so you don't get thousands of emails!
                         Email.DirectSendWarning("Data warning", "Error writing to server ok not received")
                    End If
    
                    Console.WriteLine("Error writing to server ok not received")
                    Console.WriteLine(" Response " & Check)
                Else
                    Console.WriteLine(Input) 'for test purposes only
                    Console.WriteLine(Check)
                    If Counter = 5 Then 'this will constantly be refreshing console so easy to check if port  is getting any data
                        Console.Clear()
                        Counter = 0
                    End If
                End If

               
            Catch ex As Exception
                Console.WriteLine("Error writing to server ")
                Console.WriteLine("Please Press any key to continue!")
                Console.ReadKey()
            Finally

            End Try

        Catch ex As Exception
            Console.WriteLine("Error reading from Com Port") '' :" & ex.ToString)
            Console.WriteLine("Please Press any key to quit!")
            Console.ReadKey()
            End
        End Try

    End Sub

End Module

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'Start New Class Here
'Cut down email class for this project

Imports System.Net.Mail
Imports System.IO
Imports System.Net
Imports System.Text

Public Class MyEmailer

    Property MyEmailAddress As String = "mike@pooley.blah.net" 'obviously put your email address in here not mine ;)
    Property MyPassword As String = "yourpasword"
    Property MySmtpServerHost As String = "mail.pooley.blah.net" 'your smtpserverhost
    Property MailToAddress As String = "mike@pooley.blah.net"
    Property SmtpPort As Integer = 587 'ýour port
   

  
Private Sub DirectSendWarning(ByVal Subject As String, ByVal Message As String)

        Dim smtpServer As New SmtpClient()
        Dim mail As New MailMessage()
        smtpServer.Credentials = New Net.NetworkCredential(Me.MyEmailAddress, Me.MyPassword)
        smtpServer.Port = Me.SmtpPort
        smtpServer.Host = Me.MySmtpServerHost
        mail = New MailMessage()
        mail.From = New MailAddress(Me.MyEmailAddress)
        mail.To.Add(Me.MailToAddress)
        mail.Subject = Subject
        mail.Body = Message
        smtpServer.Send(mail)

    End Sub

  

End Class