public void BaudRateToString()
        {
            BaudRate br = BaudRate.BR_57600;

            Assert.AreEqual("57600", br.ToString(true));
            Assert.AreEqual("BR_57600", br.ToString(false));
        }
Beispiel #2
0
        public string ToString(string format, IFormatProvider formatProvider)
        {
            if (string.IsNullOrEmpty(format))
            {
                format = "G";
            }

            if (formatProvider == null)
            {
                formatProvider = CultureInfo.CurrentCulture;
            }

            switch (format.ToUpperInvariant())
            {
            case "G":
                return(ToString());

            case "LOG":
                return(string.Format(Resources.SerialPortSettingsString,
                                     BaudRate.ToString(true), Parity.ToString(), StopBits.ToString(), headerTX, HeaderRX));

            default:
                throw new FormatException(string.Format(Resources.FormatNotSupported, format));
            }
        }
 private void ConnectDialog_Load(object sender, EventArgs e)
 {
     _port.Items.Clear();
     _port.Items.AddRange(SerialPort.GetPortNames().OrderBy(s => s).ToArray());
     _port.SelectedItem = PortName;
     _baudRate.Text     = BaudRate.ToString();
 }
Beispiel #4
0
 protected override void GetXml(XmlDocument document, XmlNode rootElement)
 {
     base.GetXml(document, rootElement);
     AddElement(document, rootElement, "PortName", PortName);
     AddElement(document, rootElement, "BaudRate", BaudRate.ToString(CultureInfo.InvariantCulture));
     AddElement(document, rootElement, "DataBits", DataBits.ToString(CultureInfo.InvariantCulture));
     AddElement(document, rootElement, "Parity", Parity.ToString());
     AddElement(document, rootElement, "StopBits", StopBits.ToString());
 }
 public Dictionary <string, string> Serialize()
 {
     return(new Dictionary <string, string>
     {
         { "PortName", PortName },
         { "LedNumber", LedNumber.ToString(CultureInfo.InvariantCulture) },
         { "BaudRate", BaudRate.ToString(CultureInfo.InvariantCulture) }
     });
 }
Beispiel #6
0
        /// <summary>
        /// Sets the baud rate.
        /// </summary>
        public void SetBaudRate(BaudRate BaudRate)
        {
            byte H, L;

            switch (BaudRate)
            {
            case BaudRate.Baud___9600:
                H = 0xae;
                L = 0xc8;
                break;

            case BaudRate.Baud__19200:
                H = 0x56;
                L = 0xe4;
                break;

            case BaudRate.Baud__38400:
                H = 0x2a;
                L = 0xf2;
                break;

            case BaudRate.Baud__57600:
                H = 0x1c;
                L = 0x4c;
                break;

            case BaudRate.Baud_115200:
                H = 0x0d;
                L = 0xa6;
                break;

            default:
                throw new ArgumentException("Invalid baud rate", "BaudRate");
            }

            this.EmptyBuffers();

            if (this.uart.OutputToConsole)
            {
                Console.Out.WriteLine("SetBaudRate(" + BaudRate.ToString() + ")");
            }

            this.uart.Transmit(0x56, 0x00, 0x24, 0x03, 0x01, H, L);
            this.uart.ReceiveAndVerify(0x76, 0x00, 0x24, 0x00, 0x00);

            Uart Uart2;

            Uart2                 = new Uart((int)BaudRate, Parity.None, 8, StopBits.None);
            Uart2.NewLine         = this.uart.NewLine;
            Uart2.ReadTimeout     = this.uart.ReadTimeout;
            Uart2.OutputToConsole = this.uart.OutputToConsole;

            this.uart.Dispose();
            this.uart = Uart2;
        }
Beispiel #7
0
 /// <summary>
 /// Установить параметры канала связи в соответствии с настройками
 /// </summary>
 public void SetCommCnlParams(SortedList <string, string> commCnlParams)
 {
     commCnlParams["PortName"]  = PortName;
     commCnlParams["BaudRate"]  = BaudRate.ToString();
     commCnlParams["Parity"]    = Parity.ToString();
     commCnlParams["DataBits"]  = DataBits.ToString();
     commCnlParams["StopBits"]  = StopBits.ToString();
     commCnlParams["DtrEnable"] = DtrEnable.ToString();
     commCnlParams["RtsEnable"] = RtsEnable.ToString();
     commCnlParams["Behavior"]  = Behavior.ToString();
 }
 /// <summary>
 /// Writes our settings to an XML writer
 /// </summary>
 /// <param name="writer">an XML writer</param>
 public void WriteXml(System.Xml.XmlWriter writer)
 {
     writer.WriteAttributeString("BaudRate", BaudRate.ToString());
     writer.WriteAttributeString("ControllerType", ControllerType.ToString());
     writer.WriteAttributeString("SamplingChannels", SamplingChannels.ToString());
     writer.WriteAttributeString("SamplingCompression", SamplingCompression.ToString());
     writer.WriteAttributeString("SamplingMode", SamplingMode.ToString());
     writer.WriteAttributeString("SamplingRate", SamplingRate.ToString());
     writer.WriteAttributeString("SamplingTime", SamplingTime.ToString());
     writer.WriteAttributeString("SerialPortName", SerialPortName);
 }
        public override string ToString()
        {
            List <string> paraList = new List <string>();

            paraList.Add(PortName.ToString());
            paraList.Add(BaudRate.ToString());
            paraList.Add(DataBits.ToString());
            paraList.Add(StopBits.ToString());
            paraList.Add(Parity.ToString());
            return(String.Format("{0}://{1}", Prefix, String.Join(SpitChar, paraList)));
        }
Beispiel #10
0
 /// <summary>
 /// Adds the options to the list.
 /// </summary>
 public void AddToOptionList(OptionList options)
 {
     options.Clear();
     options["PortName"]  = PortName;
     options["BaudRate"]  = BaudRate.ToString();
     options["DataBits"]  = DataBits.ToString();
     options["Parity"]    = Parity.ToString();
     options["StopBits"]  = StopBits.ToString();
     options["DtrEnable"] = DtrEnable.ToLowerString();
     options["RtsEnable"] = RtsEnable.ToLowerString();
     options["Behavior"]  = Behavior.ToString();
 }
 public void Save(XmlTextWriter xml)
 {
     xml.WriteStartElement("interface");
     xml.WriteAttributeString("id", Id);
     xml.WriteAttributeString("portName", PortName);
     xml.WriteAttributeString("baudRate", BaudRate.ToString());
     xml.WriteAttributeString("dataBits", DataBits.ToString());
     xml.WriteAttributeString("handShake", HandShake.ToString());
     xml.WriteAttributeString("parity", Parity.ToString());
     xml.WriteAttributeString("stopBits", StopBits.ToString());
     xml.WriteEndElement();
 }
 public void Save()
 {
     Basic.SetRegistryKey("UseScale", UseScale.ToString());
     Basic.SetRegistryKey("Commend", Commend.ToString());
     Basic.SetRegistryKey("PortName", PortName.ToString());
     Basic.SetRegistryKey("BaudRate", BaudRate.ToString());
     Basic.SetRegistryKey("Parity", Parity.ToString());
     Basic.SetRegistryKey("DataBit", DataBit.ToString());
     Basic.SetRegistryKey("StopBit", StopBit.ToString());
     Basic.SetRegistryKey("ScaleType", ScaleType.ToString());
     Basic.SetRegistryKey("DefaultWeight", DefaultWeight.ToString());
     Basic.SetRegistryKey("BarcodeSize", BarcodeSize.ToString());
 }
Beispiel #13
0
        public override string ToString()
        {
            var info = new StringBuilder();

            info.Append("Uuid: ").AppendLine(Uuid);
            info.Append("Description: ").AppendLine(Description);
            info.Append("COM port: ").AppendLine(ComPort);
            info.Append("Baud rate: ").AppendLine(BaudRate.ToString());
            info.Append("Connect timeout (Sec): ").AppendLine(ConnectionTimeoutInSeconds.ToString());
            info.Append("Device type: ").AppendLine(DeviceType);
            info.Append("Licence: ").AppendLine(Licence);

            return(info.ToString());
        }
Beispiel #14
0
        public FrmMain()
        {
            InitializeComponent();
            BaudRate        = 9600;
            PortName        = "COM7";
            tbBaudRate.Text = BaudRate.ToString(CultureInfo.InvariantCulture);
            tbPortName.Text = PortName;

            CheckConnection();
            _curtain.OnPositionChanged += CurtainPositionChangedHandler;

            var mrl = new List <MovementRequest>();

            using (var file = new StreamReader(Environment.CurrentDirectory + "\\" + "MovementRequests.txt"))
            {
                string line;
                while ((line = file.ReadLine()) != null)
                {
                    string[] linePrams = line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);
                    if (linePrams.Length != 3)
                    {
                        continue;
                    }
                    var mr = new MovementRequest
                    {
                        Position = Convert.ToInt32(linePrams[2]),
                        Day      = (DayOfWeek)Convert.ToInt32(linePrams[0]),
                        Time     = TimeSpan.Parse(linePrams[1])
                    };
                    mrl.Add(mr);
                    //MessageBox.Show(line);
                }

                file.Close();
            }

            if (mrl.Count > 0)
            {
                _curtain.StartPending(mrl);
            }
        }
Beispiel #15
0
        public MainWindow()
        {
            InitializeComponent();
            timer.Interval = TimeSpan.FromSeconds(1);
            timer.Tick    += timer_Tick;
            _Port          = Properties.Settings.Default.Port;
            BaudRate       = Properties.Settings.Default.BaudRate;
            Delay          = Properties.Settings.Default.Delay;
            _Sending       = Properties.Settings.Default.SendAfterStart;

            CheckBoxSendAfterStart.IsChecked = Properties.Settings.Default.SendAfterStart;
            TextBoxDelay.Text = Delay.ToString();
            TextBoxRate.Text  = BaudRate.ToString();
            TextBoxCom.Text   = _Port.ToString();
            Closing          += OnClosing;

            if (_Sending == true)
            {
                timer.Start();
            }
        }
        /**
         * This function read every setting from memory and restore it in the UI
         */
        private void readSettingsFromMemory()
        {
            if (Properties.Settings.Default.BaudRate != -1)
            {
                BaudRate = Properties.Settings.Default.BaudRate;
                baudRateDropdown.SelectedItem = BaudRate.ToString();
            }

            if (Properties.Settings.Default.Parity != -1)
            {
                var parityInt = Properties.Settings.Default.Parity;
                Parity = (Parity)parityInt;
                parityDropdown.SelectedIndex = parityInt;
            }

            if (Properties.Settings.Default.DataBits != -1)
            {
                DataBits = Properties.Settings.Default.DataBits;
                databitsDropdown.SelectedItem = DataBits.ToString();
            }

            if (Properties.Settings.Default.StopBits != -1)
            {
                var stopBitsInt = Properties.Settings.Default.StopBits;
                StopBits = (StopBits)stopBitsInt;
                stopbitsDropdown.SelectedIndex = stopBitsInt;
            }

            if (Properties.Settings.Default.FlowControl != -1)
            {
                var flowControlInt = Properties.Settings.Default.FlowControl;
                FlowControl = (Handshake)flowControlInt;
                flowcontrolDropdown.SelectedIndex = flowControlInt;
            }

            ReplaceNewLine = Properties.Settings.Default.ReplaceNewLine;
        }
Beispiel #17
0
        public static void Setup(
                                    Cpu.Pin chipSelect,
                                    SPI.SPI_module spiModule,
                                    ClockRate clockRate,
                                    BaudRate baudRateIndex)
        {
            #region SPI Init
            try
            {
                // Initialise SDI
                SPI.Configuration spiConfig = new SPI.Configuration(
                    chipSelect, // Chip select pin
                    false,      // Active state
                    10,         // Setup time (ms)
                    10,         // Hold time (ms)
                    false,      // Clock idle (low)
                    true,       // Edge (rising)
                    2048,       // Clock rate (KHz)
                    spiModule); // SPI module

                spiInterface = new SPI(spiConfig);
            }
            catch (Exception e)
            {
                throw new Exception("SPI Init Error (" + e.Message + ")", e);
            }
            #endregion

            #region SPI to WiFly UART Init
            // Initialise the WiFly shield SPI<->UART chip

            // Convert the enum to a baud rate
            int baudRate = 1200;
            int depth = Convert.ToInt32(baudRateIndex.ToString()) - (int)BaudRate.BaudRate_1200;
            for (int i = 0; i < depth; i++)
            {
                baudRate += baudRate;
            }

            // Make DLL and DLH accessible
            if (clockRate == ClockRate.Xtal_12Mhz)
            {
                // I doesn't look like a 12MHz clock can do 921600bps
                if (baudRate == 921600)
                    baudRate = 460800;

                int divisor = 12288000 / (baudRate * 16);
                WriteRegister(Register.LCR, 0x80);  // 0x80 to program baudrate
                WriteRegister(Register.DLH, (byte)((divisor & 0x0000ff00) >> 8));
                WriteRegister(Register.DLL, (byte)((divisor & 0x000000ff) >> 0));
            }
            else
            {
                int divisor = 14745600 / (baudRate * 16);
                WriteRegister(Register.LCR, 0x80);  // 0x80 to program baudrate
                WriteRegister(Register.DLH, (byte)((divisor & 0x0000ff00) >> 8));
                WriteRegister(Register.DLL, (byte)((divisor & 0x000000ff) >> 0));
            }

            // Make EFR accessible
            WriteRegister(Register.LCR, 0xBF);  // access EFR register

            // Enable CTS, RTS, and Enhanced functions (IER[7:4], FCR[5:4], and MCR[7:5])
            WriteRegister(Register.EFR, (1 << 7) | (1 << 6) | (1 << 4));

            // Finally setup LCR
            WriteRegister(Register.LCR, 0x03);  // no parity, 1 stop bit, 8 data bit
            WriteRegister(Register.FCR, 0x06);  // reset TX and RX FIFO
            WriteRegister(Register.FCR, 0x01);  // enable FIFO mode

            // Perform read/write test of scratchpad register to check if UART is working
            WriteRegister(Register.SPR, 0x55);
            byte data = ReadRegister(Register.SPR);
            if (data != 0x55)
                throw new IOException("Failed to init SPI<->UART chip");

            #endregion

            // Enter command mode
            try
            {
                EnterCommandMode();
            }
            catch (Exception e)
            {
                throw new IOException(e.ToString());
            }

            // Turn off WiFi auto-joining
            SendCommand("set wlan join 0");
            WaitForResponse("AOK");

            SendCommand("save");
            WaitForResponse("Storing in config");

            // "reboot" to a known state
            Debug.Print("Rebooting WiFly-GSX");
            SendCommand("reboot");
            WaitForResponse("*Reboot*");
            WaitForResponse("*READY*");

            // Back to command mode
            try
            {
                EnterCommandMode();
            }
            catch (Exception e)
            {
                throw new IOException(e.ToString());
            }

            FlushRX();

            // Grab the version
            SendCommand("ver");
            WaitForResponse("ver");
            string version = "";
            while ((version = ReadResponse()) == "")
                ;
            string[] tokens = version.Split(' ');
            string[] split = tokens[2].Split('.');

            firmwareVersion = new Version(Convert.ToInt32(split[0]), Convert.ToInt32(split[1].TrimEnd(',')));
            Debug.Print("WiFly firmware version: " + firmwareVersion.Major.ToString() + "." + firmwareVersion.Minor.ToString());

            // Exit command mode
            SendCommand("exit");
            WaitForResponse("EXIT");
        }
Beispiel #18
0
        /// <summary>
        /// 取得消费资料
        /// </summary>
        /// <param name="p_intDeviceNo"></param>
        /// <returns></returns>
        public override List <PaymentInfo> GetPaymentInfo(int p_intDeviceNo)
        {
            try
            {
                //取得消费记录数

                int l_intRecordNum = GetPaymentNum(p_intDeviceNo);

                //Thread.Sleep(3000);

                //如果未能连接到机械

                if (l_intRecordNum == 0)
                {
                    string data = JocatDevice.GetPaymentInfo(ComPort, BaudRate, p_intDeviceNo, 0);
                    return(new List <PaymentInfo>());
                }
                if (l_intRecordNum == -1)
                {
                    return(null);
                }

                List <PaymentInfo> l_lisReturn = new List <PaymentInfo>();

                string l_strData = "";

                for (int i = 0; i < l_intRecordNum; i = i + m_intPaymentDataNum)
                {
                    //l_strData = JocatDevice.GetPaymentInfo(ComPort, BaudRate, p_intDeviceNo, i);
                    l_strData = JocatDevice.GetPaymentInfo(int.Parse(ComPort.ToString()), int.Parse(BaudRate.ToString()), int.Parse(p_intDeviceNo.ToString()), i);

                    if (l_strData == "85" || l_strData == "86")
                    {
                        i = i - m_intPaymentDataNum;
                        continue;
                    }
                    if (l_strData.Length % 52 != 0)
                    {
                        i = i - m_intPaymentDataNum;
                        continue;
                    }

                    int    l_intSeed        = 0;
                    string l_strPaymentInfo = "";

                    //此处有可能遇到l_strData的值为85的情况

                    bool signSuccess = true;
                    List <PaymentInfo> l_tmpPaymentInfos = new List <PaymentInfo>();
                    while (l_intSeed < l_strData.Length)
                    {
                        l_strPaymentInfo = l_strData.Substring(l_intSeed, 52);
                        try
                        {
                            l_tmpPaymentInfos.Add(EncodePaymentInfo(l_strPaymentInfo));
                        }
                        catch (Exception Ex)
                        {
                            signSuccess = false;
                            break;
                        }

                        l_intSeed = l_intSeed + 52;
                    }

                    if (signSuccess)
                    {
                        l_lisReturn.AddRange(l_tmpPaymentInfos);
                    }
                    else
                    {
                        //捕抓机台返回的错误数据,使循环返回对上一次序列重新取数。

                        i = i - m_intPaymentDataNum;
                    }

                    if ((i + m_intPaymentDataNum) > l_intRecordNum)
                    {
                        Thread.Sleep(3000);
                        break;
                    }

                    Thread.Sleep(3000);
                }

                return(l_lisReturn);
            }
            catch (Exception)
            {
                throw;
            }
        }
Beispiel #19
0
 internal static string ToString(this BaudRate baudRate, bool asInt32)
 {
     return((asInt32) ? (baudRate.ToInt32()).ToString() : baudRate.ToString());
 }
        public void SaveSettingsToFile(string FileName)
        {
            try
            {
                XmlTextWriter textWritter = new XmlTextWriter(FileName, Encoding.UTF8);
                textWritter.WriteStartDocument();
                textWritter.WriteStartElement("Setup");
                textWritter.WriteEndElement();
                textWritter.Close();
            }
            catch
            {
                throw new Exception("Error create file!");
            }

            XmlDocument document = new XmlDocument();

            try
            {
                document.Load(FileName);
            }
            catch
            {
                throw new Exception("Error create file!");
            }

            XmlNode element = document.CreateElement("ComSettings");

            document.DocumentElement.AppendChild(element);                 // указываем родителя

            XmlAttribute attribute = document.CreateAttribute("PortName"); // создаём атрибут

            attribute.Value = PortName;
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("Parity");    // создаём атрибут
            attribute.Value = Parity.ToString();
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("BaudRate");  // создаём атрибут
            attribute.Value = BaudRate.ToString();
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("StopBits");  // создаём атрибут
            attribute.Value = StopBits.ToString();
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("SlaveAddr"); // создаём атрибут
            attribute.Value = SlaveAddr.ToString();
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("IPAddr");    // создаём атрибут
            attribute.Value = IpAddress;
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("IPPortNum"); // создаём атрибут
            attribute.Value = portNum.ToString();
            element.Attributes.Append(attribute);                    // добавляем атрибут

            attribute       = document.CreateAttribute("PortMode");  // создаём атрибут
            attribute.Value = serialPortMode.ToString();
            element.Attributes.Append(attribute);                    // добавляем атрибут

            try
            {
                document.Save(FileName);
            }
            catch
            {
                throw new Exception("Error create file!");
            }
        }
Beispiel #21
0
 public override void Save()
 {
     UpdateConfig(ComPort, "ComPort");
     UpdateConfig(BaudRate.ToString(), "BaudRate");
 }
 ///<summary>串口控件</summary>
 public SerialPortControl()
 {
     BaudRateString = BaudRate.ToString();
 }
Beispiel #23
0
        static void Main(string[] args)
        {
            Console.WriteLine("#######################################################\n");
            Console.WriteLine(@"
██████   ██████  ██████  ████████ ██ ████████ 
██   ██ ██    ██ ██   ██    ██    ██    ██    
██████  ██    ██ ██████     ██    ██    ██    
██      ██    ██ ██   ██    ██    ██    ██    
██       ██████  ██   ██    ██    ██    ██    
                                                                                         
");
            Console.WriteLine("[+]Coded By         :Ali Cem Sönmez\n[+]Github           :github.com/snmzcm" + "\n[+]Contact          :[email protected]");
            Console.WriteLine("#######################################################\n");
            string[] portNames  = SerialPort.GetPortNames();
            string   portChoose = "Kullanmak istediğiniz portu seçiniz";
            string   line       = "__________________________________";

            Console.WriteLine(portChoose);
            Console.WriteLine(line);
            //liste index numarası ile port isimlerini yazdır
            foreach (string port in portNames)
            {
                if (port == null)
                {
                    Console.WriteLine("Aktif port girişi algılanamadı");
                }
                else
                {
                    Console.WriteLine(port);
                }
            }
            Console.WriteLine(line);
            string comNumber = Console.ReadLine();

            Console.WriteLine(line);
            Console.WriteLine("Bir Baud Değeri Seçiniz:\n1. 300\n2. 1200\n3. 2400\n4. 4800\n5. 9600\n6. 19200\n7. 38400\n8. 57600\n9. 74880\n10. 115200\n11. 230400\n12. 250000\n13. 500000\n14. 1000000\n15. 2000000");
            Console.WriteLine(line);
            string Baud = Console.ReadLine();
            int    BaudRate;

            switch (Baud)
            {
            case "1":
                BaudRate = 300;
                break;

            case "2":
                BaudRate = 1200;
                break;

            case "3":
                BaudRate = 2400;
                break;

            case "4":
                BaudRate = 4800;
                break;

            case "5":
                BaudRate = 9600;
                break;

            case "6":
                BaudRate = 19200;
                break;

            case "7":
                BaudRate = 38400;
                break;

            case "8":
                BaudRate = 57600;
                break;

            case "9":
                BaudRate = 74880;
                break;

            case "10":
                BaudRate = 115200;
                break;

            case "11":
                BaudRate = 230400;
                break;

            case "12":
                BaudRate = 250000;
                break;

            case "13":
                BaudRate = 500000;
                break;

            case "14":
                BaudRate = 1000000;
                break;

            case "15":
                BaudRate = 2000000;
                break;

            default:
                BaudRate = 9600;
                break;
            }
            SerialPort seriPort = new SerialPort(comNumber, BaudRate, Parity.None, 8, StopBits.One);


            try
            {
                if (seriPort.IsOpen == false)
                {
                    seriPort.Open();
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("{0} Baud ile Bağlantı Başarılı", BaudRate.ToString());
                    Console.ForegroundColor = ConsoleColor.White;
                    Console.WriteLine(line);
                }
            }
            catch (Exception hata1)
            {
                Console.WriteLine("Bir hata gerçekleşti: {0}", hata1.Message);
            }


            while (true)
            {
                string message = seriPort.ReadLine().ToString();
                Console.WriteLine("=> Port Yanıtı: " + message); Console.WriteLine(line);
                string commands = Console.ReadLine();
                seriPort.Write(commands);
                Console.SetCursorPosition(Console.CursorLeft, Console.CursorTop - 1);
                Console.WriteLine(commands);
                Console.WriteLine(line);
            }
        }
        } // end _DecryptSecureString()

        private string _BuildRemoteParams()
        {
            var sb = new StringBuilder(224);

            if (0 == Util.Strcmp_OI(c_NamedPipeServerParamSet, this.ParameterSetName))
            {
                sb.Append("npipe:server=")
                .Append(NamedPipeServer)
                .Append(",pipe=")
                .Append(PipeName);
            }
            else if (0 == Util.Strcmp_OI(c_TcpServerParamSet, this.ParameterSetName))
            {
                sb.Append("tcp:server=")
                .Append(TcpServer)
                .Append(",port=")
                .Append(Port.ToString(CultureInfo.InvariantCulture));

                if (IpVersion6)
                {
                    sb.Append(",ipversion=6");
                }
            }
            else if (0 == Util.Strcmp_OI(c_ReverseTcpServerParamSet, this.ParameterSetName))
            {
                sb.Append("tcp:clicon=")
                .Append(ReverseTcpServer)
                .Append(",port=")
                .Append(Port.ToString(CultureInfo.InvariantCulture));

                if (IpVersion6)
                {
                    sb.Append(",ipversion=6");
                }
            }
            else if (0 == Util.Strcmp_OI(c_ComPortServerParamSet, this.ParameterSetName))
            {
                sb.Append("com:port=")
                .Append(Port.ToString(CultureInfo.InvariantCulture))
                .Append(",baud=")
                .Append(BaudRate.ToString(CultureInfo.InvariantCulture))
                .Append(Channel.ToString(CultureInfo.InvariantCulture));
            }
            else if (0 == Util.Strcmp_OI(c_SslPipeServerParamSet, this.ParameterSetName))
            {
                sb.Append("spipe:proto=")
                .Append(Protocol)
                .Append(",server=")
                .Append(SslPipeServer)
                .Append(",pipe=")
                .Append(PipeName);

                if (!String.IsNullOrEmpty(CertUser))
                {
                    sb.Append(",certuser="******"ssl:proto=")
                .Append(Protocol)
                .Append(",server=")
                .Append(SslTcpServer)
                .Append(",port=")
                .Append(Port.ToString(CultureInfo.InvariantCulture));

                if (!String.IsNullOrEmpty(CertUser))
                {
                    sb.Append(",certuser="******"ssl:proto=")
                .Append(Protocol)
                .Append(",clicon=")
                .Append(SslReverseTcpServer)
                .Append(",port=")
                .Append(Port.ToString(CultureInfo.InvariantCulture));

                if (!String.IsNullOrEmpty(CertUser))
                {
                    sb.Append(",certuser="******",password=").Append(_DecryptSecureString(Password));
            }

            return(sb.ToString());
        } // end _BuildRemoteParams()
Beispiel #25
0
 public Rs485Port(string portName, BaudRate baudRate, byte[] addresses)
     : this("", addresses)
 {
     connStr = portName + "," + baudRate.ToString().Substring(1);
 }
Beispiel #26
0
        /// <summary>Stores advanced settings to <see cref="ConfigurationManager"/></summary>
        public static void Store()
        {
            ConfigurationManager.AppSettings["COMPort"]          = ComPort;
            ConfigurationManager.AppSettings["BaudRate"]         = BaudRate.ToString();
            ConfigurationManager.AppSettings["UseWindowsDriver"] = UseWindowsDriver ? "true" : "false";
            ConfigurationManager.AppSettings["PollingInterval"]  = PollingInterval.ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["LogToTextBox"]     = LogToTextBox ? "true" : "false";
            ConfigurationManager.AppSettings["LogToFile"]        = LogToLogFile ? "true" : "false";
            switch (LogFormat)
            {
            case LogFormat.KML:
                ConfigurationManager.AppSettings["LogFormat"] = "KML";
                break;

            case LogFormat.CSV:
                ConfigurationManager.AppSettings["LogFormat"] = "CSV";
                break;

            default:
                ConfigurationManager.AppSettings["LogFormat"] = "GPX";
                break;
            }

            switch (TrackType)
            {
            case TrackType.Track: ConfigurationManager.AppSettings["TrackType"] = "Track"; break;

            default: ConfigurationManager.AppSettings["TrackType"] = "Points"; break;
            }
            ConfigurationManager.AppSettings["LogAltitude"]     = LogAltitude ? "true" : "false";
            ConfigurationManager.AppSettings["LogFileLocation"] = LogFileLocation;

            ConfigurationManager.AppSettings["UseGPSTime"]          = UseGpsTime ? "true" : "false";
            ConfigurationManager.AppSettings["StatusBar"]           = StatusBar ? "true" : "false";
            ConfigurationManager.AppSettings["MaxLogLength"]        = MaxLogLength.ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["AltitudeCorrection"]  = AltitudeCorrection.ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["StartImmediatelly"]   = StartImmediatelly ? "true" : "false";
            ConfigurationManager.AppSettings["KMLNameFormat"]       = KmlNameFormat;
            ConfigurationManager.AppSettings["KMLDescFormat"]       = KmlDescFormat;
            ConfigurationManager.AppSettings["KMLLineColor"]        = KmlLineColor.ToArgb().ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["MinimalDistance"]     = MinimalDistance.ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["TextLogFormat"]       = TextLogFormat;
            ConfigurationManager.AppSettings["InvalidPositionsMax"] = InvalidPositionsMax.ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["NMEALog"]             = NmeaLog ? "true" : "false";
            ConfigurationManager.AppSettings["SeaLevelAltitude"]    = SeaLevelAltitude ? "true" : "false";
            ConfigurationManager.AppSettings["InfoPane"]            = InfoPane ? "true" : "false";
            ConfigurationManager.AppSettings["BeepTimer"]           = BeepTimer.ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["KeepAwake"]           = KeepAwakeList == null ? "" : string.Join(" ", KeepAwakeList);
            ConfigurationManager.AppSettings["SpeedUnit"]           = SpeedUnit.ToString();
            ConfigurationManager.AppSettings["DistanceUnit"]        = DistanceUnit.ToString();
            ConfigurationManager.AppSettings["ElevationUnit"]       = ElevationUnit.ToString();
            ConfigurationManager.AppSettings["CSVSeparator"]        = CsvSeparator.ToString();
            ConfigurationManager.AppSettings["CSVTextQualifier"]    = CsvTextQualifier.ToString();
            ConfigurationManager.AppSettings["CSVNewLine"]          = CsvNewLine;
            ConfigurationManager.AppSettings["CSVQualifierUsage"]   = ((int)CsvQualifierUsage).ToString(System.Globalization.CultureInfo.InvariantCulture);
            ConfigurationManager.AppSettings["CSVHeader"]           = CsvHeader;
            ConfigurationManager.AppSettings["CSVFields"]           = CsvFields;
            ConfigurationManager.AppSettings["CSVDateFormat"]       = CsvDateFormat;
            ConfigurationManager.AppSettings["CSVUTC"]   = CsvUtc ? "true" : "false";
            ConfigurationManager.AppSettings["Language"] = Language;
            ConfigurationManager.AppSettings["MainFormBottomEmptySpace"] = MainFormBottomEmptySpace.ToString(System.Globalization.CultureInfo.InvariantCulture);
        }
Beispiel #27
0
        /// <summary>
        /// Converts the Baud enum value to an integer.
        /// </summary>
        /// <param name="baud">The baud.</param>
        /// <returns></returns>
        internal static int ToInt(this BaudRate baud)
        {
            var baudString = baud.ToString().ToLowerInvariant().Replace("baud", string.Empty);

            return(int.TryParse(baudString, out var outBaud) ? outBaud : -1);
        }
Beispiel #28
0
 public override string ToString()
 {
     return(String.Format("{0}-{1}-{2}-{3}-{4}", PortName.ToString(), BaudRate.ToString(), DataBits.ToString(), StopBits.ToString(), Parity.ToString()));
 }
Beispiel #29
0
 public Rs232Port(string portName, BaudRate baudRate)
     : this("")
 {
     connStr = portName + "," + baudRate.ToString().Substring(1);
 }
		/// <summary>
		/// Sets the baud rate.
		/// </summary>
		public void SetBaudRate (BaudRate BaudRate)
		{
			byte H, L;

			switch (BaudRate)
			{
				case BaudRate.Baud___9600:
					H = 0xae;
					L = 0xc8;
					break;

				case BaudRate.Baud__19200: 
					H = 0x56;
					L = 0xe4;
					break;

				case BaudRate.Baud__38400: 
					H = 0x2a;
					L = 0xf2;
					break;

				case BaudRate.Baud__57600: 
					H = 0x1c;
					L = 0x4c;
					break;

				case BaudRate.Baud_115200: 
					H = 0x0d;
					L = 0xa6;
					break;

				default:
					throw new ArgumentException ("Invalid baud rate", "BaudRate");
			}

			this.EmptyBuffers ();

			if (this.uart.OutputToConsole)
				Console.Out.WriteLine ("SetBaudRate(" + BaudRate.ToString () + ")");

			this.uart.Transmit (0x56, 0x00, 0x24, 0x03, 0x01, H, L);
			this.uart.ReceiveAndVerify (0x76, 0x00, 0x24, 0x00, 0x00);

			Uart Uart2;

			Uart2 = new Uart ((int)BaudRate, Parity.None, 8, StopBits.None);
			Uart2.NewLine = this.uart.NewLine;
			Uart2.ReadTimeout = this.uart.ReadTimeout;
			Uart2.OutputToConsole = this.uart.OutputToConsole;

			this.uart.Dispose ();
			this.uart = Uart2;
		}
Beispiel #31
0
        private static void InitializeIEC(TraceLevel trace, Media media)
        {
            GXSerial serial = (GXSerial)media.Target;

            serial.BaudRate = 300;
            serial.DataBits = 7;
            serial.Parity   = Parity.Even;
            serial.StopBits = StopBits.One;
            byte Terminator = (byte)0x0A;

            //Some meters need a little break.
            Thread.Sleep(1000);
            //Query device information.
            string data = "/?!\r\n";

            WriteLog(trace, "IEC Sending:" + data);
            if (media.WaitTime == 0)
            {
                media.WaitTime = 5;
            }
            ReceiveParameters <string> p = new ReceiveParameters <string>()
            {
                AllData  = false,
                Eop      = Terminator,
                WaitTime = media.WaitTime * 1000
            };

            lock (media.Target.Synchronous)
            {
                media.Target.Send(data, null);
                if (!media.Target.Receive(p))
                {
                    DiscIEC(media);
                    string str = "Failed to receive reply from the device in given time.";
                    WriteLog(trace, str);
                    media.Target.Send(data, null);
                    if (!media.Target.Receive(p))
                    {
                        throw new Exception(str);
                    }
                }
                //If echo is used.
                if (p.Reply == data)
                {
                    p.Reply = null;
                    if (!media.Target.Receive(p))
                    {
                        data = "Failed to receive reply from the device in given time.";
                        WriteLog(trace, data);
                        throw new Exception(data);
                    }
                }
            }
            WriteLog(trace, "IEC received: " + p.Reply);
            if (p.Reply[0] != '/')
            {
                p.WaitTime = 100;
                media.Target.Receive(p);
                throw new Exception("Invalid responce.");
            }
            string manufactureID = p.Reply.Substring(1, 3);
            char   baudrate      = p.Reply[4];
            int    BaudRate;

            switch (baudrate)
            {
            case '0':
                BaudRate = 300;
                break;

            case '1':
                BaudRate = 600;
                break;

            case '2':
                BaudRate = 1200;
                break;

            case '3':
                BaudRate = 2400;
                break;

            case '4':
                BaudRate = 4800;
                break;

            case '5':
                BaudRate = 9600;
                break;

            case '6':
                BaudRate = 19200;
                break;

            default:
                throw new Exception("Unknown baud rate.");
            }
            if (media.MaximumBaudRate != 0)
            {
                BaudRate = media.MaximumBaudRate;
                baudrate = GetIecBaudRate(BaudRate);
                WriteLog(trace, "Maximum BaudRate is set to : " + BaudRate.ToString());
            }
            WriteLog(trace, "BaudRate is : " + BaudRate.ToString());
            //Send ACK
            //Send Protocol control character
            // "2" HDLC protocol procedure (Mode E)
            byte controlCharacter = (byte)'2';
            //Send Baud rate character
            //Mode control character
            byte ModeControlCharacter = (byte)'2';

            //"2" //(HDLC protocol procedure) (Binary mode)
            //Set mode E.
            byte[] arr = new byte[] { 0x06, controlCharacter, (byte)baudrate, ModeControlCharacter, 13, 10 };
            WriteLog(trace, "Moving to mode E. " + GXCommon.ToHex(arr));
            lock (media.Target.Synchronous)
            {
                p.Reply = null;
                media.Target.Send(arr, null);
                p.WaitTime = 2000;
                //Note! All meters do not echo this.
                media.Target.Receive(p);
                if (p.Reply != null)
                {
                    WriteLog(trace, "Received: " + p.Reply);
                }
                media.Target.Close();
                serial.BaudRate = BaudRate;
                serial.DataBits = 8;
                serial.Parity   = Parity.None;
                serial.StopBits = StopBits.One;
                serial.Open();
                //Some meters need this sleep. Do not remove.
                Thread.Sleep(1000);
            }
        }