﻿Imports System.Net.Sockets
Imports System.IO.Ports

Namespace Communications

	Public MustInherit Class ByteStreamIO
		Implements IDisposable

		Public Delegate Sub ConnectionStatusChangedDelegate(ByVal Sender As ByteStreamIO, ByVal IsConnected As Boolean)
		Public Event ConnectionStatusChanged As ConnectionStatusChangedDelegate

		Public Delegate Sub DataRxDelegate(ByVal Sender As ByteStreamIO, ByVal Data() As Byte, ByVal Count As Integer)
		Public Event DataRx As DataRxDelegate

		Public Delegate Sub LineRxDelegate(ByVal Sender As ByteStreamIO, ByVal Line As String)
		Public Event LineRx As LineRxDelegate

		Public Sub New()
		End Sub

		Public Property LineDelimiter() As String
			Get
				Return mLineDelimiter
			End Get
			Set(ByVal value As String)
				mLineDelimiter = value
			End Set
		End Property

		Public Overridable Function Send(ByVal Text As String) As Boolean
			Dim Bytes As Byte() = System.Text.Encoding.UTF8.GetBytes(Text)
			Return Send(Bytes, Bytes.Length)
		End Function

		Public Overridable Function Send(ByVal Buffer() As Byte) As Boolean
			Return Send(Buffer, Buffer.Length)
		End Function

		Public MustOverride Function Connect() As Boolean
		Public MustOverride Sub Disconnect()
		Public MustOverride Function Send(ByVal Buffer() As Byte, ByVal Size As Integer) As Boolean
		Public MustOverride ReadOnly Property IsConnected() As Boolean
		Public MustOverride ReadOnly Property BaudRate As Integer
		Public MustOverride Sub SetBaudRate(ByVal BaudRate As Integer)

		Protected mLineDelimiter As String = Nothing
		Protected PartialLine As String = ""

		Protected Overridable Sub OnConnectionStatusChanged(ByVal IsConnected As Boolean)
			RaiseEvent ConnectionStatusChanged(Me, IsConnected)
		End Sub

		Protected Overridable Sub OnDataRx(ByVal Data() As Byte, ByVal Count As Integer)
#If xDEBUG Then
         Debug.WriteLine("<< " & Now.ToString() & " [" & Count.ToString() & "]: " & NorthernApex.Utility.ArrayEx.AsString(NorthernApex.Utility.ArrayEx.GetSubset(Data, 0, Count), "X2", ""))
#End If
			RaiseEvent DataRx(Me, Data, Count)
			If mLineDelimiter IsNot Nothing Then
				ProcessLines(Data, Count, mLineDelimiter)
			End If
		End Sub

		Protected Overridable Sub OnLineRx(ByVal Line As String)
			RaiseEvent LineRx(Me, Line)
		End Sub

		Private Sub ProcessLines(ByVal Data() As Byte, ByVal Count As Integer, ByVal Delimiter As String)
			Try
				'Dim DataASCII As String = System.Text.Encoding.ASCII.GetString(Data, 0, Count)
				Dim DataASCII As String = PartialLine & System.Text.Encoding.ASCII.GetString(Data, 0, Count)
				If (DataASCII IsNot Nothing) AndAlso (DataASCII.Length > 0) Then
#If Not COMPACT_FRAMEWORK Then
					Dim Delimiters() As String = New String() {Delimiter}
					Dim Lines() As String = DataASCII.Split(Delimiters, StringSplitOptions.None)
#Else
               Dim Lines() As String = StringSplit(DataASCII, Delimiter)
#End If
					If Lines.Length > 0 Then
						'Lines(0) = PartialLine & Lines(0)
						'#If Not COMPACT_FRAMEWORK Then
						'                  PartialLine = Lines(Lines.Length - 1)
						'                  Array.Resize(Lines, Lines.Length - 1)
						'#Else
						If Lines.Length = 1 Then
							PartialLine = Lines(0)
							Return
						Else
							PartialLine = Lines(Lines.Length - 1)
							ReDim Preserve Lines(Lines.Length - 2)
						End If
						'#End If
						For Each Line As String In Lines
							OnLineRx(Line)
						Next
					End If
				End If
			Catch ex As Exception
			End Try
		End Sub

#Region "IDisposable Support"
		Private disposedValue As Boolean	' To detect redundant calls

		' IDisposable
		Protected Overridable Sub Dispose(disposing As Boolean)
			If Not Me.disposedValue Then
				If disposing Then
					' TODO: dispose managed state (managed objects).
				End If

				' TODO: free unmanaged resources (unmanaged objects) and override Finalize() below.
				' TODO: set large fields to null.
			End If
			Me.disposedValue = True
		End Sub

		' TODO: override Finalize() only if Dispose(ByVal disposing As Boolean) above has code to free unmanaged resources.
		'Protected Overrides Sub Finalize()
		'    ' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
		'    Dispose(False)
		'    MyBase.Finalize()
		'End Sub

		' This code added by Visual Basic to correctly implement the disposable pattern.
		Public Sub Dispose() Implements IDisposable.Dispose
			' Do not change this code.  Put cleanup code in Dispose(ByVal disposing As Boolean) above.
			Dispose(True)
			GC.SuppressFinalize(Me)
		End Sub
#End Region

	End Class

	Public Class SerialConnection
		Inherits ByteStreamIO

		Public Sub New()
		End Sub
		Public Sub New(ByVal ComPort As String, ByVal BaudRate As Integer, ByVal Parity As System.IO.Ports.Parity, ByVal DataBits As Integer, ByVal StopBits As System.IO.Ports.StopBits)
			Me.New(ComPort, BaudRate, Parity, DataBits, StopBits, Handshake.None)
		End Sub
		Public Sub New(ByVal ComPort As String, ByVal BaudRate As Integer, ByVal Parity As System.IO.Ports.Parity, ByVal DataBits As Integer, ByVal StopBits As System.IO.Ports.StopBits, ByVal HandShaking As System.IO.Ports.Handshake)
			mComPort = ComPort
			mBaudRate = BaudRate
			mParity = Parity
			mDataBits = DataBits
			mStopBits = StopBits
			mHandShaking = HandShaking
		End Sub

		Public Property ReceiveBytesThreshold() As Integer
			Get
				Return mReceiveBytesThreshold
			End Get
			Set(ByVal value As Integer)
				mReceiveBytesThreshold = value
			End Set
		End Property

		Public Property ComPort() As String
			Get
				Return mComPort
			End Get
			Set(ByVal value As String)
				mComPort = value
			End Set
		End Property
		Public Overrides ReadOnly Property BaudRate As Integer
			Get
				Return mBaudRate
			End Get
		End Property
		'Set(ByVal value As Integer)
		'   mBaudRate = value
		'End Set
		'End Property
		Public Property DataBits() As Integer
			Get
				Return mDataBits
			End Get
			Set(ByVal value As Integer)
				mDataBits = value
			End Set
		End Property
		Public Property Parity() As System.IO.Ports.Parity
			Get
				Return mParity
			End Get
			Set(ByVal value As System.IO.Ports.Parity)
				mParity = value
			End Set
		End Property
		Public Property StopBits() As System.IO.Ports.StopBits
			Get
				Return mStopBits
			End Get
			Set(ByVal value As System.IO.Ports.StopBits)
				mStopBits = value
			End Set
		End Property
		Public Property HandShaking() As System.IO.Ports.Handshake
			Get
				Return mHandShaking
			End Get
			Set(ByVal value As System.IO.Ports.Handshake)
				mHandShaking = value
			End Set
		End Property

		Public Overrides ReadOnly Property IsConnected() As Boolean
			Get
				If mSerialPort Is Nothing Then Return False
				Return mSerialPort.IsOpen()
			End Get
		End Property

		Public Overrides Function Connect() As Boolean
			If String.IsNullOrEmpty(mComPort) Then
				Throw New InvalidOperationException("ComPort has not been set")
			End If
			If mBaudRate = -1 Then ' ?mBaudRate < 0
				Throw New InvalidOperationException("BaudRate has not been set")
			End If

			Try
				mSerialPort = New SerialPort(mComPort, mBaudRate, mParity, mDataBits, mStopBits)
				mSerialPort.Handshake = mHandShaking
				mSerialPort.ReadTimeout = COM_READ_TIMEOUT
				mSerialPort.WriteTimeout = COM_WRITE_TIMEOUT
				mSerialPort.ReceivedBytesThreshold = mReceiveBytesThreshold
				mSerialPort.Open()
				AddHandler mSerialPort.DataReceived, AddressOf mSerialPort_DataReceived
				OnConnectionStatusChanged(True)
				Return True
			Catch ex As Exception
				Return False
			End Try
		End Function

		Public Overloads Function Connect(ByVal ComPort As String, ByVal BaudRate As Integer, ByVal Parity As System.IO.Ports.Parity, ByVal DataBits As Integer, ByVal StopBits As System.IO.Ports.StopBits) As Boolean
			Return Connect(ComPort, BaudRate, Parity, DataBits, StopBits, Handshake.None)
		End Function

		Public Overloads Function Connect(ByVal ComPort As String, ByVal BaudRate As Integer, ByVal Parity As System.IO.Ports.Parity, ByVal DataBits As Integer, ByVal StopBits As System.IO.Ports.StopBits, ByVal HandShaking As System.IO.Ports.Handshake) As Boolean
			mComPort = ComPort
			mBaudRate = BaudRate
			mParity = Parity
			mDataBits = DataBits
			mStopBits = StopBits
			mHandShaking = HandShaking
			Return Connect()
		End Function

		Public Overrides Sub Disconnect()
			Try
				OnConnectionStatusChanged(False)
				mSerialPort.Close()
			Catch ex As Exception
			End Try
		End Sub

		Public Overrides Function Send(ByVal Buffer() As Byte, ByVal Size As Integer) As Boolean
			Try
				mSerialPort.DiscardOutBuffer()
				mSerialPort.DiscardInBuffer()
				mSerialPort.Write(Buffer, 0, Size)
				Return True
			Catch ex As Exception
				Return False
			End Try
		End Function

		Public Overrides Sub SetBaudRate(BaudRate As Integer)
			If mSerialPort IsNot Nothing Then
				mSerialPort.BaudRate = BaudRate
			End If
		End Sub

		Private Const COM_WRITE_TIMEOUT As Integer = 1000
		Private Const COM_READ_TIMEOUT As Integer = 1500

		Private mReceiveBytesThreshold As Integer = 1

		Private mSerialPort As SerialPort
		Private mComPort As String = Nothing
		Private mBaudRate As Integer = -1
		Private mDataBits As Integer = 8
		Private mParity As System.IO.Ports.Parity = Parity.None
		Private mStopBits As System.IO.Ports.StopBits = StopBits.One
		Private mHandShaking As System.IO.Ports.Handshake = Handshake.None

		Private Sub mSerialPort_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
			Try
				Dim BytesToRead As Integer = mSerialPort.BytesToRead()
				If BytesToRead > 0 Then
					Dim Buffer(BytesToRead - 1) As Byte
					mSerialPort.Read(Buffer, 0, BytesToRead)
					MyBase.OnDataRx(Buffer, BytesToRead)
				End If
			Catch ex As Exception
			End Try
		End Sub

		Protected Overrides Sub Dispose(disposing As Boolean)
			MyBase.Dispose(disposing)

			If disposing Then
				If (mSerialPort IsNot Nothing) Then
					mSerialPort.Dispose()
				End If
			End If

		End Sub

	End Class

End Namespace
