
Imports System.Net.Sockets
Imports System.Net
Imports System.Text.UTF8Encoding

Public Class mainForm
    Private net_client As TcpClient
    Private net_stream As NetworkStream
    Private tcp_net_connected As Boolean
    Dim procedure_number As Integer = 1
    Dim tmrAlarmCount As Byte
    Dim mode As String

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Imposto l'intervallo di riconnessione
        tmrReconnect.Interval = My.Settings.Timeout_ReConn * 1000
        txtStatus.Text = "Server disconnesso."
        btnConnect.Enabled = True
        btnImp.Enabled = True
        btnDisconnect.Enabled = False
        mode = "NORMAL"
        lblModeState.Text = "Normale"
        btnSafe.Enabled = True
        btnNorm.Enabled = False
        'Attivo procedure a seconda delle inpostazioni di MySettings
        If My.Settings.Autoconnect Then
            connect_net()
        End If
        If My.Settings.AutoReconnect Then
            tmrReconnect.Start()
        End If
    End Sub
    Private Sub connect_net()
        Try
            'Procedura instaurazione connessione logica
            net_client = New TcpClient()

            Application.DoEvents()
            net_client.Connect(My.Settings.IP_srv_address, My.Settings.TCP_Port)
            net_stream = net_client.GetStream
            btnDisconnect.Enabled = True
            btnConnect.Enabled = False
            btnImp.Enabled = False
            tmrData.Start()
            tmrConState.Start()
            txtStatus.Text = "Server connesso."
            tcp_net_connected = True
            tmrProcedure.Start()
        Catch
            'Reimposto i pulsanti
            btnDisconnect.Enabled = False
            btnConnect.Enabled = True
            btnImp.Enabled = True
            'Segnalo l'errore
            txtStatus.Text = "Errore connessione al controller!"
        End Try
    End Sub
    Private Sub tmrData_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrData.Tick
        If net_client.Available > 0 Then
            'resetto timeout connessione
            tmrConState.Stop()
            Dim rx_net_buffer(net_client.Available - 1) As Byte
            net_stream.Read(rx_net_buffer, 0, rx_net_buffer.Length)
            Dim received_net_data As String = UTF8.GetString(rx_net_buffer)
            decode_data(received_net_data)
            tmrConState.Start() 'riattivo timeout connessione
        End If
    End Sub

    Private Sub Imp_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnImp.Click
        impForm.Show()
        Me.Close()
    End Sub

    Private Sub tmrConState_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrConState.Tick
        'Se nessun dato viene inviato per il tempo impostato in tmrConState, la procedura invia un segnale
        'di controllo per verificare la connessione
        send_net_data("CLI_CON_OK")
    End Sub

    Private Sub send_net_data(ByRef data_send As String)
        Try
            If Not String.IsNullOrEmpty(data_send) Then
                Dim tx_net_buffer() As Byte = UTF8.GetBytes(data_send)
                net_stream.Write(tx_net_buffer, 0, tx_net_buffer.Length)
            End If
        Catch
            btnDisconnect.PerformClick()
        End Try
    End Sub

    Private Sub btnExit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnExit.Click
        End
    End Sub

    Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
        connect_net() 'procedura connessione rete
    End Sub

    Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
        Try
            'Disabilito timer

            tmrProcedure.Stop() 'Disattivo procedure ordinarie
            tmrConState.Stop()
            tmrData.Stop()
            If tcp_net_connected Then 'se il client è connesso
                net_client.Client.Close()
                net_client.Close()
                net_client = Nothing
                net_stream.Close()
            End If
            tcp_net_connected = False
            btnDisconnect.Enabled = False
            btnConnect.Enabled = True
            btnImp.Enabled = True
            txtStatus.Text = "Server disconnesso."
            lblTemp1.Text = "NO DATA"
            lblTemp2.Text = "NO DATA"
            lblSensorState.Text = "-"
        Catch
            txtStatus.Text = "Errore disconnessione!"
        End Try
    End Sub

    Private Sub tmrTimeout_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs)

        btnDisconnect.PerformClick()
    End Sub

    Private Sub tmrReconnect_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrReconnect.Tick
        'Se il timer di riconnessione non viene resettato, si attiva questra procedura
        'se il bottone di connessione è attivo (server disconnesso)
        If btnConnect.Enabled = True Then
            'effettuo la riconnessione
            btnConnect.PerformClick()
        End If
    End Sub

    Private Sub tmrProcedure_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrProcedure.Tick
        tmrProcedure.Stop()
        'Procedure principali di controllo
        Select Case procedure_number
            Case 1
                send_net_data("TEMPALL")
            Case 2
                send_net_data("INDR_2")
            Case 3
                send_net_data("INDR_2")
            Case 4
                send_net_data("INDR_2")
            Case 5
                send_net_data("INDR_2")
            Case 6
                send_net_data("TEMPRC_3")
            Case 7
                send_net_data("TEMPRC_4")
        End Select
        If procedure_number > 6 Then
            procedure_number = 0
        End If
        procedure_number = procedure_number + 1
        tmrProcedure.Start()
    End Sub

    Private Sub decode_data(ByRef data_to_decode As String)
        System.Threading.Thread.Sleep(60)
        Dim ric_decode_buffer() As String = data_to_decode.Split("_")
        Select Case ric_decode_buffer(0)
            Case "TEMPR"
                If (ric_decode_buffer(3) = "READOK") And (ric_decode_buffer(1) = 3) Then
                    lblTemp1.Text = ric_decode_buffer(2)
                End If
                If (ric_decode_buffer(3) = "READOK") And (ric_decode_buffer(1) = 4) Then
                    lblTemp2.Text = ric_decode_buffer(2)
                End If
            Case "INDR"
                If (ric_decode_buffer(3) = "READOK") And (ric_decode_buffer(1) = 2) Then
                    If ((ric_decode_buffer(2) And 1) = 1) And chkOpExecute.Checked Then
                        lblSensorState.Text = "1"
                        If (mode = "NORMAL") Then
                            send_net_data("OUTDW_2_1")
                        ElseIf (mode = "SAFE") Then
                            send_net_data("OUTDW_2_2")
                            tmrAlarm.Start()
                        End If
                    Else
                        lblSensorState.Text = "0"
                        If (mode = "NORMAL") Then
                            send_net_data("OUTDW_2_0")
                        ElseIf (mode = "SAFE") Then
                            send_net_data("OUTDW_2_0")
                        End If
                    End If
                End If
        End Select
    End Sub

    Private Sub btnSafe_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSafe.Click
        mode = "SAFE"
        lblModeState.Text = "Protezione"
        btnSafe.Enabled = False
        btnNorm.Enabled = True
    End Sub

    Private Sub btnNorm_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNorm.Click
        mode = "NORMAL"
        lblModeState.Text = "Normale"
        btnSafe.Enabled = True
        btnNorm.Enabled = False
    End Sub

    Private Sub tmrAlarm_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles tmrAlarm.Tick
        If tmrAlarmCount > 10 Then
            tmrAlarm.Stop()
            lblAlert.Enabled = False
            tmrAlarmCount = 0
        Else
            lblAlert.Enabled = Not lblAlert.Enabled
            Beep()
            tmrAlarmCount = tmrAlarmCount + 1
        End If

    End Sub
End Class
