Ejemplo n.º 1
0
 private void OnCOMPortDataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     do
     {
         var rxChar = Convert.ToByte(COMPort.ReadByte());
         RawData[DataIndex++] = rxChar;
         if (DataIndex >= RawData.Length)
         {
             DataIndex = 0;
             DataValid = false;
             try {
                 RocketData.Bytes   = RawData;
                 DataLastUpdateTime = DateTime.UtcNow;
                 DataStreamValid++;
             } catch (ArgumentException ex) {
                 Console.WriteLine($@"Rocket Data Error: {ex.Message}");
                 DataStreamInvalid++;
             }
         }
         else if (rxChar == 0xFF)
         {
             if (DataIndex >= 8)
             {
                 DataValid = true;
             }
         }
         else if (!DataValid)
         {
             DataIndex = 0;
         }
     } while (IsConnected && COMPort.BytesToRead > 0);
 }
Ejemplo n.º 2
0
 public void clearDataCOM()
 {
     try {
         COMPort.DiscardInBuffer();
     }
     catch (Exception ex) {}
 }
Ejemplo n.º 3
0
 protected virtual void ConnectToPort(object obj)
 {
     if (IsConnected || SerialPort.GetPortNames().All(x => x != SelectedPort))
     {
         COMPort.Close();
     }
     else
     {
         DataIndex         = 0;
         DataValid         = false;
         COMPort.PortName  = SelectedPort;
         COMPort.BaudRate  = 115200;
         COMPort.DataBits  = 8;
         COMPort.StopBits  = StopBits.One;
         COMPort.Handshake = Handshake.None;
         COMPort.Parity    = Parity.None;
         try {
             COMPort.Open();
         } catch (Exception ex) {
             Console.WriteLine($@"Error opening port: {ex.Message}");
         }
         DataLastUpdateTime = DateTime.UtcNow;
     }
     OnPropertyChanged(nameof(ComboIsEnabled));
     OnPropertyChanged(nameof(IsConnected));
     OnPropertyChanged(nameof(ConnectText));
     OnPropertyChanged(nameof(ConnectIsEnabled));
 }
Ejemplo n.º 4
0
        private void InitializeSerialPorts()
        {
            var ArrayComPortsNames = SerialPort.GetPortNames();
            var i = 0;

            foreach (string array in ArrayComPortsNames)
            {
                Model.COMPort port = new COMPort();
                port.Id  = i;
                port.COM = array;
                Model.COMPort.COMPorts.Add(port);
                i++;
            }
            Ports.ItemsSource           = Model.COMPort.COMPorts;
            Ports.DisplayMemberPath     = "COM";
            BaudRates.ItemsSource       = Model.BaudRate.BaudRates;
            BaudRates.DisplayMemberPath = "Value";

            HandShakes.ItemsSource       = EHandshake.Handshakes;
            Parities.ItemsSource         = EParity.Parities;
            StopBites.ItemsSource        = EStopBits.StopBites;
            HandShakes.DisplayMemberPath = "Name";
            Parities.DisplayMemberPath   = "Name";
            StopBites.DisplayMemberPath  = "Name";

            var settings = Settings.Instance;

            DataBits.Text            = settings.DataBits.ToString();
            BaudRates.SelectedIndex  = settings.BaudRate != null ? settings.BaudRate.Id : BaudRate.Default.Id;
            HandShakes.SelectedIndex = settings.Handshake != null ? settings.Handshake.Id : EHandshake.Default.Id;
            Parities.SelectedIndex   = settings.Parity != null ? settings.Parity.Id : EParity.Default.Id;
            StopBites.SelectedIndex  = settings.StopBits != null ? settings.StopBits.Id - 1 : EStopBits.Default.Id - 1;
        }
Ejemplo n.º 5
0
        public dynArduino()
        {
            //InPortData.Add(new PortData(null, "loop", "The loop to execute.", typeof(dynLoop)));
            InPortData.Add(new PortData(null, "i/o", "Switch Arduino on?", typeof(dynBool)));
            InPortData.Add(new PortData(null, "tim", "How often to receive updates.", typeof(dynTimer)));

            OutPortData.Add(new PortData(null, "S", "Serial output", typeof(dynDouble)));
            //OutPortData[0].Object = this.Tree;

            base.RegisterInputsAndOutputs();

            port           = new SerialPort("COM3", 9600);
            port.NewLine   = "\r\n";
            port.DtrEnable = true;
            //port.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

            com3Item             = new System.Windows.Controls.MenuItem();
            com3Item.Header      = "COM3";
            com3Item.IsCheckable = true;
            com3Item.IsChecked   = true;
            com3Item.Checked    += new System.Windows.RoutedEventHandler(com3Item_Checked);

            com4Item             = new System.Windows.Controls.MenuItem();
            com4Item.Header      = "COM4";
            com4Item.IsCheckable = true;
            com4Item.IsChecked   = false;
            com4Item.Checked    += new System.Windows.RoutedEventHandler(com4Item_Checked);

            this.MainContextMenu.Items.Add(com3Item);
            this.MainContextMenu.Items.Add(com4Item);
            portState     = COMPort.COM3;
            port.PortName = "COM3";
        }
Ejemplo n.º 6
0
 private void OnCOMPortDataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     do
     {
         var rxChar = Convert.ToByte(COMPort.ReadByte());
         RawData[DataIndex++] = rxChar;
         if (DataIndex >= RawData.Length)
         {
             DataIndex = 0;
         }
         if (DataValid)
         {
             DataValid = false;
             try {
                 //GSData.Bytes = _portDataRaw;
                 DataLastUpdateTime = DateTime.UtcNow;
                 DataStreamValid++;
             } catch (ArgumentException) {
                 DataStreamInvalid++;
             }
         }
         else if (rxChar == 0xFF)
         {
             if (DataIndex >= 8)
             {
                 DataValid = true;
             }
         }
         else
         {
             DataIndex = 0;
         }
     } while (COMPort.BytesToRead > 0);
 }
Ejemplo n.º 7
0
        private async void ConnectBtn_Click(object sender, EventArgs e)
        {
            try
            {
                ConnectBtn.Enabled      = false;
                LoadMessagesBtn.Enabled = false;
                DisconnectBtn.Enabled   = false;

                if (ComPortsComboBox.SelectedItem == null)
                {
                    throw new Exception("Select Valid COM Port");
                }
                COMPort portt = (COMPort)ComPortsComboBox.SelectedItem;
                AppendStatus($"Connecting to PORT: {portt.AttachedTo} {portt.Description}");
                //Try Connect
                await modemService.ConnectToCOMPortAsync(portt);

                AppendStatus($"CONNECTED to PORT: {portt.AttachedTo} {portt.Description}");
                ConnectBtn.Enabled      = true;
                LoadMessagesBtn.Enabled = true;
                DisconnectBtn.Enabled   = true;
            }
            catch (Exception ex)
            {
                AppendStatus($"ERROR: " + ex.Message);
                LoadMessagesBtn.Enabled = false;
                DisconnectBtn.Enabled   = false;
            }
        }
Ejemplo n.º 8
0
 /// <summary>
 /// Override lai ham nhan du lieu tu router emboard qua cong COM
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 public override void comPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
 {
     try
     {
         if (COMPort.IsOpen == true)
         {
             DataReadCOM = COMPort.ReadLine();
             //DataReadCOM = COMPort.ReadExisting();
             if (DataReadCOM[0] != '#' && DataReadCOM[0] != 'R')   // sai o cho nay, can hoi lai
             {
                 DisplayData(DataReadCOM, txtShowData);
             }
             if ((DataReadCOM.Length >= 6) && (DataReadCOM[0] == '#'))
             {
                 WebServer.dataSendToWeb.Enqueue(DataReadCOM);
                 //convertData(DataReadCOM);
                 DataProcess.Enqueue(DataReadCOM);
             }
         }
     }
     catch (Exception ex)
     {
         ERR = ex.Message;
     }
 }
Ejemplo n.º 9
0
        /// <summary>
        /// 处理接收到的Ntrip数据。
        /// </summary>
        /// <param name="myBytes"></param>
        private void ProcessReceivingData(byte[] myBytes)
        {
            //写到串口
            if (COMPort.IsOpen)
            {
                COMPort.Write(myBytes, 0, myBytes.Length);
            }
            //写到本地接收器
            if (this.Option.IsWriteToLocal)
            {
                WriteRawDataToLocal(myBytes);
            }
            //实时解析处理器
            if (Rtcm3DataReceiver != null)
            {
                Rtcm3DataReceiver.Receive(myBytes);
            }

            if (ReceivedByteCount == 0)
            {
                OnInfoProduced(Name + " NTRIP Client is receiving data.");
            }
            ReceivedByteCount += myBytes.Length;
            OnInstantInfoProduced(Name + " Connected, " + Strings.Format(ReceivedByteCount, "###,###,###,##0") + " bytes received.");
        }
Ejemplo n.º 10
0
 public Task <bool> ConnectToCOMPortAsync(COMPort port)
 {
     return(Task.Run(() =>
     {
         return ConnectToCOMPort(port);
     }));
 }
Ejemplo n.º 11
0
 private void COMPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     if (firstStart)
     {
         Display.Series[0].Points.Clear();
         Display.Series[1].Points.Clear();
         Display.Series[2].Points.Clear();
         firstStart = false;
     }
     if (NumMode.Checked == false)
     {
         byte[] buf = new byte[COMPort.BytesToRead];
         COMPort.Read(buf, 0, buf.Length);
         foreach (Byte mes in buf)
         {
             countByte++;
             value = value << 8 | mes;
             if (countByte == length)
             {
                 //Display.Series[seriousCount].Points.AddY(value);
                 this.Invoke(new Action(() =>
                 {
                     Display.Series[seriousCount].Points.AddY(value);
                 }));
                 value = 0;
                 seriousCount++;
                 countByte = 0;
             }
             if (seriousCount == seriousnum)
             {
                 seriousCount = 0;
             }
         }
     }
     else
     {
         byte[] buf = new byte[COMPort.BytesToRead];
         COMPort.Read(buf, 0, buf.Length);
         foreach (Byte mes in buf)
         {
             countByte++;
             value = value * 10 + (mes - '0');
             if (countByte == length)
             {
                 //Display.Series[seriousCount].Points.AddY(value);
                 this.Invoke(new Action(() =>
                 {
                     Display.Series[seriousCount].Points.AddY(value);
                 }));
                 value = 0;
                 seriousCount++;
                 countByte = 0;
             }
             if (seriousCount == seriousnum)
             {
                 seriousCount = 0;
             }
         }
     }
 }
Ejemplo n.º 12
0
        public void SendPacket()
        {
            if (!IsConnected)
            {
                return;
            }
            var data = GSCommand.Bytes;

            COMPort.Write(data, 0, data.Length);
        }
Ejemplo n.º 13
0
        public void SendPacket(bool launchArmed)
        {
            RocketCommand.LaunchArmed = launchArmed;
            if (!IsConnected)
            {
                return;
            }
            var data = RocketCommand.Bytes;

            COMPort.Write(data, 0, data.Length);
        }
Ejemplo n.º 14
0
        private void btnWrite_Click(object sender, EventArgs e)
        {
            byte[] buff = new byte[41];
            buff[0] = 0xaa;
            buff[1] = 0x57; // W
            buff[2] = Convert.ToByte(chkPPMA.Checked);
            buff[3] = (byte)(cbFrameA.SelectedIndex + 4);
            buff[4] = (byte)(cbChannelsA.SelectedIndex + 1);

            buff[5]  = (byte)(cbChA1.SelectedIndex);
            buff[6]  = (byte)(cbChA2.SelectedIndex);
            buff[7]  = (byte)(cbChA3.SelectedIndex);
            buff[8]  = (byte)(cbChA4.SelectedIndex);
            buff[9]  = (byte)(cbChA5.SelectedIndex);
            buff[10] = (byte)(cbChA6.SelectedIndex);
            buff[11] = (byte)(cbChA7.SelectedIndex);
            buff[12] = (byte)(cbChA8.SelectedIndex);
            buff[13] = (byte)(cbChA9.SelectedIndex);
            buff[14] = (byte)(cbChA10.SelectedIndex);
            buff[15] = (byte)(cbChA11.SelectedIndex);
            buff[16] = (byte)(cbChA12.SelectedIndex);
            buff[17] = (byte)(cbChA13.SelectedIndex);
            buff[18] = (byte)(cbChA14.SelectedIndex);
            buff[19] = (byte)(cbChA15.SelectedIndex);
            buff[20] = (byte)(cbChA16.SelectedIndex);

            buff[21] = Convert.ToByte(chkPPMB.Checked);
            buff[22] = (byte)(cbFrameB.SelectedIndex + 4);
            buff[23] = (byte)(cbChannelsB.SelectedIndex + 1);

            buff[24] = (byte)(cbChB1.SelectedIndex);
            buff[25] = (byte)(cbChB2.SelectedIndex);
            buff[26] = (byte)(cbChB3.SelectedIndex);
            buff[27] = (byte)(cbChB4.SelectedIndex);
            buff[28] = (byte)(cbChB5.SelectedIndex);
            buff[29] = (byte)(cbChB6.SelectedIndex);
            buff[30] = (byte)(cbChB7.SelectedIndex);
            buff[31] = (byte)(cbChB8.SelectedIndex);
            buff[32] = (byte)(cbChB9.SelectedIndex);
            buff[33] = (byte)(cbChB10.SelectedIndex);
            buff[34] = (byte)(cbChB11.SelectedIndex);
            buff[35] = (byte)(cbChB12.SelectedIndex);
            buff[36] = (byte)(cbChB13.SelectedIndex);
            buff[37] = (byte)(cbChB14.SelectedIndex);
            buff[38] = (byte)(cbChB15.SelectedIndex);
            buff[39] = (byte)(cbChB16.SelectedIndex);

            buff[40] = 0x5d;

            COMPort.Open();
            COMPort.Write(buff, 0, 41);
            COMPort.Close();
        }
Ejemplo n.º 15
0
    public static void ThreadWriteProcess()
    {
        COMPort cp = new COMPort("COM1");

        cp.Open();
        for (int i = 0; i < 100; i++)
        {
            Thread.Sleep(100);
            cp.setBuffer(System.Text.Encoding.ASCII.GetBytes("hello world"));
            cp.Write();
        }
        cp.Close();
    }
Ejemplo n.º 16
0
    public static void ThreadReadProcess()
    {
        COMPort cp = new COMPort("COM2");

        cp.Open();
        while (true)
        {
            Thread.Sleep(100);
            if (cp.Read() > 0)
            {
                Console.WriteLine(System.Text.Encoding.ASCII.GetString(cp.getBuffer()));
            }
        }
    }
Ejemplo n.º 17
0
 public bool ConnectToCOMPort(COMPort port)
 {
     //Will Close any Active or Open Port
     DisconnectFromCOMPort();
     ActiveSerialPort.PortName  = port.AttachedTo;
     ActiveSerialPort.BaudRate  = 9600;
     ActiveSerialPort.Parity    = System.IO.Ports.Parity.None;
     ActiveSerialPort.DataBits  = 8;
     ActiveSerialPort.StopBits  = System.IO.Ports.StopBits.One;
     ActiveSerialPort.Handshake = System.IO.Ports.Handshake.None;
     ActiveSerialPort.RtsEnable = true;
     ActiveSerialPort.ReceivedBytesThreshold = 1;
     ActiveSerialPort.NewLine     = Environment.NewLine;
     ActiveSerialPort.ReadTimeout = 1000;
     ActiveSerialPort.Open();
     return(IsCOMPortOpen());
 }
Ejemplo n.º 18
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (button1.Text == "打开串口")
     {
         if (comboBoxBaudRate.SelectedIndex == 1)
         {
             COMPort.BaudRate = 115200;
         }
         else
         {
             COMPort.BaudRate = 9600;
         }
         try
         {
             COMPort.PortName = comboBoxCOM.Text;
             COMPort.Open();
         }
         catch (ArgumentException exc)
         {
             MessageBox.Show(exc.Message);
             return;
         }
         if (COMPort.IsOpen)
         {
             MessageBox.Show("打开成功");
             string s   = "SGT_Debuger Online";
             byte[] buf = Encoding.ASCII.GetBytes(s);
             COMPort.Write(buf, 0, s.Length);
             button1.Text = "关闭串口";
         }
         else
         {
             MessageBox.Show("存在问题");
         }
     }
     else
     {
         string s   = "SGT_Debuger Offline";
         byte[] buf = Encoding.ASCII.GetBytes(s);
         COMPort.Write(buf, 0, s.Length);
         COMPort.Close();
         button1.Text = "打开串口";
     }
 }
Ejemplo n.º 19
0
        // Executes at DXLog.net start
        public void Initialize(FrmMain main)
        {
            mainForm = main;
            CATCommon radio1 = main.COMMainProvider.RadioObject(1);

            if (main.ContestDataProvider.OPTechnique == ContestData.Technique.SO2V)
            {
                // Find Microham port
                foreach (COMPort _comport in main.COMMainProvider._com)
                {
                    if (_comport._mk2r != null)
                    {
                        microHamPort = _comport;
                    }
                }

                if (microHamPort != null)
                {
                    // Initialize temporary stereo mode to DXLog's stereo mode to support temporary toggle
                    // At start up, radio 1 is always focused and stereo audio is forced
                    main.SetListenStatusMode(COMMain.ListenMode.R1R2, true, false);
                    tempStereoToggle = false;
                    lastFocusedRadio = 1;

                    main.ContestDataProvider.FocusedRadioChanged += new ContestData.FocusedRadioChange(HandleFocusChange);

                    // Only initialize radio if present and ICOM
                    if (radio1 != null)
                    {
                        if (radio1.IsICOM())
                        {
                            // Initialize radio to DW off, Split off and Main VFO focused
                            radio1.SendCustomCommand(IcomDualWatchOn);
                            radio1.SendCustomCommand(IcomSelectMain);
                            radio1.SendCustomCommand(IcomSplitOff);
                        }
                    }
                }
                else
                {
                    main.COMMainProvider.SignalMessage("ICOM_SO2V: ERROR no Microham device");
                }
            }
        }
Ejemplo n.º 20
0
 private void button1_Click(object sender, EventArgs e)
 {
     if (comboBoxBaudRate.SelectedIndex == 1)
     {
         COMPort.BaudRate = 115200;
     }
     else
     {
         COMPort.BaudRate = 9600;
     }
     try
     {
         COMPort.PortName = comboBoxCOM.Text;
         COMPort.Open();
     }
     catch (ArgumentException exc)
     {
         MessageBox.Show(exc.Message);
         return;
     }
     button1.Text = "连接成功";
 }
Ejemplo n.º 21
0
 private void ModbusSendReceive(object param)
 {
     lock (this)
     {
         try
         {
             ModbusParam parameters;
             if (param is ModbusParam)
             {
                 parameters = (ModbusParam)param;
             }
             else
             {
                 throw new ModbusPDUException("Wrong parametrization of ModbusSendReceive method.");
             }
             byte[] responseFrame = new byte[(int)parameters.ResponseSize];
             COMPort.DiscardInBuffer();
             COMPort.Write(parameters.RequestADU, 0, parameters.RequestADU.Length);
             Thread.Sleep(ResponseWaitingDelay);
             COMPort.Read(responseFrame, 0, (int)parameters.ResponseSize);
             byte[] adu = ModbusSerialPDU.extractADU(responseFrame);
             if (responseFrame[1] > (byte)127)
             {
                 throw new ModbusPDUException(String.Format("Modbus application error : function {0:X}, exception {1:X}", responseFrame[1], responseFrame[2]));
             }
             else
             if (responseFrame[1] == 0x03)
             {
                 Int16[] values = GetValuesFromResponseADU03(adu);
                 ModbusDataReceived(values);
             }
         }
         catch (Exception ex)
         {
             commException = ex;
             ModbusError(ex);
         }
     }
 }
Ejemplo n.º 22
0
        /// <summary>
        /// 串口输入。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void SerialInput(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                ReceiveBuffer += COMPort.ReadExisting();

                if (ReceiveBuffer.IndexOf("\r\n") + 1 == 1)// == 1 为添加
                {
                    //If InStr(ReceiveBuffer, Chr(13)) Then
                    //Contains at least one carridge return
                    string[] lines = ReceiveBuffer.Split('\n');
                    //Dim lines() As String = Split(ReceiveBuffer, Chr(13))
                    for (var i = 0; i <= (lines.Length - 1) - 1; i++)
                    {
                        if (lines[(int)i].Length > 5)
                        {
                            SendSerialLineToUIThread(lines[(int)i].Trim());
                        }
                    }
                    ReceiveBuffer = lines[(lines.Length - 1)];
                }
                else
                {
                    //Data doesn't contain any line breaks
                    if (ReceiveBuffer.Length > 4000)
                    {
                        ReceiveBuffer = "";
                        SendSerialLineToUIThread("No line breaks found in data stream.");
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(ex.Message);
            }
        }
Ejemplo n.º 23
0
        public dynArduino()
        {
            //InPortData.Add(new PortData(null, "loop", "The loop to execute.", typeof(dynLoop)));
            InPortData.Add(new PortData(null, "i/o", "Switch Arduino on?", typeof(dynBool)));
            InPortData.Add(new PortData(null, "tim", "How often to receive updates.", typeof(dynTimer)));

            OutPortData.Add(new PortData(null, "S", "Serial output", typeof(dynDouble)));
            //OutPortData[0].Object = this.Tree;

            base.RegisterInputsAndOutputs();

            port = new SerialPort("COM3", 9600);
            port.NewLine = "\r\n";
            port.DtrEnable = true;
            //port.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);

            com3Item = new System.Windows.Controls.MenuItem();
            com3Item.Header = "COM3";
            com3Item.IsCheckable = true;
            com3Item.IsChecked = true;
            com3Item.Checked += new System.Windows.RoutedEventHandler(com3Item_Checked);

            com4Item = new System.Windows.Controls.MenuItem();
            com4Item.Header = "COM4";
            com4Item.IsCheckable = true;
            com4Item.IsChecked = false;
            com4Item.Checked += new System.Windows.RoutedEventHandler(com4Item_Checked);

            this.MainContextMenu.Items.Add(com3Item);
            this.MainContextMenu.Items.Add(com4Item);
            portState = COMPort.COM3;
            port.PortName = "COM3";
        }
 public ApexValidator(COMPort comm, CultureInfo culture)
 {
     comPort = comm;
     currentCulture = culture;
 }
 public ApexValidator(string comm, CultureInfo culture)
 {
     comPort = (COMPort)Enum.Parse(typeof(COMPort), comm);
     currentCulture = culture;
 }
Ejemplo n.º 26
0
 private void SendOut(char[] message)
 {
     COMPort.Write(message, 0, 5);
     Thread.Sleep(100);
 }
Ejemplo n.º 27
0
 private void COMPort_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
 {
     labelMES.Text = COMPort.ReadExisting();
 }
 public ApexValidator(COMPort comm, string culture)
 {
     comPort = comm;
     currentCulture = new CultureInfo(culture);
 }
Ejemplo n.º 29
0
        private void btnRead_Click(object sender, EventArgs e)
        {
            byte[] buff = new byte[41];
            buff[0] = 0xaa;
            buff[1] = 0x52; // R

            for (int i = 2; i < 40; i++)
            {
                buff[i] = 0;
            }

            buff[40] = 0x5d;

            COMPort.Open();
            COMPort.Write(buff, 0, 41);

            int cnt = 0;

            while (cnt < 40)
            {
                if (COMPort.BytesToRead > 40)
                {
                    cnt = COMPort.Read(buff, 0, 41);
                }
            }
            COMPort.Close();

            chkPPMA.Checked = (buff[2] == 1);
            if (buff[3] - 4 < 7)
            {
                cbFrameA.SelectedIndex = buff[3] - 4;
            }
            if (buff[4] - 1 < 16)
            {
                cbChannelsA.SelectedIndex = buff[4] - 1;
            }

            if (buff[5] < 17)
            {
                cbChA1.SelectedIndex = buff[5];
            }
            if (buff[6] < 17)
            {
                cbChA2.SelectedIndex = buff[6];
            }
            if (buff[7] < 17)
            {
                cbChA3.SelectedIndex = buff[7];
            }
            if (buff[8] < 17)
            {
                cbChA4.SelectedIndex = buff[8];
            }
            if (buff[9] < 17)
            {
                cbChA5.SelectedIndex = buff[9];
            }
            if (buff[10] < 17)
            {
                cbChA6.SelectedIndex = buff[10];
            }
            if (buff[11] < 17)
            {
                cbChA7.SelectedIndex = buff[11];
            }
            if (buff[12] < 17)
            {
                cbChA8.SelectedIndex = buff[12];
            }
            if (buff[13] < 17)
            {
                cbChA9.SelectedIndex = buff[13];
            }
            if (buff[14] < 17)
            {
                cbChA10.SelectedIndex = buff[14];
            }
            if (buff[15] < 17)
            {
                cbChA11.SelectedIndex = buff[15];
            }
            if (buff[16] < 17)
            {
                cbChA12.SelectedIndex = buff[16];
            }
            if (buff[17] < 17)
            {
                cbChA13.SelectedIndex = buff[17];
            }
            if (buff[18] < 17)
            {
                cbChA14.SelectedIndex = buff[18];
            }
            if (buff[19] < 17)
            {
                cbChA15.SelectedIndex = buff[19];
            }
            if (buff[20] < 17)
            {
                cbChA16.SelectedIndex = buff[20];
            }

            chkPPMB.Checked = (buff[21] == 1);
            if (buff[22] - 4 < 7)
            {
                cbFrameB.SelectedIndex = buff[22] - 4;
            }
            if (buff[23] - 1 < 16)
            {
                cbChannelsB.SelectedIndex = buff[23] - 1;
            }

            if (buff[24] < 17)
            {
                cbChB1.SelectedIndex = buff[24];
            }
            if (buff[25] < 17)
            {
                cbChB2.SelectedIndex = buff[25];
            }
            if (buff[26] < 17)
            {
                cbChB3.SelectedIndex = buff[26];
            }
            if (buff[27] < 17)
            {
                cbChB4.SelectedIndex = buff[27];
            }
            if (buff[28] < 17)
            {
                cbChB5.SelectedIndex = buff[28];
            }
            if (buff[29] < 17)
            {
                cbChB6.SelectedIndex = buff[29];
            }
            if (buff[30] < 17)
            {
                cbChB7.SelectedIndex = buff[30];
            }
            if (buff[31] < 17)
            {
                cbChB8.SelectedIndex = buff[31];
            }
            if (buff[32] < 17)
            {
                cbChB9.SelectedIndex = buff[32];
            }
            if (buff[33] < 17)
            {
                cbChB10.SelectedIndex = buff[33];
            }
            if (buff[34] < 17)
            {
                cbChB11.SelectedIndex = buff[34];
            }
            if (buff[35] < 17)
            {
                cbChB12.SelectedIndex = buff[35];
            }
            if (buff[36] < 17)
            {
                cbChB13.SelectedIndex = buff[36];
            }
            if (buff[37] < 17)
            {
                cbChB14.SelectedIndex = buff[37];
            }
            if (buff[38] < 17)
            {
                cbChB15.SelectedIndex = buff[38];
            }
            if (buff[39] < 17)
            {
                cbChB16.SelectedIndex = buff[39];
            }
        }
Ejemplo n.º 30
0
 void com3Item_Checked(object sender, System.Windows.RoutedEventArgs e)
 {
     portState          = COMPort.COM3;
     com4Item.IsChecked = false;
     com3Item.IsChecked = true;
 }
 public ApexValidator(string comm)
 {
     comPort = (COMPort)Enum.Parse(typeof(COMPort), comm);
 }
Ejemplo n.º 32
0
        static void Main(string[] args)
        {
            String           localCallSign;
            String           cmd;
            String           loopback;
            Int32            channel = 0;
            Int32            baud    = 9600;
            String           tmpc;
            DataLinkProvider dlProvider;
            DataLinkProvider digi1;
            DataLinkProvider digi2;

            Connection.ConnectionParameterBuf conParams;
            Connection.ConnectionStatus       cstat;
            Connection.ConnectionStatus[]     mcstat = new Connection.ConnectionStatus[12];
            DataLinkProvider[] testProvider          = new DataLinkProvider[12];

            Console.Write("Local station callsign-SSID? (e.g. KA1XYZ-5) ? ");
            localCallSign = Console.ReadLine();

            //
            // Set loopback mode to Y if you are not using a TNC.
            //
            Console.Write("Use loopback mode? (y/[n]) ");
            tmpc     = Console.ReadLine();
            loopback = tmpc;

            Console.Write("TNC Channel number? ([0]/1/2) ");
            tmpc = Console.ReadLine();
            if (tmpc.Length > 0)
            {
                channel = Convert.ToInt32(Console.ReadLine());
            }
            //
            // Step 1: Create the low level Com Port that communicates directly
            // with the TNC
            //
            if (loopback.ToUpper().StartsWith("Y"))
            {
                //
                // Use loopback.  No data goes out the serial port
                //
                tncComPort = new COMPort("COM1", 9600, true);
            }
            else
            {
                //
                // No loopback.  Use the real TNC
                //
                Console.Write("Com Port? (COM1, COM2, etc) ");
                String comp = Console.ReadLine().ToUpper();

                Console.Write("Baud? ([9600],19200, etc) ");
                tmpc = Console.ReadLine();
                if (tmpc.Length > 0)
                {
                    baud = Convert.ToInt32(tmpc);           // (JNW Feb 15)
                }

                tncComPort = new COMPort(comp, baud);
            }

            Char[] c = { ' ' };

            //
            // Tell the KISS layer if there are any characters to 'escape' in
            // the data stream.  The reason for this is some KISS implementations
            // (Like the TNC in the Kenwood D710A) actually act upon certain
            // character sequences even when in KISS mode.
            //
            // Example: Escape the 'C' character (needed on TM-D710)
            //
            // You can also add escape byte for non printable characters using the
            // SetEscapedCharList().  In this case, supply a string that contains the
            // comma separated list of bytes to escape.  Example: A string value of:
            // "03, 0d" will exclude byte valus 0x03 and 0x0d
            //
            tncComPort.escapedCharList = "C";

            //tncComPort.SetEscapedCharsList("03, 0d");

            //
            // Step 2: Create a TNC channel on top of the COM port. TNCs like
            // the KPC3+ have one channel (channel 0).  Other TNCs like the KAM
            // Plus have 2 (one for VHF (channel 0) and one for HF (channel 1).  The
            // KISS protocol dictates that TNC Channels MUST be in the range of 0-15.
            //
            tncVHFChannel = tncComPort.CreateChannel(channel);

            //
            // (Optional) Enable the packet monitor function if we want to
            // monitor all incoming and outgoing packets.  Setting the value
            // to 'Both' enables queue monitoring as well as file logging of
            // the packets.  (We defined the filename above by setting the static
            // member: Support.pktLogFile above.)
            //
            tncVHFChannel.packetMonitorEnable = TNCChannel.PacketMonitorType.Both;

            //
            // Step 3: Create a DataLinkProvider assigning it the desited
            // local station callsign-ssid.  Multiple Data Link Providers \
            // are supported, however each must have a unique callsign-ssid.
            //
            dlProvider           = tncVHFChannel.CreateProvider(localCallSign);
            digi1                = tncVHFChannel.CreateProvider("RELAY1");
            digi1.digipeatEnable = true;
            digi2                = tncVHFChannel.CreateProvider("RELAY2");
            digi2.digipeatEnable = true;


            //
            // Note: 3a.1 - 3a-3 are optional steps you would do if you want
            // to change any of the default connection parameter settings for
            // this particular connection, like MAXIFrame, MaxWindowsSize, etc.
            // Unless you are planning to change the defaults, you don't have
            // to do this and can skip right to step 4.
            //

            //
            // Step 3a.1: (Optional) Create a Connection parameter buf to
            // use during XID negotiation.
            //
            conParams = new Connection.ConnectionParameterBuf();

            //
            // Step 3a.2: (Optional) Make any changes to the parameter values
            // in the parameter buffer here
            //

            //conParams.maxWindowSize = 1;
            //conParams.maxIFrame = 2;

            //
            // Step 3a.3: Create a connection using the connection parameters
            // specified in the parameter buffer and skip step 4 below.
            //
            con = dlProvider.CreateConnection(conParams);

            for (Int32 i = 0; i < testProvider.Length; i++)
            {
                testProvider[i] = tncVHFChannel.CreateProvider("T6EST-" + i.ToString());
                mcon[i]         = testProvider[i].CreateConnection(conParams);
                mcon[i].registerStateHandlers.ReportConnectionEvents      += new EventHandler <ConnectionEvents>(NotifyConnectionState);
                mcon[i].registerIndicationHandlers.ReportIndicationEvents += new EventHandler <IndicationEvents>(NotifyIndicationEvents);
            }


            //
            // Step 4: Create the Connection using default parameters
            //
            //con = dlProvider.CreateConnection();

            //
            // Register for connection state change notifications, if desired
            //
            con.registerStateHandlers.ReportConnectionEvents += new EventHandler <ConnectionEvents>(NotifyConnectionState);

            //
            // Register for protocol indication event notifications, if desired
            //
            con.registerIndicationHandlers.ReportIndicationEvents += new EventHandler <IndicationEvents>(NotifyIndicationEvents);

            //
            // Launch our packet monitor thread. (If we chose to monitor packets
            // above).
            //
            MonitorThread      = new Thread(PacketMonitor);
            MonitorThread.Name = "PacketMonitor Thread";
            MonitorThread.Start();

            //
            // Launch the thread the displays the data stream coming back from
            // the remote station
            //
            ReaderThread      = new Thread(Reader);
            ReaderThread.Name = "Reader Thread";
            ReaderThread.Start();

            //
            // Create a thread that adds a second DataLinkProvider with a different
            // callsign that we can perform loopback testing with.  We only start
            // the thread when requested by the command '@listener callsign-ssid'.
            // You would typically only do this when testing in loopback mode.
            //
            // In an applications where you wait for other stations to connect,
            // you can create a pool of connection threads that would permit
            // multiple independent incoming connections to your app simultaneously.
            //
            ResponderThread = new Thread(Responder);

            //
            // Command processing loop
            //
            StringBuilder sb = new StringBuilder("Commands:" + CRLF);

            sb.Append("  @h                       - this help text" + CRLF);
            sb.Append("  @listener callsign-ssid  - Create a second DataLinkProvider for callsign-ssid" + CRLF);
            sb.Append("  @con callsign-ssid [digi1] [digi2]" + CRLF);
            sb.Append("                           - Connect to remote station callsign-ssid using optional relays" + CRLF);
            sb.Append("  @mcon n callsign-ssid    - Connect T6EST-n to remote station callsign-ssid" + CRLF);
            sb.Append("  @xid                     - Initiate XID negotiation" + CRLF);
            sb.Append("  @data callsign-ssid text - Send 'text' to calllsign-ssid as a datagram packet" + CRLF);
            sb.Append("  @test callsign-ssid text - Send a TEST command to callsign-ssid & " + CRLF);
            sb.Append("                                wait 5 seconds for a response" + CRLF);
            sb.Append("  @disc                    - Disconnect from the currently connected station" + CRLF);
            sb.Append("  @mdisc n                 - Disconnect T6EST-n" + CRLF);
            sb.Append("  @digi callsign-ssid      - Create a digipeater at callsign-ssid" + CRLF);
            sb.Append("  @bye                     - Disconnect from the currently connected station & " + CRLF);
            sb.Append("                                and exit the program" + CRLF);
            sb.Append("  @koff                    - Send the Exit KISS mode sequence to the TNC" + CRLF);
            sb.Append("  (other text)             - Send as data to the connected station" + CRLF + CRLF);

            Console.WriteLine(sb.ToString());

            while (true && dlProvider.Enabled)
            {
                //
                // Command loop
                //
                Console.Write(">>> ");
                cmd = Console.ReadLine();
                if (cmd.StartsWith("@h"))
                {
                    Console.WriteLine(sb.ToString());
                    continue;
                }

                if (cmd.StartsWith("@xid"))
                {
                    Console.WriteLine("Initiate XID negotiation with remote.  status: " +
                                      con.InitiateXID().ToString());
                    continue;
                }

                if (cmd.StartsWith("@test "))
                {
                    //
                    // Test command requested
                    //
                    String h  = cmd.Substring(6);
                    Int32  q  = h.IndexOf(" ");
                    String c1 = h.Substring(0, q);
                    h = h.Substring(q + 1);

                    Byte[] resp = dlProvider.LinkTest(c1, "", "",
                                                      Encoding.ASCII.GetBytes(h), 5000);
                    String respC = "(Timeout)";
                    if (resp != null)
                    {
                        respC = Encoding.ASCII.GetString(resp);
                    }
                    Console.WriteLine("Test response: " + respC);
                    continue;
                }

                if (cmd.StartsWith("@koff"))
                {
                    //
                    // Send the Kiss Exit command to the TNC
                    //
                    tncVHFChannel.SetKissModeOff();
                    continue;
                }

                if (cmd.StartsWith("@digi "))
                {
                    //
                    // Start a digipeater
                    //
                    String           h  = cmd.Substring(6);
                    DataLinkProvider dl = tncVHFChannel.CreateProvider(h);
                    dl.digipeatEnable        = true;
                    dl.accessControlListType = DataLinkProvider.AccessControlListType.black;
                    dl.AccessControlListAdd("n6prw-3");
                    continue;
                }

                if (cmd.StartsWith("@data "))
                {
                    //
                    // Send UI datagram
                    //
                    String h  = cmd.Substring(6);
                    Int32  q  = h.IndexOf(" ");
                    String c1 = h.Substring(0, q);
                    h = h.Substring(q + 1);
                    dlProvider.SendDatagram(c1, Encoding.ASCII.GetBytes(h),
                                            Frame.ProtocolVersion.V22);
                    Console.WriteLine("Datagram Sent: " + h);
                    continue;
                }

                if (cmd.StartsWith("@mcon "))
                {
                    //
                    // Connect to remote station
                    //
                    String[] h = cmd.Substring(6).Split(c);
                    Int32    m = 0;

                    if (h.Length == 2)
                    {
                        m         = Convert.ToInt32(h[0]);
                        mcstat[m] = mcon[m].Connect(h[1]);
                        Console.WriteLine("Connect status: " + mcstat[m].ToString());
                    }
                    continue;
                }

                if (cmd.StartsWith("@con "))
                {
                    //
                    // Connect to remote station
                    //
                    cstat = Connection.ConnectionStatus.Busy;
                    String[] h = cmd.Substring(5).Split(c);

                    if (h.Length == 1)
                    {
                        cstat = con.Connect(h[0]);
                    }
                    if (h.Length == 2)
                    {
                        cstat = con.Connect(h[0], h[1]);
                    }
                    if (h.Length == 3)
                    {
                        cstat = con.Connect(h[0], h[1], h[2]);
                    }

                    Console.WriteLine("Connect status: " + cstat.ToString());
                    continue;
                }

                if (cmd.StartsWith("@listener "))
                {
                    //
                    // Start the listener we'll use for loopback testing
                    //
                    String h = cmd.Substring(10);
                    responderCallSign = h;
                    if (!ResponderThread.IsAlive)
                    {
                        ResponderThread.Start();
                    }
                    continue;
                }

                if (cmd.StartsWith("@disc"))
                {
                    //
                    // Disconnect from the remote station
                    //
                    cstat = con.Disconnect();
                    Console.WriteLine("Disconnected:  status: " + cstat.ToString());
                    continue;
                }
                if (cmd.StartsWith("@mdisc "))
                {
                    //
                    // Disconnect from the remote station
                    //
                    String[] h = cmd.Substring(7).Split(c);
                    Int32    m = 0;
                    if (h.Length == 1)
                    {
                        m         = Convert.ToInt32(h[0]);
                        mcstat[m] = mcon[m].Disconnect();
                        Console.WriteLine("Disconnected:  status: " + mcstat[m].ToString());
                    }
                    continue;
                }


                if (cmd.StartsWith("@exit"))
                {
                    //
                    // Exit KISS mode
                    //
                    tncVHFChannel.SetKissModeOff();
                    Console.WriteLine("Kiss mode exited");
                    break;
                }

                if (cmd.StartsWith("@bye"))
                {
                    //
                    // Disconnect and close the program
                    //
                    cstat = con.Disconnect();
                    Console.WriteLine("Disconnected:  status: " + cstat.ToString());
                    break;
                }

                // everything else is treated as data

                if (!con.isConnected)
                {
                    Console.WriteLine("Not connected...");
                    continue;
                }
                else
                {
                    if (cmd.Length > 0)
                    {
                        con.Send(Encoding.ASCII.GetBytes(cmd + CR));
                    }
                    else
                    {
                        Console.WriteLine("Nothing to send");
                    }
                }
            }
            //con.Close();
            //dlProvider.Close();
            //tncVHFChannel.Close();

            //
            // Time to go.  Just shutting down the lower layer is sufficient.
            // All the upper instances will be shut down as well.
            //
            tncComPort.Close();
            Console.Write("Press return to exit");
            cmd = Console.ReadLine();
        }
Ejemplo n.º 33
0
 void com4Item_Checked(object sender, System.Windows.RoutedEventArgs e)
 {
     portState = COMPort.COM4;
     com4Item.IsChecked = true;
     com3Item.IsChecked = false;
 }
 public ApexValidator(COMPort comm)
 {
     comPort = comm;
 }
Ejemplo n.º 35
0
        // TBD split this constructor up into 5 separate user story abstractions in a new User stories layer
        // Do we need a layer called plug-in to pul this off?
        // or can each user stor object have some public instances that get wired by the us


        private Application()
        {
            // First part of the code is to set up a real farming device simulator instance that we configure with mock data.
            // In the real application, this would be a real farming device connected to the physical COM port of the PC.
            // This simulated device gets wired to the COMPort abstraction and pretends to be connected to a real serial COM port.
            // The simulated device is not part of the application, so is not shown on the application-diagram even though we instantiate and configure it here.
            // The simulated device emulates the real devices ability to receive SCP commands and respond to them.

            var simulatedExternalDevice = new RealFarmingDeviceSimulator();

            // Configure the simulated device with some session data
            // Farmers call their files inside devices "sessions". They can configure the fields that they want to use, so here we have three sessions, each with different fields.
            simulatedExternalDevice.AddSession(name: "session0", date: "2021-02-28", columns: new[] { "F01FID", "F11EID" });
            simulatedExternalDevice.AddSession(name: "session1", date: "2021-03-31", columns: new[] { "F01FID", "F11EID", "F10Weight" });
            simulatedExternalDevice.AddSession(name: "session2", date: "2021-04-30", columns: new[] { "F01FID", "F11EID", "F10Weight", "F12Remark" });
            simulatedExternalDevice.AddSessionData(index: 0, sessionData: new[] { "1", "EID0000000000000" });
            simulatedExternalDevice.AddSessionData(index: 0, sessionData: new[] { "2", "EID0000000000001" });
            simulatedExternalDevice.AddSessionData(index: 1, sessionData: new[] { "013", "EID0000000000010", "342" });
            simulatedExternalDevice.AddSessionData(index: 1, sessionData: new[] { "001", "EID0000000000011", "373" });
            simulatedExternalDevice.AddSessionData(index: 1, sessionData: new[] { "002", "EID0000000000012", "304" });
            simulatedExternalDevice.AddSessionData(index: 2, sessionData: new[] { "0123", "EID0000000000021", "405", "healthy" });
            simulatedExternalDevice.AddSessionData(index: 2, sessionData: new[] { "1023", "EID0000000000022", "376", "pregnant" });
            simulatedExternalDevice.AddSessionData(index: 2, sessionData: new[] { "0412", "EID0000000000023", "354", "black spot" });
            simulatedExternalDevice.AddSessionData(index: 2, sessionData: new[] { "0219", "EID0000000000024", "395", "lame" });



// -------------------------- BEGIN CODE MANUALLY GENERATED FROM DIAGRAM --------------------------------------------------------------
            // The following code has been manually generated from the diagram in application-diagram.drawio (read-only version in application-diagram.pdf)
            // Refer to that diagram for how this application works, not this code.
            // Also application.md is a commentary on reading the diagram.
            // Take an interest in this code if:
            // 1. You want to understand how the diagram was hand-coded
            // 2. You want to know all the mechanics of how the ALA diagram was made to actually execute
            // 3. You have modified the diagram and need to correspondingly modify this code


            // First instantiate any domain abstractions that we can't instantiate anonymously in the later code because they need to be referred to by name because the diagram has circular wiring:

            var saveFileBrowser = new SaveFileBrowser(title: "Save file", extension: "CSV");
            var textConnected   = new Text("Connected", false)
            {
                Color = Brushes.Green
            };
            var textSearching = new Text("Searching for a device...")
            {
                Color = Brushes.Red
            };
            var scpProtocol = new SCPProtocol();
            var arbitrator  = new Arbitrator()
            {
                InstanceName = "scpDevice"
            };
            var ignoredDataFlowConnector = new DataFlowConnector <string>();
            var sessionListScp           = new SCPSessions()
            {
                InstanceName = "sessionList"
            };
            var sessionDataScp = new SCPData()
            {
                InstanceName = "forGrid"
            };
            var sessionDataScpImport = new SCPData()
            {
                InstanceName = "import"
            };
            var saveToCsvFileTransact = new Transfer()
            {
                InstanceName = "save to csv file transact", AutoLoadNextBatch = true
            };
            var sessionListGrid = new Grid()
            {
                InstanceName = "sessions", RowHeight = 50, PrimaryKey = "index"
            };
            var sessionDataGrid = new Grid()
            {
                InstanceName = "data"
            };
            var csvFileReaderWriter = new CSVFileReaderWriter();
            var comPort             = new COMPort();


            // Now do all the wiring of the diagram
            // Note any instances of domain abstractions not already instantiated anonymously in this code.
            // Note that a.wireTo(b) is an extension method that uses reflection to wire 'a' to 'b' via 'ports'. The ports on 'a' and 'b' must be a programmming paradigm interface of the same interface type - 'a' must have a private field of the interface and 'b' must implement the interface.
            // Note that the fluent style is used: wireTo returns its first argument, allowing you to call wireTo again to wire it some thing else.
            // Note that InstanceName properties are not needed by the code - they are just to help when debugging because if there are multiple instances of the same domain abstraction you often dont know which instance you have break-pointed into.
            // Sometimes WireTo has a second parameter which is the name of the specific port it is wiring to. This ensures wiring to the correct port if there is more than one port of a given type.
            mainWindow
            // UI
            .WireTo(new Vertical(true)
            {
                Layouts = new int[] { 0, 0, 2, 0 }
            }
                    .WireTo(new Horizontal()
            {
                InstanceName = "menubar"
            }
                            .WireTo(new Menubar()
                                    .WireTo(new Menu("File")
                                            .WireTo(new MenuItem("Import from device")
                                                    .WireTo(new Wizard("Where do you want to put it?")
                                                            .WireTo(new RadioButton("Local CSV file")
                                                                    .WireTo(saveFileBrowser)
                                                                    )
                                                            .WireTo(new RadioButton("Cloud"))
                                                            )
                                                    )
                                            .WireTo(new MenuItem("Exit")
                                                    .WireTo(mainWindow)
                                                    )
                                            )
                                    )
                            )
                    .WireTo(new Horizontal()
            {
                InstanceName = "toolbar"
            }
                            .WireTo(new Toolbar()
                                    .WireTo(new Tool("5000Import.png")
                                            .WireTo(saveFileBrowser
                                                    .WireTo(csvFileReaderWriter, "dataFlowOutputFilePathNames")
                                                    .WireTo(saveToCsvFileTransact
                                                            .WireTo(sessionDataScpImport
                                                                    .WireTo(scpProtocol, "SCPPort")
                                                                    .WireTo(arbitrator, "arbitrator")
                                                                    , "tableDataFlowSource")
                                                            .WireTo(csvFileReaderWriter, "tableDataFlowDestination")
                                                            , "fileSelected")
                                                    )
                                            )
                                    )
                            )
                    .WireTo(new Horizontal()
            {
                InstanceName = "mainPanel", Ratios = new int[] { 1, 3 }
            }
                            .WireTo(sessionListGrid
                                    .WireTo(sessionListScp
                                            .WireTo(scpProtocol, "requestResponseDataFlow")
                                            .WireTo(arbitrator, "arbitrator")
                                            , "dataSource")
                                    .WireTo(sessionListScp, "dataFlowSelectedPrimaryKey")
                                    .WireTo(sessionDataGrid
                                            .WireTo(sessionDataScp
                                                    .WireTo(scpProtocol, "SCPPort")
                                                    .WireTo(arbitrator, "arbitrator")
                                                    , "dataSource")
                                            , "eventRowSelected")
                                    )
                            .WireTo(sessionDataGrid)
                            )
                    .WireTo(new Horizontal()
            {
                InstanceName = "statusbar"
            }
                            .WireTo(new Statusbar()
                                    .WireTo(textConnected)
                                    .WireTo(textSearching)
                                    )
                            )
                    )
            .WireTo(new Timer()
            {
                Delay = 3000
            }
                    .WireTo(new SCPSense()
            {
                InstanceName = "scpSence"
            }
                            .WireTo(arbitrator, "arbitrator")
                            .WireTo(scpProtocol
                                    .WireTo(comPort
                                            .WireTo(scpProtocol, "outputForCharactersReceiveFromTheCOMPort")
                                            .WireTo(simulatedExternalDevice
                                                    .WireTo(comPort, "responseOutput")
                                                    , "virtualComPortTx")
                                            , "scpCommand")
                                    , "requestResponseDataFlow")
                            .WireTo(new DataFlowConnector <bool>()
                                    .WireTo(textConnected)
                                    .WireTo(new Not()
                                            .WireTo(textSearching)
                                            )
                                    .WireTo(new ToEvent <bool>()
                                            .WireTo(sessionListGrid)
                                            )
                                    , "IsDeviceConnected")
                            )
                    , "appStart");
            // -------------------------- END CODE MANUALLY GENERATED FROM DIAGRAM --------------------------------------------------------------



            // See logging.cs for an explantion of why we wire up logging instead of using a programming paradigm layer abstraction for it

            // This logging instance is configured to output to the specified file
            // We will all the logging output ports of all the programming paradigms to it
            var debugLoggerToFile = new LoggerToFile(@"C:\ProgramData\Example_ALA\debugLog.txt")
            {
                InstanceName = "debugLoggerToFile"
            };
            var debugLoggerToWindow = new LoggerToWindow()
            {
                InstanceName = "debugLoggerToWindow"
            };

            // This wires the static diagnostic output port of WireManyPorts abstraction to logging so we get diagnostic output of it wiring up all the other diagnostic outputs
            WireMany.diagnosticOutput += debugLoggerToWindow.WriteLine;
            WireMany.diagnosticOutput += wiringLoggerToFile.WriteLine;

            // this method call will look through all the domain abstractions and wire all their static event diagnosticOutput ports to debugLoggingToWindow
            // doing the equivalent of the lines below without us having to do every one individually
            WireMany.WireManyTo("DomainAbstractions", "diagnosticOutput", debugLoggerToWindow, "WriteLine");
            WireMany.WireManyTo("DomainAbstractions", "diagnosticOutput", debugLoggerToFile, "WriteLine");

            // These manual wirings are how we used to do it - they are now done by WireMany above
            // Do it this way to override anything that you want to go to a special place
            // Arbitrator.diagnosticOutput += (s) => Debug.WriteLine(s);
            // SCPProtocol.diagnosticOutput += (s) => Debug.WriteLine(s);
            // Grid.diagnosticOutput += (s) => Debug.WriteLine(s);
            // CSVFileReaderWriter.diagnosticOutput += (s) => Debug.WriteLine(s);
            // Transfer.diagnosticOutput += (s) => Debug.WriteLine(s);
        }
Ejemplo n.º 36
0
        } // New

        // Function to open the KISS TNC
        private bool Open()
        {
            bool OpenRet = default;

            OpenRet = true;
            string strConfiguration;
            bool   blnInKissStartSequence = false;
            var    strLine      = default(string);
            bool   blnOnAir1200 = false;
            bool   blnOnAir9600 = false;

            strAPSFile = Globals.stcSelectedChannel.TNCConfigurationFile;
            if (File.Exists(strAPSFile) == false)
            {
                Globals.queChannelDisplay.Enqueue("R*** .aps Configuration file not found...");
                OpenRet = false;
            }
            else
            {
                try
                {
                    strConfiguration = File.ReadAllText(strAPSFile);
                    var objStringReader = new StringReader(strConfiguration);
                    do
                    {
                        try
                        {
                            strLine = objStringReader.ReadLine();
                            if (string.IsNullOrEmpty(strLine))
                            {
                                break;
                            }
                            var strCommand = strLine.Split(';');
                            if (!string.IsNullOrEmpty(strCommand[0].Trim()))
                            {
                                var strTokens  = strCommand[0].Trim().Split(' ');
                                var switchExpr = strTokens[0].Trim().ToUpper();
                                switch (switchExpr)
                                {
                                // These key words define the 1200 and  9600 baud segments
                                case "BEGIN1200B":
                                {
                                    blnOnAir1200 = true;
                                    blnOnAir9600 = false;
                                    break;
                                }

                                case "BEGIN9600B":
                                {
                                    blnOnAir9600 = true;
                                    blnOnAir1200 = false;
                                    break;
                                }

                                case "END1200B":
                                {
                                    blnOnAir9600 = false;
                                    blnOnAir1200 = false;
                                    if (Globals.stcSelectedChannel.TNCOnAirBaud == 1200)
                                    {
                                        break;
                                    }
                                    break;
                                }

                                case "END9600B":
                                {
                                    blnOnAir9600 = false;
                                    blnOnAir1200 = false;
                                    if (Globals.stcSelectedChannel.TNCOnAirBaud == 9600)
                                    {
                                        break;
                                    }
                                    break;
                                }
                                }

                                if (blnOnAir1200 & Globals.stcSelectedChannel.TNCOnAirBaud == 1200 | blnOnAir9600 & Globals.stcSelectedChannel.TNCOnAirBaud == 9600)
                                {
                                    var switchExpr1 = strTokens[0].Trim().ToUpper();
                                    switch (switchExpr1)
                                    {
                                    case "KISSSTART":
                                    {
                                        strKissStart           = new string[0];
                                        blnInKissStartSequence = true;
                                        break;
                                    }

                                    case "KISSEND":
                                    {
                                        blnInKissStartSequence = false;
                                        break;
                                    }

                                    case "TXDELAY":
                                    {
                                        intTXDelay = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "PERSISTANCE":
                                    {
                                        intPersistance = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "SLOTTIME":
                                    {
                                        intSlottime = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "FULLDUPLEX":
                                    {
                                        blnFullDuplex = Convert.ToBoolean(strTokens[1]);
                                        break;
                                    }

                                    case "MAXFRAMESIZE":
                                    {
                                        intMaxFrameSize = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "MAXFRAMES":
                                    {
                                        intMaxFrames = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "ACKTIMER":
                                    {
                                        intACKTimer = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "MAXRETRY":
                                    {
                                        intMaxRetry = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "POLLTHRESH":
                                    {
                                        intPollThresh = Convert.ToInt32(strTokens[1]);
                                        break;
                                    }

                                    case "KISSEXIT":
                                    {
                                        blnExitKiss = Convert.ToBoolean(strTokens[1]);
                                        break;
                                    }

                                    case "ESCAPE":
                                    {
                                        strEscapeChars = strTokens[1].Trim();
                                        break;
                                    }

                                    default:
                                    {
                                        if (blnInKissStartSequence)
                                        {
                                            Array.Resize(ref strKissStart, strKissStart.Length + 1);
                                            strKissStart[strKissStart.Length - 1] = strCommand[0].Trim().ToUpper();
                                        }

                                        break;
                                    }
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Log.Error("[ModemNativeKiss.Open] " + strLine + Globals.CR + ex.Message);
                        }
                    }while (true);
                }
                catch (Exception ex)
                {
                    Log.Error("[ModemNativeKiss.Open] " + ex.Message);
                }
            }

            if (objSerial != null)
            {
                objSerial.Close();
                Thread.Sleep(Globals.intComCloseTime);
                objSerial.Dispose();
                objSerial = null;
            }
            // Open the serial port...
            try
            {
                objSerial = new SerialPort(
                    Globals.stcSelectedChannel.TNCSerialPort,
                    Convert.ToInt32(Globals.stcSelectedChannel.TNCBaudRate),
                    Parity.None,
                    8,
                    StopBits.One);
                objSerial.Handshake = Handshake.None;
                objSerial.RtsEnable = true;
                try
                {
                    objSerial.Open();
                }
                catch
                {
                    Globals.queChannelDisplay.Enqueue("R*** Failed to open serial port on " + Globals.stcSelectedChannel.TNCSerialPort + ". Port may be in use by another application.");
                    Log.Error("[ClinetNativeKISS.Open] Failed to open serial port on " + Globals.stcSelectedChannel.TNCSerialPort);
                    return(false);
                }

                if (objSerial.IsOpen == false)
                {
                    Globals.queChannelDisplay.Enqueue("R*** Failed to open serial port on " + Globals.stcSelectedChannel.TNCSerialPort + ". Port may be in use by another application.");
                    Log.Error("[ModemNativeKiss.Open] Failed to open serial port on " + Globals.stcSelectedChannel.TNCSerialPort);
                    return(false);
                }
                else
                {
                    Globals.queChannelDisplay.Enqueue("G*** Serial port " + Globals.stcSelectedChannel.TNCSerialPort + " opened");
                }
            }
            catch (Exception ex)
            {
                Log.Error("[ModemNativeKiss.Open] " + ex.Message);
                return(false);
            }

            OpenRet = InitializeKISSTnc(); // initialize the TNC to KISS mode

            if (OpenRet == false)
            {
                Log.Error("[ClientNativeKiss.Open] Failed to Initialize KISS TNC");
                enmState = LinkStates.LinkFailed;

                if (objSerial != null)
                {
                    objSerial.Close();
                    Thread.Sleep(Globals.intComCloseTime);
                    objSerial.Dispose();
                    objSerial = null;
                }

                return(false);
            }
            else
            {
                // All OK so set up Peter's Native KISS DLL
                try
                {
                    objKissComPort = new COMPort(objSerial); // Globals.stcSelectedChannel.TNCSerialPort, Convert.ToInt32(Globals.stcSelectedChannel.TNCBaudRate));
                    // set up the optional escape characters
                    if (!string.IsNullOrEmpty(strEscapeChars))
                    {
                        objKissComPort.escapedCharList = strEscapeChars;                     // Escape characters from .aps file
                    }
                    objKissChannel    = objKissComPort.CreateChannel(0);                     // Create TNC Channel 0
                    objKissDLProvider = objKissChannel.CreateProvider(Globals.SiteCallsign); // Create a DLProvider for the Site Call sign
                                                                                             // set up the KISS parameters from default values or as updated from the .aps file
                    objConParam               = new Connection.ConnectionParameterBuf();
                    objConParam.ackTimer      = 1000 * intACKTimer;                          // convert from Sec to ms.
                    objConParam.maxRetry      = intMaxRetry;
                    objConParam.maxIFrame     = intMaxFrameSize;
                    objConParam.maxWindowSize = intMaxFrames;
                    objConParam.pollThresh    = 1000 * intPollThresh; // convert from Sec to ms
                    objKissChannel.SetPersistence(intPersistance);
                    objKissChannel.SetSlotTime(intSlottime);
                    objKissChannel.SetTXDelay(intTXDelay);
                    objKissChannel.SetTXFullDuplex(Convert.ToInt32(blnFullDuplex));
                    enmState = LinkStates.Initialized;
                }
                catch (Exception ex)
                {
                    Log.Error("[ClientNativeKiss.Open] Call to DLL Error: " + ex.ToString());
                    return(false);
                }
            }
            // Extended logging added for debugging
            if (File.Exists(Globals.SiteRootDirectory + @"Log\NativeKISSax25PktLog.log"))
            {
                File.Delete(Globals.SiteRootDirectory + @"Log\NativeKISSax25PktLog.log");
            }

            Support.pktLogFile = Globals.SiteRootDirectory + @"Log\NativeKISSax25PktLog.log";
            objKissChannel.packetMonitorEnable = TNCChannel.PacketMonitorType.LogFile;
            return(OpenRet);
        } // Open