Imports Microsoft.Win32
Imports System.Drawing.Graphics
Imports System.Net
Imports System.Net.Sockets

Public Class Form_ControlP

    Public PwrBoxConnected As Boolean = False
    Dim tcpClient As New System.Net.Sockets.TcpClient()
    Dim networkStream As NetworkStream
    Dim relays(2) As Boolean
    Dim DomeTestLoop As Integer
    Dim DomeTestCnt As Integer
    Dim CP4IP As String

    Protected Overrides ReadOnly Property CreateParams() As CreateParams
        Get
            Dim cp As CreateParams = MyBase.CreateParams
            Const CS_DBLCLKS As Int32 = &H8
            Const CS_NOCLOSE As Int32 = &H200
            cp.ClassStyle = CS_DBLCLKS Or CS_NOCLOSE
            Return cp
        End Get
    End Property


    Private Sub ButtonC1_Click(sender As System.Object, e As System.EventArgs) Handles ButtonC1.Click
        Me.Hide()

    End Sub

    Private Sub ButtonC2_Click(sender As System.Object, e As System.EventArgs) Handles ButtonC2.Click
        Me.Hide()

    End Sub

    Private Sub ButtonC3_Click(sender As System.Object, e As System.EventArgs) Handles ButtonC3.Click
        Me.Hide()

    End Sub

    Private Sub ButtonC4_Click(sender As System.Object, e As System.EventArgs) Handles ButtonC4.Click
        Me.Hide()

    End Sub

    Private Sub ButtonC5_Click(sender As System.Object, e As System.EventArgs) Handles ButtonC5.Click
        Me.Hide()

    End Sub

    Private Sub CloseC6_Click(sender As System.Object, e As System.EventArgs) Handles CloseC6.Click
        Me.Hide()

    End Sub

    Private Sub ButtonQuery_Click(sender As System.Object, e As System.EventArgs) Handles ButtonQuery.Click
        If CheckBoxFW.Checked = True Then
            SendReceiveAP(":V#", "Firmware", True, 0)
            TextBoxFW.Text = Form1.Rsp
        End If

        If CheckBoxSP.Checked = True Then
            SendReceiveAP(":pS#", "Side of Pier", True, 0)
            TextBoxSP.Text = Form1.Rsp
        End If

        If CheckBoxLAT.Checked = True Then
            SendReceiveAP(":Gt#", "Latitude", True, 0)
            TextBoxLAT.Text = Form1.Rsp
        End If

        If CheckBoxLON.Checked = True Then
            SendReceiveAP(":Gg#", "Longitude", True, 0)
            TextBoxLON.Text = Form1.Rsp
        End If

        If CheckBoxST.Checked = True Then
            SendReceiveAP(":GS#", "Sidereal Time", True, 0)
            TextBoxST.Text = Form1.Rsp
        End If

        If CheckBoxRA.Checked = True Then
            SendReceiveAP(":GR#", "RA", True, 0)
            TextBoxRA.Text = Form1.Rsp
        End If

        If CheckBoxDEC.Checked = True Then
            SendReceiveAP(":GD#", "DEC", True, 0)
            TextBoxDEC.Text = Form1.Rsp
        End If

        If CheckBoxALT.Checked = True Then
            SendReceiveAP(":GA#", "Altitude", True, 0)
            TextBoxALT.Text = Form1.Rsp
        End If

        If CheckBoxAZ.Checked = True Then
            SendReceiveAP(":GZ#", "Azimuth", True, 0)
            TextBoxAZ.Text = Form1.Rsp
        End If

        If CheckBoxMountTime.Checked = True Then
            SendReceiveAP(":GL#", "Time", True, 0)
            TextBoxMountTime.Text = Form1.Rsp
        End If

        If CheckBoxMerDist.Checked = True Then
            GetMeridianDist()
            TextBoxMerDist.Text = Form1.AP_MeridianDist
        End If

        If CheckBoxMerOffset.Checked = True Then
            If Form1.AscomConnect = True Then
                TextBoxMerOffset.Text = "Not supported via ASCOM"
            Else
                Form1.AP_Command("GetMeridianOffset")
                Dim MerO As String = Form1.MeridianOffset
                Dim S As String = " East"
                If Mid(MerO, 1, 1) = "-" Then
                    S = " West"
                End If
                TextBoxMerOffset.Text = MerO & S
            End If
        End If

        If CheckboxGOS.Checked = True Then
            If Form1.AscomConnect = True Then
                TextBoxMerOffset.Text = "Not supported via ASCOM"
            Else
                Form1.AP_Command("MountOperatingStatus")
                TextBoxGOS.Text = Form1.GOSresp
            End If
        End If


    End Sub

    Private Sub ButtonAddRemoveStartup_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAddRemoveStartup.Click
        Dim ExecName As String = Form1.Path & "\AP GTO Mini Control.exe"
        Dim S As String = ""
        Dim regKey As RegistryKey
        regKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True)
        S = regKey.GetValue("AP Mini Control")

        If S = "" Then
            regKey.SetValue("AP Mini Control", ExecName)
            TextBoxAddRemoveStartup.Text = "AP Mini added to startup"
        Else
            regKey.DeleteValue("AP Mini Control")
            TextBoxAddRemoveStartup.Text = "AP Mini removed from startup"
        End If

        regKey.Close()


    End Sub

    Private Sub CheckBoxAlwaysOnTop_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxAlwaysOnTop.CheckedChanged
        Form1.AlwaysOnTop()
        If CheckBoxAlwaysOnTop.Checked = True Then
            TextBoxAlwaysOnTop.Text = "All windows set to Top"
        Else
            TextBoxAlwaysOnTop.Text = "All windows set to Normal"
        End If
    End Sub

    Private Sub ButtonSetMouseHoverColor_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetMouseHoverColor.Click
        ColorDialog1.Color = Form1.ActiveColor
        ColorDialog1.ShowDialog()
        If Form1.ActiveColor <> ColorDialog1.Color Then
            Form1.ActiveColor = ColorDialog1.Color
            TextBoxMouseHoverColor.Text = "Active color changed"
        End If

    End Sub

    Private Sub ButtonResetMouseHoverColor_Click(sender As System.Object, e As System.EventArgs) Handles ButtonResetMouseHoverColor.Click
        Form1.ActiveColor = My.Settings.ActiveColorDefault
        TextBoxMouseHoverColor.Text = "Active color set to default"

    End Sub

    Private Sub CheckBoxDebugLogging_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxDebugLogging.CheckedChanged
        If CheckBoxDebugLogging.Checked = True Then
            TextBoxDebugLogging.Text = "Debug logging enabled"
        Else
            TextBoxDebugLogging.Text = "Debug logging disabled"
        End If
    End Sub

    Private Sub CheckBoxDelay1stCommand_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxDelay1stCommand.CheckedChanged
        If CheckBoxDelay1stCommand.Checked = True Then
            TextBoxDelay1stCommand.Text = "1st command to mount delayed"
        Else
            TextBoxDelay1stCommand.Text = "Disabled"
        End If
    End Sub

    Private Sub CheckBoxErrorMsgBox_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxErrorMsgBox.CheckedChanged
        If CheckBoxErrorMsgBox.Checked = True Then
            Form1.ErrorMsgBox = True
            TextBoxErrorMsgBox.Text = "Popup error box enabled"
        Else
            Form1.ErrorMsgBox = False
            TextBoxErrorMsgBox.Text = "Popup error box disabled"
        End If
    End Sub

    Private Sub CheckBoxPosWinStartup_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxPosWinStartup.CheckedChanged
        If CheckBoxPosWinStartup.Checked = True Then
            TextBoxPosWinStartup.Text = "Enabled"
        Else
            TextBoxPosWinStartup.Text = "Disabled"
        End If
    End Sub

    Private Sub ButtonShowSplash_Click(sender As System.Object, e As System.EventArgs)
        SplashScreen1.Show()

    End Sub

    Private Sub ButtonSaveSettings_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSaveSettings.Click
        Form1.SaveSettings()
        TextBoxSaveSettings.Text = "Settings saved"

    End Sub

    Public Sub ButtonShowPDF_Click(sender As System.Object, e As System.EventArgs) Handles ButtonShowPDF.Click
        Dim Pdf As String = Form1.Path & "\" & "AP GTO Mini Control.pdf"
        Try
            Process.Start(Pdf)

        Catch ex As Exception
            Form1.StatusLabel.Text = ex.Message

        End Try

    End Sub

    Private Sub ButtonDateTime_Click(sender As System.Object, e As System.EventArgs) Handles ButtonDateTime.Click
        Form_DATE_TIME.Show()
        Form_DATE_TIME.Focus()

    End Sub

    Private Sub ButtonMountDiag_Click(sender As System.Object, e As System.EventArgs) Handles ButtonMountDiag.Click
        Form_DIAGS.Show()

    End Sub

    Private Sub SetQuery(State As Boolean)
        CheckBoxFW.Checked = State
        CheckBoxSP.Checked = State
        CheckBoxLAT.Checked = State
        CheckBoxLON.Checked = State
        CheckBoxST.Checked = State
        CheckBoxRA.Checked = State
        CheckBoxDEC.Checked = State
        CheckBoxALT.Checked = State
        CheckBoxAZ.Checked = State
        CheckBoxMountTime.Checked = State
        CheckBoxMerDist.Checked = State
        CheckBoxMerOffset.Checked = State
        CheckboxGOS.Checked = State

    End Sub

    Private Sub CheckBoxTimedBeep_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxTimedBeep.CheckedChanged
        If CheckBoxTimedBeep.Checked = True Then
            TextBoxTimedBeep.Text = "Enabled"
        Else
            TextBoxTimedBeep.Text = "Disabled"
        End If
        Form1.Ding = CheckBoxTimedBeep.Checked

    End Sub

    Private Sub CheckBoxStopOnConnect_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopOnConnect.CheckedChanged
        If CheckBoxStopOnConnect.Checked = True Then
            TextBoxStopMountTracking.Text = "Connect Enabled"
            CheckBoxStartTrackingOnConnect.Checked = False
        Else
            TextBoxStopMountTracking.Text = "Connect Disabled"
        End If
        Form1.StopOnConnect = CheckBoxStopOnConnect.Checked

    End Sub

    Private Sub CheckBoxStopOnPark_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopOnPark.CheckedChanged
        If CheckBoxStopOnPark.Checked = True Then
            TextBoxStopMountTracking.Text = "Park Enabled"
        Else
            TextBoxStopMountTracking.Text = "Park Disabled"
        End If
        Form1.StopOnPark = CheckBoxStopOnPark.Checked

    End Sub

    Private Sub CheckBoxStopOnAlAzSlew_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopOnAlAzSlew.CheckedChanged
        If CheckBoxStopOnAlAzSlew.Checked = True Then
            TextBoxStopMountTracking.Text = "Alt/Az Slew Enabled"
        Else
            TextBoxStopMountTracking.Text = "Alt/Az Slew Disabled"
        End If
        Form1.StopOnAltAzSlew = CheckBoxStopOnAlAzSlew.Checked

    End Sub

    Private Sub CheckBoxStartTrackingOnConnect_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStartTrackingOnConnect.CheckedChanged
        If CheckBoxStartTrackingOnConnect.Checked = True Then
            TextBoxStartTrackingOnConnect.Text = "Enabled"
            CheckBoxStopOnConnect.Checked = False
        Else
            TextBoxStartTrackingOnConnect.Text = "Disabled"
        End If
        Form1.StartOnConnect = CheckBoxStartTrackingOnConnect.Checked

    End Sub

    Private Sub ButtonTestSpeakRate_Click(sender As System.Object, e As System.EventArgs) Handles ButtonTestSpeakRate.Click
        Form1.Talker.SpeakAsync("Speak rate set to " & ComboBoxSpeakRate.SelectedItem)

    End Sub

    Private Sub ComboBoxSpeakRate_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ComboBoxSpeakRate.SelectedIndexChanged
        Form1.Talker.Rate = ComboBoxSpeakRate.SelectedItem
        If Form1.FormLoading = False Then
            ButtonTestSpeakRate.PerformClick()
        End If

    End Sub

    Private Sub ButtonShowCOMports_Click(sender As System.Object, e As System.EventArgs) Handles ButtonShowCOMports.Click
        Form1.ShowTheCOMports()

    End Sub

    Private Sub ReadTimeoutComboBox_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ReadTimeoutComboBox.SelectedIndexChanged
        Form1.ReadTimeout = ReadTimeoutComboBox.SelectedIndex + 1
        If Form1.FormLoading = False Then
            TextBoxReadTimeout.Text = "Read timeout set to " & Form1.ReadTimeout & " sec."
        End If
        Form1.IgnoreButton = True
        Form1.ShowTheCOMports()
        Form1.IgnoreButton = False

    End Sub

    Private Sub ButtonUpdateAPip_Click(sender As System.Object, e As System.EventArgs) Handles ButtonUpdateAPip.Click
        Form1.APipAddress = APip.Text
        Form1.UpdateStatusLine("AP mount IP address set to " & Form1.APipAddress, Color.Black)
        TextBoxAPip.Text = "AP mount IP address updated"

    End Sub

    Private Sub ButtonUpdateAPport_Click(sender As System.Object, e As System.EventArgs) Handles ButtonUpdateAPport.Click
        Form1.APipPort = APport.Text
        Form1.UpdateStatusLine("AP mount IP port set to " & Form1.APipPort, Color.Black)
        TextBoxAPport.Text = "AP mount IP port updated"

    End Sub

    Private Sub ButtonUpdateAPnetpurge_Click(sender As System.Object, e As System.EventArgs) Handles ButtonUpdateAPnetpurge.Click
        Form1.APipPurgeTimeout = APpurge.Text
        Form1.UpdateStatusLine("Network purge time set to " & Form1.APipPurgeTimeout, Color.Black)
        TextBoxAPpurge.Text = "Network purge time updated"
    End Sub

    Private Sub Form_ControlP_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        ' Make sure form is on the screen
        If Me.Location.X < 0 Or Me.Location.Y < 0 Then
            Me.Location = New Point(0, 0)
        End If

        LabelProductName.Text = My.Application.Info.ProductName
        LabelVersion.Text = "Version: V" & Form1.Version & "  " & Form1.Version_Date
        LabelCompanyName.Text = My.Application.Info.CompanyName
        LabelCopyright.Text = My.Application.Info.Copyright
        'Me.TextBoxDescription.Text = My.Application.Info.Description
        TextBoxDescription.Text = "Controls slewing and focus motor for Astro-Physics GTO mounts." & _
            vbCrLf & "Can also control the NCO and AGF custom dome controllers." & _
            vbCrLf & "AGF focus motor controller, MoonLite dual stepper motor controller and" & _
            vbCrLf & "ASCOM focus motors." & _
            vbCrLf & _
        vbCrLf & "Note: Slew rate and AP mount focus rate are undetermined at program statup." & _
        ""
        'vbCrLf & _
        'vbCrLf & "Keyboard Control of mount by using the following keys when active:" & _
        'vbCrLf & "  Up arrow, Numpad 5 - North slew" & _
        'vbCrLf & "  Down arrow, Numpad 2 - Sourh slew" & _
        'vbCrLf & "  Right arrow, Numpad 3 - East slew" & _
        'vbCrLf & "  Left arrow, Numpad 1 - West slew" & _
        'vbCrLf & "  Page Up, Numpad 4, [ - In Focus" & _
        'vbCrLf & "  Page Down, Numpad 6, ] - Out Focus" & _
        'vbCrLf & "  Numpad Clear & Divide - Toggle NS keys" & _
        'vbCrLf & "  Numpad Multiply & Subtract - Toggle EW keys" & _
        'vbCrLf & "  Numpad 7, 8, 9 - Set rate 0.5x, 1.0x, 12x" & _
        'vbCrLf & "  Numpad Add - Set rate to GTOCP3 variable settings" & _
        'vbCrLf & "  Numpad 0 - Clear all counters" & _
        SetXportPwrBlack()

    End Sub

    Private Sub SetXportPwrBlack()
        PictureBoxR1.Image = My.Resources.BallBlack
        PictureBoxR2.Image = My.Resources.BallBlack
        PictureBoxR3.Image = My.Resources.BallBlack

    End Sub

    Private Sub ButtonSetXportIP_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetXportIP.Click
        Form1.XPORTipAddress = TextBoxXportIPaddress.Text
        Form1.UpdateStatusLine("Xport Power IP address set to " & Form1.XPORTipAddress, Color.Black)
        TextBoxUpdateXportIP.Text = "XPort IP address updated"

    End Sub

    Private Sub ButtonSetXportPort_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetXportPort.Click
        Form1.XPORTipPort = TextBoxXportIPport.Text
        Form1.UpdateStatusLine("Xport Power IP port set to " & Form1.XPORTipPort, Color.Black)
        TextBoxUpdateXportPort.Text = "XPort IP port updated"

    End Sub

    Private Sub LabelUpdateR1Name_Click(sender As System.Object, e As System.EventArgs) Handles LabelUpdateR1Name.Click
        Form1.PwrRelay1Name = TextBoxR1Name.Text
        TextBoxDurPwrOff.Text = "Power relay #1 name updated"

    End Sub


    Private Sub LabelUpdateR2Name_Click(sender As System.Object, e As System.EventArgs) Handles LabelUpdateR2Name.Click
        Form1.PwrRelay2Name = TextBoxR2Name.Text
        TextBoxDurPwrOff.Text = "Power relay #2 name updated"

    End Sub

    Private Sub LabelUpdateR3Name_Click(sender As System.Object, e As System.EventArgs) Handles LabelUpdateR3Name.Click
        Form1.PwrRelay3Name = TextBoxR3Name.Text
        TextBoxDurPwrOff.Text = "Power relay #3 name updated"

    End Sub

    Private Sub CheckBoxR1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxR1.CheckedChanged
        Form1.PwrRelay1 = CheckBoxR1.Checked

    End Sub

    Private Sub CheckBoxR2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxR2.CheckedChanged
        Form1.PwrRelay2 = CheckBoxR2.Checked

    End Sub

    Private Sub CheckBoxR3_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxR3.CheckedChanged
        Form1.PwrRelay3 = CheckBoxR3.Checked

    End Sub

    Private Sub CheckBoxDurPwrOff_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxDurPwrOff.CheckedChanged
        Form1.DurTimerPwrOff = CheckBoxDurPwrOff.Checked

    End Sub

    Private Sub CheckBoxDisconnect_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxDisconnect.CheckedChanged
        Form1.DurTimerDisconnect = CheckBoxDisconnect.Checked

    End Sub

    Private Sub CheckBoxStopPHD_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopPHD.CheckedChanged
        Form1.StopPHD = CheckBoxStopPHD.Checked

    End Sub

    Private Sub CheckBoxPark1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxPark1.CheckedChanged
        If CheckBoxPark1.Checked = True Then
            CheckBoxPark2.Checked = False
            CheckBoxPark3.Checked = False
            CheckBoxPark4.Checked = False
        End If

    End Sub

    Private Sub CheckBoxPark2_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxPark2.CheckedChanged
        If CheckBoxPark2.Checked = True Then
            CheckBoxPark1.Checked = False
            CheckBoxPark3.Checked = False
            CheckBoxPark4.Checked = False
        End If

    End Sub

    Private Sub CheckBoxPark3_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxPark3.CheckedChanged
        If CheckBoxPark3.Checked = True Then
            CheckBoxPark1.Checked = False
            CheckBoxPark2.Checked = False
            CheckBoxPark4.Checked = False
        End If

    End Sub

    Private Sub CheckBoxPark4_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxPark4.CheckedChanged
        If CheckBoxPark4.Checked = True Then
            CheckBoxPark1.Checked = False
            CheckBoxPark2.Checked = False
            CheckBoxPark2.Checked = False
        End If

    End Sub

    Private Sub CheckBoxDurTime_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopDur.CheckedChanged
        If CheckBoxStopDur.Checked = True Then
            Dim D As String = TextBoxStopDur.Text
            Dim Line As String = "Tracking duration timer set to " & Mid(D, 1, 2) & " hours " & Mid(D, 4, 2) & " minutes"
            Form1.LogScope("Status = ", Color.Black, Line)
            Form1.UpdateStatusLine("Tracking duration timer enabled", Color.Black)
            Dim Hours As Integer = Mid(TextBoxStopDur.Text, 1, 2)
            Dim Mins As Integer = Mid(TextBoxStopDur.Text, 4, 2)
            Form1.StopDurCnt = ((Hours * 60) + (Mins))
            LabelCnt.Text = Form1.StopDurCnt
            Form1.LabelDurCnt.Text = Form1.StopDurCnt
            LabelCnt.Visible = True
            Form1.LabelDurCnt.Visible = True
            Form1.TimerMeridianStopDur.Interval = ((Hours * 3600) + (Mins * 60)) * 1000
            Form1.TimerMeridianStopDur.Enabled = True
            Form1.TimerMeridianStopDurCnt.Enabled = True
            Form1.ToolTip1.SetToolTip(Form1.LabelDurCnt, "Minutes remaining to issue stop")
            Form1.PictureBoxStopTimer.Visible = True
            TextBoxStopDur.Enabled = False
        Else
            Form1.TimerMeridianStopDurCnt.Enabled = False
            Form1.TimerMeridianStopDur.Enabled = False
            SetTimerPic()
            TextBoxStopDur.Enabled = True
            Form1.UpdateStatusLine("Tracking duration timer stopped", Color.Black)
        End If

    End Sub

    Private Sub CheckBoxStopMeridian_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopMeridian.CheckedChanged
        If CheckBoxStopMeridian.Checked = True Then
            Form1.AP_Command("Latitude")
            Dim Line As String = "Tracking meridian timer set to " & NumericUpDownStopDeg.Value & "° past meridian"
            Form1.LogScope("Status = ", Color.Black, Line)
            Form1.UpdateStatusLine("Tracking meridian timer enabled", Color.Black)
            Form1.TimerMeridianStopDeg.Interval = 60000
            Form1.TimerMeridianStopDeg.Enabled = True
            Form1.PictureBoxStopTimer.Visible = True
            Form1.LabelDurCnt.Text = NumericUpDownStopDeg.Value & "°M"
            Form1.ToolTip1.SetToolTip(Form1.LabelDurCnt, "Degrees past meridian to issue stop")
            Form1.LabelDurCnt.Visible = True
        Else
            Form1.TimerMeridianStopDeg.Enabled = False
            SetTimerPic()
            Form1.UpdateStatusLine("Tracking meridian timer stopped", Color.Black)
        End If
        If Form_Monitor.Visible = True Then
            Form1.Update_Scope_Pos()
        End If

    End Sub

    Private Sub CheckBoxStopAlt_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxStopAlt.CheckedChanged
        If CheckBoxStopAlt.Checked = True Then
            Dim Line As String = "Tracking altitude timer set to " & NumericUpDownStopAlt.Value & "°"
            Form1.LogScope("Status = ", Color.Black, Line)
            Form1.UpdateStatusLine("Tracking altitude timer enabled", Color.Black)
            Form1.TimerAltStopDeg.Interval = 60000
            Form1.TimerAltStopDeg.Enabled = True
            Form1.PictureBoxStopTimer.Visible = True
            Form1.LabelDurCnt.Text = NumericUpDownStopAlt.Value & "°A"
            Form1.ToolTip1.SetToolTip(Form1.LabelDurCnt, "Mount altitude to issue stop")
            Form1.LabelDurCnt.Visible = True
        Else
            Form1.TimerAltStopDeg.Enabled = False
            SetTimerPic()
            Form1.UpdateStatusLine("Tracking altitude timer stopped", Color.Black)
        End If
        If Form_Monitor.Visible = True Then
            Form1.Update_Scope_Pos()
        End If

    End Sub

    Private Sub SetTimerPic()
        If Form1.TimerMeridianStopDeg.Enabled = False And Form1.TimerMeridianStopDur.Enabled = False _
            And Form1.TimerAltStopDeg.Enabled = False Then
            Form1.PictureBoxStopTimer.Visible = False
            Form1.LabelDurCnt.Visible = False
        End If

    End Sub

    Private Sub NumericUpDownStopDeg_ValueChanged(sender As System.Object, e As System.EventArgs) Handles NumericUpDownStopDeg.ValueChanged
        Dim Tip As String = ""
        Dim D As Integer = NumericUpDownStopDeg.Value
        Dim M As Integer = D * 4

        Form1.LabelDurCnt.Text = NumericUpDownStopDeg.Value & "°M"

        If M < 60 Then
            Tip = D & "° = " & M & " minutes"
            Form1.MinsToMerStop = M
        End If
        If M >= 60 And M < 120 Then
            M = M - 60
            Tip = D & "° = 1 hour, " & M & " minutes"
            Form1.MinsToMerStop = M + 60
        End If
        If M >= 120 Then
            M = M - 120
            Tip = D & "° = 2 hours, " & M & " minutes"
            Form1.MinsToMerStop = M + 120
        End If
        ToolTip1.SetToolTip(NumericUpDownStopDeg, Tip)

        If Form_Monitor.Visible = True Then
            Form1.Update_Scope_Pos()
        End If

    End Sub

    Private Sub NumericUpDownStopAlt_ValueChanged(sender As System.Object, e As System.EventArgs) Handles NumericUpDownStopAlt.ValueChanged
        Form1.LabelDurCnt.Text = NumericUpDownStopAlt.Value & "°A"

    End Sub

    Private Sub CheckBoxMerPark_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxMerPark.CheckedChanged
        Form1.MerTimerPark = CheckBoxMerPark.Checked

    End Sub

    Private Sub CheckBoxDurPark_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxDurPark.CheckedChanged
        Form1.DurTimerPark = CheckBoxDurPark.Checked

    End Sub

    Private Sub CheckBoxAltPark_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxAltPark.CheckedChanged
        Form1.AltTimerPark = CheckBoxAltPark.Checked

    End Sub

    Private Sub Label1Thelp_Click(sender As System.Object, e As System.EventArgs) Handles Label1Thelp.Click
        Dim S As String = ""
        Dim Msg As String = "Scope on West side of mount:" & vbCrLf _
            & "  Stop tracking when mount moves past meridian" & vbCrLf _
            & "  number of degrees indicated." & vbCrLf & vbCrLf _
            & "Scope on East side of mount:" & vbCrLf _
            & "  Stop tracking when mount moves past meridian 180°" & vbCrLf _
            & "  plus number of degrees indicated " & vbCrLf _
            & "  or when mount altitude is 5° from western horizon." & vbCrLf & vbCrLf _
            & "If the meridian is adjusted using the mount's hand " & vbCrLf _
            & "  controller 'Deg. past meridian' does not take that" & vbCrLf _
            & "  into account."

        S = MessageBox.Show(Msg, "AP GTO Mini Control - Stop Mount Tracking Past Meridian", _
              MessageBoxButtons.OK, MessageBoxIcon.Information)

    End Sub


    Private Sub ButtonPower_Click(sender As System.Object, e As System.EventArgs) Handles ButtonPower.Click
        If PwrBoxConnected = False Then
            ConnectToPwrBox()
        Else
            DisconnectToPwrBox()
        End If
        Form1.PwrBoxConnected = PwrBoxConnected

    End Sub

    Private Sub ConnectToPwrBox()
        Try
            tcpClient = New System.Net.Sockets.TcpClient()
            Dim IPaddr As IPAddress = IPAddress.Parse(TextBoxXportIPaddress.Text)
            Dim TCPdataPort As Integer = TextBoxXportIPport.Text
            tcpClient.Connect(IPaddr, TCPdataPort)
            tcpClient.ReceiveTimeout = 3000
            networkStream = tcpClient.GetStream
            PwrBoxConnected = True
            TextBoxPwrBox.Text = "Connected"
            ButtonPower.Text = "Disconnect XPort Power Box"
            GetRelays() 'get relays state
            ButtonSetRelays.Enabled = True

        Catch ex As Exception
            PwrBoxConnected = False
            Form1.LogScope("PwrBox Error: ", Color.DarkRed, ex.Message)
            TextBoxPwrBox.Text = "Error connecting, see log"

        End Try
    End Sub

    Private Sub DisconnectToPwrBox()
        Try
            SetXportPwrBlack()
            tcpClient.Close()
            PwrBoxConnected = False
            TextBoxPwrBox.Text = "Disconnected"
            ButtonPower.Text = "Connect XPort Power Box"
            ButtonSetRelays.Enabled = False

        Catch ex As Exception
            PwrBoxConnected = False
            Form1.LogScope("PwrBox Error: ", Color.DarkRed, ex.Message)
            TextBoxPwrBox.Text = "Error disconnecting, see log"

        End Try
    End Sub

    Private Sub ButtonSetRelays_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetRelays.Click
        Dim rly As Integer = 0
        If CheckBoxR1.Checked = True Then
            rly = rly Or &H1
        End If

        If CheckBoxR2.Checked = True Then
            rly = rly Or &H2
        End If

        If CheckBoxR3.Checked = True Then
            rly = rly Or &H4
        End If

        Dim bbuff(8) As Byte
        bbuff(0) = &H1B 'set states command byte
        bbuff(1) = &H7  'mask for 3 bits
        bbuff(2) = 0
        bbuff(3) = 0
        bbuff(4) = 0
        bbuff(5) = Convert.ToByte(rly)
        bbuff(6) = 0
        bbuff(7) = 0
        bbuff(8) = 0
        SendBytesHex(bbuff)    'send to XPort

        ' update relays
        UpdateRelays()

    End Sub

    Public Sub PwrOff()
        Dim rly As Integer = 0
        If CheckBoxR1.Checked = False Then
            If relays(0) = True Then
                rly = rly Or &H1
            End If
        End If
        If CheckBoxR2.Checked = False Then
            If relays(1) = True Then
                rly = rly Or &H2
            End If
        End If
        If CheckBoxR3.Checked = False Then
            If relays(2) = True Then
                rly = rly Or &H4
            End If
        End If
        Dim bbuff(8) As Byte
        bbuff(0) = &H1B 'set states command byte
        bbuff(1) = &H7  'mask for 3 bits
        bbuff(2) = 0
        bbuff(3) = 0
        bbuff(4) = 0
        bbuff(5) = Convert.ToByte(rly)
        bbuff(6) = 0
        bbuff(7) = 0
        bbuff(8) = 0
        SendBytesHex(bbuff)    'send to XPort

        ' update relays
        UpdateRelays()

    End Sub

    ' TCP Send/Receive bytes hex
    Private Sub SendBytesHex(buff As Byte())

        ' write to socket
        Try
            Form1.LogScope("PwrBox > ", Color.Black, "Get relays")
            networkStream.Write(buff, 0, buff.Length)
        Catch ex As Exception
            Form1.LogScope("PwrBox Error: ", Color.DarkRed, ex.Message)
        End Try

        'read from socket
        Try
            Do
                Dim numBytesRead As Integer = networkStream.Read(buff, 0, buff.Length)
            Loop While networkStream.DataAvailable

            ' update relay state array
            If buff(0) = &H13 Or buff(0) = &H1B Then
                Dim ba As New BitArray({buff(1)})
                relays(0) = ba.Get(0)
                relays(1) = ba.Get(1)
                relays(2) = ba.Get(2)
            End If
            Form1.LogScope("PwrBox < ", Color.Black, "Relays")

            UpdateRelays()

        Catch ex As Exception
            Form1.LogScope("PwrBox Error: ", Color.DarkRed, ex.Message)

        End Try

    End Sub

    'get xport relay status
    Private Sub GetRelays()
        Dim bbuff(8) As Byte
        bbuff(0) = &H13
        SendBytesHex(bbuff) 'send to XPort

    End Sub

    'update relay indicators
    Private Sub UpdateRelays()
        If relays(0) = True Then
            PictureBoxR1.Image = My.Resources.BallGreen    'on
        Else
            PictureBoxR1.Image = My.Resources.BallRed     'off
        End If
        If relays(1) = True Then
            PictureBoxR2.Image = My.Resources.BallGreen    'on
        Else
            PictureBoxR2.Image = My.Resources.BallRed     'off
        End If
        If relays(2) = True Then
            PictureBoxR3.Image = My.Resources.BallGreen    'on
        Else
            PictureBoxR3.Image = My.Resources.BallRed     'off
        End If

    End Sub


    Private Sub ButtonAbort_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAbort.Click
        Form1.AbortStopWait = True

    End Sub

    Private Sub ButtonAllOn_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAllOn.Click
        SetQuery(True)

    End Sub

    Private Sub ButtonAllOff_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAllOff.Click
        SetQuery(False)

    End Sub

    Private Sub ButtonAllClear_Click(sender As System.Object, e As System.EventArgs) Handles ButtonAllClear.Click
        TextBoxFW.Text = ""
        TextBoxSP.Text = ""
        TextBoxLAT.Text = ""
        TextBoxLON.Text = ""
        TextBoxST.Text = ""
        TextBoxRA.Text = ""
        TextBoxDEC.Text = ""
        TextBoxALT.Text = ""
        TextBoxAZ.Text = ""
        TextBoxMountTime.Text = ""
        TextBoxMerDist.Text = ""
        TextBoxMerOffset.Text = ""
        TextBoxGOS.Text = ""

    End Sub

    Private Sub CheckBoxSetMOonConnect_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBoxSetMOonConnect.CheckedChanged
        If CheckBoxSetMOonConnect.Checked = True Then
            TextBoxSetMOConnect.Text = "Enabled"
        Else
            TextBoxSetMOConnect.Text = "Disabled"
        End If
        Form1.SetMeridianOffsetOnConnect = CheckBoxSetMOonConnect.Checked

    End Sub

    Private Sub ButtonShowSplash_Click_1(sender As System.Object, e As System.EventArgs) Handles ButtonShowSplash.Click
        SplashScreen1.ShowDialog()

    End Sub

    Private Sub PictureBox1_Click(sender As System.Object, e As System.EventArgs)
        Dim ImageFile As String = Form1.Path & "\dome_calculation.jpg"
        Try
            Process.Start(ImageFile)

        Catch ex As Exception
            MsgBox("Picture:" & vbCrLf & ImageFile & vbCrLf & vbCrLf & ex.Message, _
                    MsgBoxStyle.OkOnly, "Error opening picture")

        End Try

    End Sub

    Private Sub ButtonDomeTest_Click(sender As System.Object, e As System.EventArgs) Handles ButtonDomeTest.Click
        If TimerDomeTest.Enabled = False Then
            TimerDomeTest.Interval = 1000
            DomeTestLoop = NumLoop.Value
            ButtonDomeTest.Text = "Stop"
            DomeTestCnt = DomeTestLoop
            LabelTestCnt.Text = DomeTestCnt
            LabelTestCnt.Visible = True
            LabelDomeTestRunning.Visible = True
            TimerDomeTest.Enabled = True
        Else
            TimerDomeTest.Enabled = False
            LabelDomeTestRunning.Visible = False
            LabelTestCnt.Visible = False
            ButtonDomeTest.Text = "Start"
        End If

    End Sub

    Private Sub TimerDomeTest_Tick(sender As System.Object, e As System.EventArgs) Handles TimerDomeTest.Tick
        If Form_Dome.DomeConnected = True And DomeTestLoop > 0 Then
            DomeTestLoop = DomeTestLoop - 1
            Dim DomePos As Integer = Form_Dome.TrackBarDomePos.Value
            Dim DomeDeg As Integer = NumDegs.Value
            LabelTestCnt.Text = DomeTestCnt
            If DirCW.Checked = True Then
                DomePos = DomePos + DomeDeg
                If DomePos > 360 Then
                    DomePos = DomePos - 360
                End If
            End If
            If DirCCW.Checked = True Then
                DomePos = DomePos - DomeDeg
                If DomePos < 0 Then
                    DomePos = DomePos + 360
                End If
            End If
            Form_Dome.TrackBarDome.Value = DomePos
            Form_Dome.ButtonDomeGoto.PerformClick()
            TimerDomeTest.Interval = NumWait.Value * 1000
            DomeTestCnt = DomeTestCnt - 1
            If CheckBoxToggle.Checked = True Then
                If DirCW.Checked = True Then
                    DirCW.Checked = False
                    DirCCW.Checked = True
                Else
                    DirCW.Checked = True
                    DirCCW.Checked = False
                End If
            End If
        Else
            ButtonDomeTest.PerformClick()
        End If

    End Sub

    Private Function CheckAdminPriv()
        If My.User.IsInRole(ApplicationServices.BuiltInRole.Administrator) Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Sub ButtonTestToJ2000_Click(sender As System.Object, e As System.EventArgs) Handles ButtonTestToJ2000.Click
        RaIn = TextBoxTestRA.Text
        DecIn = TextBoxTestDEC.Text
        RaDecJ2000()
        TextBoxRANow.Text = NewRA
        TextBoxDECNow.Text = NewDEC

        RaIn = NewRA
        DecIn = NewDEC
        RaDecToJ2000()
        TextBoxRAJ2000.Text = NewRA
        TextBoxDECJ2000.Text = NewDEC

    End Sub

    Private Sub ButtonFocuserHelp_Click(sender As System.Object, e As System.EventArgs) Handles ButtonFocuserHelp.Click
        Form_FocusHelp.Show()

    End Sub

    Private Sub ButtonMainKeysHelp_Click(sender As System.Object, e As System.EventArgs) Handles ButtonMainKeysHelp.Click
        Form_KeysHelp.Show()

    End Sub

    Private Sub ButtonSetLogsFolder_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetLogsFolder.Click
        FolderBrowserDialog1.SelectedPath = Application.StartupPath
        If DialogResult.OK = FolderBrowserDialog1.ShowDialog() Then
            TextBoxLogsFolder.Text = FolderBrowserDialog1.SelectedPath
            Form1.LogsFolder = TextBoxLogsFolder.Text
        End If

    End Sub

    Private Sub ButtonDefaultLogsFolder_Click(sender As System.Object, e As System.EventArgs) Handles ButtonDefaultLogsFolder.Click
        TextBoxLogsFolder.Text = My.Computer.FileSystem.SpecialDirectories.MyDocuments
        Form1.LogsFolder = TextBoxLogsFolder.Text

    End Sub

    Private Sub ButtonXPortPort_Click(sender As System.Object, e As System.EventArgs) Handles ButtonXPortPort.Click
        APport.Text = "7777"
        ButtonUpdateAPport.PerformClick()

    End Sub

    Private Sub ButtonCP4Port_Click(sender As System.Object, e As System.EventArgs) Handles ButtonCP4Port.Click
        APport.Text = "23"
        ButtonUpdateAPport.PerformClick()

    End Sub

    Private Sub ButtonGetCP4ip_Click(sender As System.Object, e As System.EventArgs) Handles ButtonGetCP4ip.Click
        If Form1.CP4 = True Then
            SendReceiveAP(":ICp#", "CP4 IP address", True, 0)
            CP4IP = Mid(Form1.Rsp, 1, Len(Form1.Rsp) - 1)
            TextBoxAPip.Text = CP4IP
        End If

    End Sub

    Private Sub ButtonSetCP4ip_Click(sender As System.Object, e As System.EventArgs) Handles ButtonSetCP4ip.Click
        APip.Text = CP4ip

    End Sub

    Private Sub LabelGOS_Click(sender As System.Object, e As System.EventArgs) Handles LabelGOS.Click
        Form_GOS.Show()

    End Sub

End Class