private SerialStatusPacket openSerialPortConsole(byte id, int communicationDeviceTimeoutIn1ms, BaudRate baudrate)
        {
            // Initialize return packet 
            SerialStatusPacket returnPacket = new SerialStatusPacket();
            returnPacket.completionCode = CompletionCode.UnspecifiedError;
            Tracer.WriteInfo("Invoked SerialPortConsole.openSerialPortConsole({0})", id);

            try
            {
                // Call device layer below
                SerialConsolePortOpenResponse serialResponse = (SerialConsolePortOpenResponse)this.SendReceive(this.SerialPortConsoleDeviceType,
                    translateSerialPortId(this.PortId), new SerialConsolePortOpenRequest(communicationDeviceTimeoutIn1ms, baudrate),
                    typeof(SerialConsolePortOpenResponse), (byte)PriorityLevel.User);

                // check for completion code 
                if (serialResponse.CompletionCode != 0)
                {
                    Tracer.WriteError("SerialPortConsole.openSerialPortConsole({0}) error in commdev.sendreceive", id);
                    returnPacket.completionCode = (CompletionCode)serialResponse.CompletionCode;
                }
                else
                {
                    returnPacket.completionCode = CompletionCode.Success;
                }
            }
            catch (System.Exception ex)
            {
                returnPacket.completionCode = CompletionCode.UnspecifiedError;
                Tracer.WriteError(ex);
            }

            return returnPacket;
        }
Exemple #2
0
 public static string StrBaudRate(BaudRate baud)
 {
   switch (baud)
   {
     case BaudRate.b1200:
       return "1200";
     case BaudRate.b2400:
       return "2400";
     case BaudRate.b4800:
       return "4800";
     case BaudRate.b9600:
       return "9600";
     case BaudRate.b14400:
       return "14400";
     case BaudRate.b19200:
       return "19200";
     case BaudRate.b28800:
       return "28800";
     case BaudRate.b57600:
       return "57600";
     case BaudRate.b115200:
       return "115200";
     default:
       return "1200";
   }
 }
Exemple #3
0
        /// <summary>
        /// Преобразует значение NGK.CAN.OSIModel.DataLinkLayer.CanPort.BaudRate в значение
        /// F_CAN_BAUDRATE
        /// </summary>
        /// <param name="baudRate">значение типа BaudRate</param>
        /// <returns>значение типа F_CAN_BAUDRATE</returns>
        public static F_CAN_BAUDRATE ConvertToF_CAN_BAUDRATE(BaudRate baudRate)
        {
            F_CAN_BAUDRATE f_baudRate;

            switch (baudRate)
            {
                case BaudRate.BR10:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_10kBaud;
                        break;
                    }
                case BaudRate.BR20:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_20kBaud;
                        break;
                    }
                case BaudRate.BR50:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_50kBaud;
                        break;
                    }
                case BaudRate.BR100:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_100kBaud;
                        break;
                    }
                case BaudRate.BR125:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_125kBaud;
                        break;
                    }
                case BaudRate.BR250:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_250kBaud;
                        break;
                    }
                case BaudRate.BR500:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_500kBaud;
                        break;
                    }
                case BaudRate.BR800:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_800kBaud;
                        break;
                    }
                case BaudRate.BR1000:
                    {
                        f_baudRate = F_CAN_BAUDRATE.CANBR_1MBaud;
                        break;
                    }
                default:
                    {
                        throw new InvalidCastException(
                            "Неудалось преобразовать агрумент типа BaudRate в F_CAN_BAUDRATE. Не найдено соответствие");
                    }
            }
            return f_baudRate;
        }
 public SerialPortConfiguration(string portName, BaudRate baudRate, Parity parity = Parity.None, int dataBits = 8, StopBits stopBits = StopBits.One, bool hardwareFlowControl = false)
 {
     PortName = portName;
     BaudRate = baudRate;
     Parity = parity;
     DataBits = dataBits;
     StopBits = stopBits;
     HardwareFlowControl = hardwareFlowControl;
 }
Exemple #5
0
        public static J2534Err PassThruConnect(int deviceId, ProtocolID protocolId, ConnectFlag flags, BaudRate baudRate, ref int channelId)
        {
            Log.WriteTimestamp("", "PTConnect({0}, {1}, {2}, {3}, {4})", deviceId, protocolId, flags, baudRate, channelId);

            var result = Loader.Lib.PassThruConnect(deviceId, protocolId, flags, baudRate, ref channelId);

            Log.WriteTimestamp("  ", "{0}: {1}", (int)result, result);

            return result;
        }
        public static bool SerialSetup(SerialPort sp, String portName, BaudRate baud) {
            if (portName == null || portName.Length < 4) return false;

            sp.PortName = portName;
            sp.BaudRate = baud.Value;
            sp.Parity = Parity.None;
            sp.StopBits = StopBits.One;
            sp.Handshake = Handshake.None;
            sp.DataBits = 8;
            sp.ReadTimeout = 1000;
            sp.ReadBufferSize = 65536;
            
            sp.Open();
            sp.ReadTimeout = 1000;
            return true;
        }
Exemple #7
0
        /// <summary>
        /// Конструктор для десериализации
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public CanPort(SerializationInfo info, StreamingContext context)
        {
            this._InputBufferMessages = new Queue<Frame>(100);

            // Инициализируем дескриптор устройства
            this._DeviceHandle = new SafeFileHandle(IntPtr.Zero, true);
            this._DeviceHandle.Close();

            this._PortName = info.GetString("PortName");
            this._BitRate = (BaudRate)info.GetValue("BitRate", typeof(BaudRate));
            this._OpMode = (PortMode)info.GetValue("Mode", typeof(PortMode));
            this._ErrorFrameEnable = info.GetBoolean("ErrorFrameEnable");
            this._FrameFormat = (FrameFormat)info.GetValue("FrameFormat", typeof(FrameFormat));
            this._Timeouts = (F_CAN_TIMEOUTS)info.GetValue("Timeouts", typeof(F_CAN_TIMEOUTS));
        }
Exemple #8
0
 public SerialDevice(string portName, BaudRate baudRate)
 {
     this.portName = portName;
     this.baudRate = baudRate;
 }
Exemple #9
0
        /// <summary>
        /// Преобразует значение NGK.CAN.OSIModel.DataLinkLayer.CanPort.BaudRate в значение
        /// F_CAN_BAUDRATE
        /// </summary>
        /// <param name="baudRate">значение типа BaudRate</param>
        /// <returns>значение типа F_CAN_BAUDRATE</returns>
        public static F_CAN_BAUDRATE ConvertToF_CAN_BAUDRATE(BaudRate baudRate)
        {
            F_CAN_BAUDRATE f_baudRate;

            switch (baudRate)
            {
            case BaudRate.BR10:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_10kBaud;
                break;
            }

            case BaudRate.BR20:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_20kBaud;
                break;
            }

            case BaudRate.BR50:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_50kBaud;
                break;
            }

            case BaudRate.BR100:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_100kBaud;
                break;
            }

            case BaudRate.BR125:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_125kBaud;
                break;
            }

            case BaudRate.BR250:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_250kBaud;
                break;
            }

            case BaudRate.BR500:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_500kBaud;
                break;
            }

            case BaudRate.BR800:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_800kBaud;
                break;
            }

            case BaudRate.BR1000:
            {
                f_baudRate = F_CAN_BAUDRATE.CANBR_1MBaud;
                break;
            }

            default:
            {
                throw new InvalidCastException(
                          "Неудалось преобразовать агрумент типа BaudRate в F_CAN_BAUDRATE. Не найдено соответствие");
            }
            }
            return(f_baudRate);
        }
Exemple #10
0
 public J2534Err Connect(int deviceId, ProtocolID protocolId, ConnectFlag flags, BaudRate baudRate, ref int channelId)
 {
     return((J2534Err)m_wrapper.Connect(deviceId, (int)protocolId, (int)flags, (int)baudRate, ref channelId));
 }
Exemple #11
0
 public BaudRateCommand(BaudRate baudRate) : this()
 {
     Parameter = baudRate;
 }
Exemple #12
0
 public PortStream(String port, BaudRate baudRate, Parity parity, DataSize dataSize, StopBits stopBits)
     : this(port, (Int32) baudRate, parity, dataSize, stopBits)
 {
 }
 public MySerialPort(string PortName, BaudRate BaudRate, Parity Parity, DataBits DataBits, StopBits StopBits)
     : base(PortName, (int)BaudRate, Parity, (int)DataBits, StopBits)
 {
 }
Exemple #14
0
 void IGXDLMSBase.Load(GXXmlReader reader)
 {
     CommSpeed = (BaudRate)reader.ReadElementContentAsInt("CommSpeed");
 }
 public MySerialPort(string PortName, BaudRate BaudRate, Parity Parity, DataBits DataBits, StopBits StopBits)
     : base(PortName, (int)BaudRate, Parity, (int)DataBits, StopBits)
 {
 }
        private static IObservable <T> CreateListener <T>(string portName, BaudRate baudRate, Parity parity, int dataBits, StopBits stopBits, Encoding encoding, int bufferSize, Func <RJCPIO.SerialPortStream, T[], Task <int> > readFromPort)
        {
            if (string.IsNullOrEmpty(portName))
            {
                throw new ArgumentNullException("portName");
            }
            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }
            if (bufferSize < 1)
            {
                throw new ArgumentOutOfRangeException("bufferSize", bufferSize, string.Empty);
            }

            var buffer = new T[bufferSize];

            return(Observable.Using(
                       () =>
            {
                RJCPIO.Parity rjcpParity;
                switch (parity)
                {
                case Parity.Even: rjcpParity = RJCPIO.Parity.Even; break;

                case Parity.Mark: rjcpParity = RJCPIO.Parity.Mark; break;

                case Parity.None: rjcpParity = RJCPIO.Parity.None; break;

                case Parity.Odd: rjcpParity = RJCPIO.Parity.Odd; break;

                case Parity.Space: rjcpParity = RJCPIO.Parity.Space; break;

                default: throw new NotSupportedException(string.Format("'{0}' is not supported.", parity));
                }

                RJCPIO.StopBits rjcpStopBits;
                switch (stopBits)
                {
                case StopBits.One: rjcpStopBits = RJCPIO.StopBits.One; break;

                case StopBits.OnePointFive: rjcpStopBits = RJCPIO.StopBits.One5; break;

                case StopBits.Two: rjcpStopBits = RJCPIO.StopBits.Two; break;

                default: throw new NotSupportedException(string.Format("'{0}' is not supported.", stopBits));
                }

                var port = new RJCPIO.SerialPortStream(portName, (int)baudRate, dataBits, rjcpParity, rjcpStopBits)
                {
                    NewLine = "\r\n", Encoding = encoding
                };
                port.Open();

                return port;
            },
                       port =>
            {
                int?count = null;

                return Observable.While(() => port.IsOpen && (count == null || count > 0),
                                        Observable.Defer(
                                            async() =>
                {
                    try
                    {
                        count = await readFromPort(port, buffer).ConfigureAwait(false);

                        if (count <= 0)
                        {
                            return Notification.CreateOnCompleted <T>().ToObservable();
                        }
                        else
                        {
                            var received = new T[count.Value];
                            Array.Copy(buffer, 0, received, 0, count.Value);
                            return received.ToObservable();
                        }
                    }
                    catch (Exception ex)
                    {
                        return Notification.CreateOnError <T>(ex).ToObservable();
                    }
                }));
            }));
        }
Exemple #17
0
        public static J2534Err PassThruConnect(int deviceId, ProtocolID protocolId, ConnectFlag flags, BaudRate baudRate, ref int channelId)
        {
            Log.WriteTimestamp("", "PTConnect({0}, {1}, {2}, {3}, {4})", deviceId, protocolId, flags, baudRate, channelId);

            var result = Loader.Lib.PassThruConnect(deviceId, protocolId, flags, baudRate, ref channelId);

            Log.WriteTimestamp("  ", "{0}: {1}", (int)result, result);

            return(result);
        }
 public static IObservable <char> CreateCharListener(string portName, BaudRate baudRate, Parity parity, int dataBits, StopBits stopBits, int?bufferSize = null)
 {
     return(CreateCharListener(portName, baudRate, parity, dataBits, stopBits, Encoding.ASCII, bufferSize));
 }
 public static IObservable <byte> CreateByteListener(string portName, BaudRate baudRate, Parity parity, int dataBits, StopBits stopBits, int?bufferSize = null)
 {
     return(CreateListener <byte>(portName, baudRate, parity, dataBits, stopBits, Encoding.ASCII, bufferSize ?? (int)baudRate,
                                  (port, buffer) => port.ReadAsync(buffer, 0, buffer.Length)));
 }
Exemple #20
0
 /// <summary>
 /// Sets baud rate. Default is 9600 bps.
 /// Baud rate is applicable only in UART mode and only in some BSL revs.
 /// </summary>
 public Status SetBaudRate(BaudRate BaudRate)
 {
     return(dev.ChangeBaudRate(BaudRate) ?? Utils.StatusCreateEx(466));
 }
Exemple #21
0
 //--------------------------------------------------------------------------------
 /// <summary>
 /// Конструктор
 /// </summary>
 public CanPort()
 {
     //#if DEBUG
     //WindowsDebugging = new OutputWindow(String.Format("CAN-Port {0}", this.PortName));
     //WindowsDebugging.Show();
     //#endif
     // Настраиваем поля 
     // Инициализируем входной буфер сообщений
     this._InputBufferMessages = new Queue<Frame>(100);
     // Инициализируем свойства порта
     this._FrameFormat = FrameFormat.StandardFrame;
     this._ErrorFrameEnable = true;
     this._ListenOnlyMode = false;
     this._LowSpeedModeEnable = false;
     // Устанавливаем скорость по умолчанию
     this._CanBitRate = BaudRate.BR10;
 }
Exemple #22
0
 public static Boolean LessThanMax(BaudRate baudRate, SettableBaud settableBaud)
 {
     return LessThanMax((Int32) baudRate, settableBaud);
 }
Exemple #23
0
        /// <summary>
        /// Конструктор для десериализации
        /// </summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        public CanPort(SerializationInfo info, StreamingContext context)
        {
            this.PortName = info.GetString("PortName");
            this._InputBufferMessages = new Queue<Frame>(100);

            this._FrameFormat = (FrameFormat)info.GetValue("FrameFormat", typeof(FrameFormat));
            this._ErrorFrameEnable = info.GetBoolean("ErrorFrameEnable");
            this._ListenOnlyMode = info.GetBoolean("ListenOlnyMode");
            this._CanBitRate = (BaudRate)info.GetValue("BitRate", typeof(BaudRate));
        }
 public WindowsSerialDevice(string portName, BaudRate baudRate) : base(portName, baudRate)
 {
 }
        /* CONSTRUCTOR */
        public Com_SerialPort()
        {
            portIndex = 1;
            baudRate = BaudRate.Baud_9600;
            parity = Parity.None;
            dataBits = ByteSize.Eight;
            stopBits = StopBits.One;
            handle = IntPtr.Zero;
            ReadIntervalTimeout = Com_WinApi.MAXDWORD;

            _pcfg = new Hashtable();

            _pcfg.Add("PORT", this.portIndex);
            _pcfg.Add("RATE", (int)this.baudRate);
            _pcfg.Add("PARITY", (byte)this.parity);
            _pcfg.Add("DBITS", (byte)this.dataBits);
            _pcfg.Add("SBITS", (int)this.stopBits);
            _pcfg.Add("RT", this.ReadIntervalTimeout);
            _pcfg.Add("RM", this.ReadTotalTimeoutMultiplier);
            _pcfg.Add("RC", this.ReadTotalTimeoutConstant);
            _pcfg.Add("WM", this.WriteTotalTimeoutMultiplier);
            _pcfg.Add("WC", this.WriteTotalTimeoutConstant);
        }
Exemple #26
0
        /// <summary>
        /// Set communicatin speed that will be used by camera until physically power off.
        /// </summary>
        /// <param name="baudRate">Baudrate</param>
        /// <returns>True if succeeded</returns>
        public bool SetBaudRate(BaudRate baudRate)
        {
            byte divider1;

            switch (baudRate)
            {
                case BaudRate.Baud7200:
                    divider1 = 0xFF;
                    break;
                case BaudRate.Baud9600:
                    divider1 = 0xBF;
                    break;
                case BaudRate.Baud14400:
                    divider1 = 0x7F;
                    break;
                case BaudRate.Baud19200:
                    divider1 = 0x5F;
                    break;
                case BaudRate.Baud28800:
                    divider1 = 0x3F;
                    break;
                case BaudRate.Baud38400:
                    divider1 = 0x2F;
                    break;
                case BaudRate.Baud57600:
                    divider1 = 0x1F;
                    break;
                case BaudRate.Baud115200:
                    divider1 = 0x0F;
                    break;
                default:
                    divider1 = 0xBF;
                    break;
            }

            // Create 'Set Baudrate' command
            command[0] = CMD_PREFIX;
            command[1] = CMD_BAUDRATE;
            command[2] = divider1; // Divider 1
            command[3] = 0x01; // Divider 2
            command[4] = 0x00;
            command[5] = 0x00;

            // Send 'Set Baudrate' command
            SendCommand(command);

            // Receive ACK
            if (!ReceiveACK(CMD_BAUDRATE)) //100
                return false;

            return true;
        }
Exemple #27
0
 public HamLibWrapper(string rigName, string port, BaudRate baudRate, Handshake handshake, int dataBits, int stopBits)
 {
     hamLibWrapper = new HamLibWrapperInternal(rigName, port, baudRate, handshake, dataBits, stopBits);
 }
Exemple #28
0
        public uWAVEPort(string portName, BaudRate portBaudrate)
        {
            #region NMEA init

            if (!singleton)
            {
                NMEAParser.AddManufacturerToProprietarySentencesBase(ManufacturerCodes.UWV);

                // IC_D2H_ACK             $PUWV0,cmdID,errCode
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "0", "c--c,x");

                // IC_H2D_SETTINGS_WRITE  $PUWV1,rxChID,txChID,styPSU,isCmdMode,isACKOnTXFinished,gravityAcc
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "1", "x,x,x.x,x,x,x.x");

                // IC_H2D_RC_REQUEST      $PUWV2,txChID,rxChID,rcCmdID
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "2", "x,x,x");

                // IC_D2H_RC_RESPONSE     $PUWV3,txChID,rcCmdID,propTime_seс,snr,[value],[azimuth]
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "3", "x,x,x.x,x.x,x.x,x.x");

                // IC_D2H_RC_TIMEOUT      $PUWV4,txChID,rcCmdID
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "4", "x,x");

                // IC_D2H_RC_ASYNC_IN     $PUWV5,rcCmdID,snr,[azimuth]
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "5", "x,x.x,x.x");

                // IC_H2D_AMB_DTA_CFG     $PUWV6,isWriteInFlash,periodMs,isPrs,isTemp,isDpt,isBatV
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "6", "x,x,x,x,x,x");

                // IC_D2H_AMB_DTA         $PUWV7,prs_mBar,temp_C,dpt_m,batVoltage_V
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "7", "x.x,x.x,x.x,x.x");

                // IC_D2H_LBLA            $PUWVA,baseID,baseLat,baseLon,baseDpt,baseBat,pingerData,TOAsecond
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "A", "x,x.x,x.x,x.x,x.x,x,x.x");

                // IC_H2D_DINFO_GET       $PUWV?,reserved
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "?", "x");

                // IC_D2H_DINFO $PUWV!,serial_number,sys_moniker,sys_version,core_moniker [release],core_version,acBaudrate,rxChID,txChID,totalCh,styPSU,isPTS,isCmdModeDefault
                NMEAParser.AddProprietarySentenceDescription(ManufacturerCodes.UWV, "!", "c--c,c--c,x,c--c,x,x.x,x,x,x,x.x,x,x");


                singleton = true;
            }

            #endregion

            #region Parsers

            parsers = new Dictionary <ICs, parserDelegate>()
            {
                { ICs.IC_D2H_ACK, new parserDelegate(ACK_Parse) },
                { ICs.IC_D2H_AMB_DTA, new parserDelegate(AMB_DTA_Parse) },
                { ICs.IC_D2H_DINFO, new parserDelegate(DINFO_Parse) },
                { ICs.IC_D2H_RC_ASYNC_IN, new parserDelegate(RC_ASYNC_IN_Parse) },
                { ICs.IC_D2H_RC_RESPONSE, new parserDelegate(RC_RESPONSE_Parse) },
                { ICs.IC_D2H_RC_TIMEOUT, new parserDelegate(RC_TIMEOUT_Parse) },
                { ICs.IC_D2H_LBLA, new parserDelegate(RC_LBLA_Parse) }
            };

            #endregion

            #region port

            port = new NMEASerialPort(new SerialPortSettings(portName,
                                                             portBaudrate,
                                                             System.IO.Ports.Parity.None,
                                                             DataBits.dataBits8,
                                                             System.IO.Ports.StopBits.One,
                                                             System.IO.Ports.Handshake.None));

            port.NewNMEAMessage += new EventHandler <NewNMEAMessageEventArgs>(port_NewNMEAMessageReceived);
            port.PortError      += new EventHandler <SerialErrorReceivedEventArgs>(port_ErrorReceived);
            port.RawDataReceived = new EventHandler <RawDataReceivedEventArgs>(port_RawDataReceived);

            #endregion

            #region timer

            timer        = new PrecisionTimer();
            timer.Mode   = Mode.Periodic;
            timer.Period = 1000;
            timer.Tick  += new EventHandler(timer_Tick);

            #endregion

            #region Misc.

            InitDeviceInformation();

            #endregion
        }
 private void ConstructorSuccessTest(BaudRate baud)
 {
     ConstructorSuccessTest(Serial.COM1, (int)baud, Parity.None, 8, StopBits.One);
 }
Exemple #30
0
        /// <summary>
        /// set the baudrate for the serial communication
        /// </summary>
        /// <param name="baudRate">constant baudrate for the communication</param>
        private void setBaudRate(BaudRate baudRate)
        {
            if (_sPort.IsOpen)
            {
                _sPort.Close();
            }
            try
            {
                switch (baudRate)
                {
                case BaudRate.CBR_1200:
                    _sPort.BaudRate = 1200;
                    _waitingTime    = 1400;
                    break;

                case BaudRate.CBR_2400:
                    _sPort.BaudRate = 2400;
                    _waitingTime    = 1000;
                    break;

                case BaudRate.CBR_4800:
                    _sPort.BaudRate = 4800;
                    _waitingTime    = 900;
                    break;

                case BaudRate.CBR_9600:
                    _sPort.BaudRate = 9600;
                    _waitingTime    = 700;
                    break;

                case BaudRate.CBR_19200:
                    _sPort.BaudRate = 19200;
                    _waitingTime    = 550;
                    break;

                case BaudRate.CBR_38400:
                    _sPort.BaudRate = 38400;
                    _waitingTime    = 400;
                    break;

                case BaudRate.CBR_57600:
                    _sPort.BaudRate = 57600;
                    _waitingTime    = 200;
                    break;

                case BaudRate.CBR_115200:
                    _sPort.BaudRate = 115200;
                    _waitingTime    = 100;
                    break;
                }
            }
            catch (ArgumentOutOfRangeException e)
            {
                throw new ArgumentOutOfRangeException(e.Message);
            }
            catch (IOException e)
            {
                throw new IOException(e.Message);
            }
            catch (Exception e)
            {
                if (e.InnerException != null)
                {
                    throw new Exception(e.InnerException.Message);
                }
                else
                {
                    throw new Exception(e.Message);
                }
            }
        }
Exemple #31
0
 /// <summary>
 ///     Sets the baud rate for the serial interface on this node.
 /// </summary>
 /// <param name="baudRate"></param>
 /// <returns></returns>
 public Task SetBaudRateAsync(BaudRate baudRate)
 {
     return(ExecuteAtCommandAsync(new BaudRateCommand(baudRate), true));
 }
        public static BaudRate GetSelectBaudRate(int nInxex)
        {
            BaudRate br = BaudRate._500Kbps;

            switch (nInxex)
            {
            case 0:
                br = BaudRate._5Kbps;
                break;

            case 1:
                br = BaudRate._10Kbps;
                break;

            case 2:
                br = BaudRate._20Kbps;
                break;

            case 3:
                br = BaudRate._40Kbps;
                break;

            case 4:
                br = BaudRate._50Kbps;
                break;

            case 5:
                br = BaudRate._80Kbps;
                break;

            case 6:
                br = BaudRate._100Kbps;
                break;

            case 7:
                br = BaudRate._125Kbps;
                break;

            case 8:
                br = BaudRate._200Kbps;
                break;

            case 9:
                br = BaudRate._250Kbps;
                break;

            case 10:
                br = BaudRate._400Kbps;
                break;


            case 11:
                br = BaudRate._500Kbps;
                break;

            case 12:
                br = BaudRate._666Kbps;
                break;

            case 13:
                br = BaudRate._800Kbps;
                break;

            case 14:
                br = BaudRate._1000Kbps;
                break;
            }
            return(br);
        }
 ///<summary>串口控件</summary>
 public SerialPortControl()
 {
     BaudRateString = BaudRate.ToString();
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="baudRate">波特率</param>
        private void SetBaudRateTimer(BaudRate value)
        {
            switch (value)
            {
            case BaudRate._5Kbps:
                SetTimerBasedOnBaudRate(0xBF, 0xFF);
                break;

            case BaudRate._10Kbps:
                SetTimerBasedOnBaudRate(0x31, 0x1C);
                break;

            case BaudRate._20Kbps:
                SetTimerBasedOnBaudRate(0x18, 0x1C);
                break;

            case BaudRate._40Kbps:
                SetTimerBasedOnBaudRate(0x87, 0xFF);
                break;

            case BaudRate._50Kbps:
                SetTimerBasedOnBaudRate(0x09, 0x1C);
                break;

            case BaudRate._80Kbps:
                SetTimerBasedOnBaudRate(0x83, 0xFF);
                break;

            case BaudRate._100Kbps:
                SetTimerBasedOnBaudRate(0x04, 0x1C);
                break;

            case BaudRate._125Kbps:
                SetTimerBasedOnBaudRate(0x03, 0x1C);
                break;

            case BaudRate._200Kbps:
                SetTimerBasedOnBaudRate(0x81, 0xFA);
                break;

            case BaudRate._250Kbps:
                SetTimerBasedOnBaudRate(0x01, 0x1C);
                break;

            case BaudRate._400Kbps:
                SetTimerBasedOnBaudRate(0x80, 0xFA);
                break;

            case BaudRate._500Kbps:
                SetTimerBasedOnBaudRate(0x00, 0x1C);
                break;

            case BaudRate._666Kbps:
                SetTimerBasedOnBaudRate(0x80, 0xB6);
                break;

            case BaudRate._800Kbps:
                SetTimerBasedOnBaudRate(0x00, 0x16);
                break;

            case BaudRate._1000Kbps:
                SetTimerBasedOnBaudRate(0x00, 0x14);
                break;

            default:
                SetTimerBasedOnBaudRate(0x00, 0x1C);
                break;
            }
        }
 public void Open(string port, BaudRate baudRate, Handshake handshake, int dataBits, int stopBits) => innerRig.Open(port, baudRate, handshake, dataBits, stopBits);
		/// <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;
		}
Exemple #37
0
 public static extern int cfsetspeed(byte[] termios_data, BaudRate speed);
		/// <summary>
		/// Class handling the LinkSprite JPEG Color Camera, connected to the UART on the Raspberry Pi GPIO Pin Header.
		/// For more inforation, see: <see cref="http://www.linksprite.com/upload/file/1291522825.pdf"/>
		/// 
		/// NOTE: To be able to use the UART on the Raspberry GPIO Pin Header, you need to disable the ttyAMA0 device in Linux. For more information
		/// on how to do this, see: <see cref="http://elinux.org/RPi_Serial_Connection#Connection_to_a_microcontroller_or_other_peripheral"/>.
		/// </summary>
		/// <param name="BaudRate">Baud Rate to use</param>
		public LinkSpriteJpegColorCamera (BaudRate BaudRate)
		{
			this.uart = new Uart ((int)BaudRate, Parity.None, 8, StopBits.None);
			this.uart.NewLine = "\r\n";
			this.uart.OutputToConsole = false;	// Set to true, to debug communication.
		}
Exemple #39
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="portName"></param>
        /// <param name="bitRate"></param>
        /// <param name="frameFormat"></param>
        /// <param name="mode"></param>
        public CanPort(String portName, BaudRate bitRate, FrameFormat frameFormat,
            PortMode mode)
        {
            // Инициализируем буфер входящих сообщений
            this._InputBufferMessages = new Queue<Frame>(100);

            // Инициализируем дескриптор устройства
            this._DeviceHandle = new SafeFileHandle(IntPtr.Zero, true);
            this._DeviceHandle.Close();

            // Номер порта
            PortName = portName;
            _BitRate = bitRate;
            _FrameFormat = frameFormat;
            _OpMode = mode;

            // Структура таймаутов
            _Timeouts = new F_CAN_TIMEOUTS();
        }
Exemple #40
0
 public override void CommSet(BaudRate baud_rate)
 {
 }
Exemple #41
0
        /// <summary>
        /// Преобразуте значение перечислимого NGK.CAN.OSIModel.DataLinkLayer.BITRATE
        /// в структуру Ixxat.Vci3.Bal.Can.CanBitrate
        /// </summary>
        /// <returns>Ixxat.Vci3.Bal.Can.CanBitrate</returns>
        private static Ixxat.Vci3.Bal.Can.CanBitrate ConvertBitrate(BaudRate bitRate)
        {
            String msg;
            Ixxat.Vci3.Bal.Can.CanBitrate IxxatBitRate;

            switch (bitRate)
            {
                case BaudRate.BR10:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia10KBit;
                        break; 
                    }
                case BaudRate.BR20:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia20KBit;
                        break;
                    }
                case BaudRate.BR50:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia50KBit;
                        break;
                    }
                case BaudRate.BR100:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate._100KBit;
                        break;
                    }
                case BaudRate.BR125:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia125KBit;
                        break;
                    }
                case BaudRate.BR250:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia250KBit;
                        break;
                    }
                case BaudRate.BR500:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia500KBit;
                        break;
                    }
                case BaudRate.BR1000:
                    {
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Cia1000KBit;
                        break;
                    }
                default:
                    {
                        msg = String.Format(
                            "{0}: class CanPort: Невозможно преобразовать значение типа BITRATE в значение типа Ixxat.Vci3.Bal.Can.CanBitrate. Не найдено соответствие", 
                            DateTime.Now.ToString(new System.Globalization.CultureInfo("ru-Ru", false)));
                        IxxatBitRate = Ixxat.Vci3.Bal.Can.CanBitrate.Empty;
                        Trace.TraceError(msg);
                        throw new ArgumentException(msg, "bitRate");
                    }
            }
            return IxxatBitRate;
        }
Exemple #42
0
 public SerialPort(string portName, BaudRate baudRate, Parity parity, DataBits dataBits, StopBits stopBits, Handshake handshake)
     : base(portName, (int)baudRate, (_Parity)parity, (int)dataBits, (_StopBits)stopBits)
 {
     this.Handshake = (_Handshake)handshake;
 }
Exemple #43
0
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <param name="portName">Наименование порта (серийный номер порта)</param>
        public CanPort(String portName, BaudRate bitRate, FrameFormat frameFormat,
            PortMode mode)
        {
            IVciDeviceList deviceList;
            String serialNumber;
            Object pack;

            // Настраиваем поля 
            this.PortName = portName;
            // Инициализируем входной буфер сообщений
            this._InputBufferMessages = new Queue<Frame>(100);
            // Инициализируем свойства порта
            this._FrameFormat = frameFormat;
            this._ErrorFrameEnable = true;
            ((ICanPort)this).Mode = mode;
            this._LowSpeedModeEnable = false;
            // Устанавливаем скорость по умолчанию
            this._CanBitRate = bitRate;

            // Получаем список доступных устройств
            deviceList = GetDeviceList();
            // Находим нужное нам устройство и открываем его
            foreach (IVciDevice item in deviceList)
            {
                pack = (Object)item.UniqueHardwareId;
                serialNumber = GetSerialNumber(ref pack);

                if (serialNumber == this._SerialNumber)
                {
                    // Устройство найдено
                    this._CanDevice = item;
                    break;
                }
            }
        }
Exemple #44
0
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         LogicalName = GXCommon.ToLogicalName(e.Value);
     }
     else if (e.Index == 2)
     {
         InitiatorElectricalPhase = (InitiatorElectricalPhase)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 3)
     {
         DeltaElectricalPhase = (DeltaElectricalPhase)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 4)
     {
         MaxReceivingGain = (byte)e.Value;
     }
     else if (e.Index == 5)
     {
         MaxTransmittingGain = (byte)e.Value;
     }
     else if (e.Index == 6)
     {
         SearchInitiatorThreshold = (byte)e.Value;
     }
     else if (e.Index == 7)
     {
         object[] tmp = (object[])e.Value;
         MarkFrequency  = (UInt32)tmp[0];
         SpaceFrequency = (UInt32)tmp[1];
     }
     else if (e.Index == 8)
     {
         MacAddress = (UInt16)e.Value;
     }
     else if (e.Index == 9)
     {
         List <ushort> list = new List <ushort>();
         if (e.Value != null)
         {
             foreach (object it in (object[])e.Value)
             {
                 list.Add((ushort)it);
             }
         }
         MacGroupAddresses = list.ToArray();
     }
     else if (e.Index == 10)
     {
         Repeater = (Repeater)Convert.ToInt32(e.Value);
     }
     else if (e.Index == 11)
     {
         RepeaterStatus = (bool)e.Value;
     }
     else if (e.Index == 12)
     {
         MinDeltaCredit = (byte)e.Value;
     }
     else if (e.Index == 13)
     {
         InitiatorMacAddress = (UInt16)e.Value;
     }
     else if (e.Index == 14)
     {
         SynchronizationLocked = (bool)e.Value;
     }
     else if (e.Index == 15)
     {
         TransmissionSpeed = (BaudRate)Convert.ToInt32(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
 void IGXDLMSBase.SetValue(int index, object value)
 {
     if (index == 1)
     {
         if (value is string)
         {
             LogicalName = value.ToString();
         }
         else
         {
             LogicalName = GXDLMSClient.ChangeType((byte[])value, DataType.OctetString).ToString();
         }                
     }
     else if (index == 2)
     {
         CommSpeed = (BaudRate)Convert.ToInt32(value);
     }
     else
     {
         throw new ArgumentException("SetValue failed. Invalid attribute index.");
     }
 }
Exemple #46
0
 public J2534Err Connect(int deviceId, ProtocolID protocolId, ConnectFlag flags, BaudRate baudRate, ref int channelId)
 {
     return (J2534Err)m_wrapper.Connect(deviceId, (int)protocolId, (int)flags, (int)baudRate, ref channelId);
 }
Exemple #47
0
 public PortStream(String port, BaudRate baudRate, Parity parity)
     : this(port, (Int32) baudRate, parity, DataSize.DataSize8, StopBits.One)
 {
 }
Exemple #48
0
 //Constructor & destructor
 public ComPort()
 {
     portIndex = 1;
     baudRate = BaudRate.Baud_9600;
     parity = Parity.None;
     dataBits = ByteSize.Eight;
     stopBits = StopBits.One;
     handle = IntPtr.Zero;
     ReadIntervalTimeout = API.MAXDWORD;
 }
Exemple #49
0
 protected SerialDevice(string portName, BaudRate baudRate)
 {
     this.portName = portName;
     this.baudRate = baudRate;
 }
Exemple #50
0
 public Connection(string portName, BaudRate baudRate)
 {
     _serialPort = new SerialPort(portName, Convert.ToInt32(baudRate));
 }
        public Contracts.StartSerialResponse StartSerialPortConsole(int portID, int clientSessionInactivityTimeoutInSecs, int serialdeviceCommunicationTimeoutInMsecs, BaudRate baudRate)
        {
            Contracts.StartSerialResponse response = new Contracts.StartSerialResponse();
            response.completionCode = Contracts.CompletionCode.Failure;
            response.serialSessionToken = null;
            this.portId = portID;

            Tracer.WriteInfo("Received StartSerialPortConsole({0})", this.portId);

            int clientInactivityTimeoutInSecs = ConfigLoaded.SerialPortConsoleClientSessionInactivityTimeoutInSecs;
            if (clientSessionInactivityTimeoutInSecs < 0 || clientSessionInactivityTimeoutInSecs > 0)
            {
                clientInactivityTimeoutInSecs = clientSessionInactivityTimeoutInSecs;
            }

            byte[] randomNumber = new byte[8];
            new System.Security.Cryptography.RNGCryptoServiceProvider().GetNonZeroBytes(randomNumber);
            Tracer.WriteInfo("StartSerialPortConsole: Random string is " + BitConverter.ToString(randomNumber));

            // Initialize Serial Session MetaData including the client inactivity timeout - this function does this automically
            // This function acts as a serialization point - only one active thread can proceed beyond this
            if (this.CompareAndSwapMetadata(ConfigLoaded.InactiveSerialPortSessionToken, BitConverter.ToString(randomNumber), DateTime.Now, clientInactivityTimeoutInSecs) != CompletionCode.Success)
            {
                response.completionCode = Contracts.CompletionCode.SerialSessionActive;
                return response;
            }

            SerialPortConsole currConsole = new SerialPortConsole((byte)portId);
            SerialStatusPacket serialStatus = new SerialStatusPacket();

            // We should later take the default value from app.config and include this as parameter in REST API
            BaudRate portBaudRate = (BaudRate)baudRate;

            // Negative timeout values will be interpreted as infinite timeout by the device layer open serial port function
            int communicationDeviceTimeoutIn1ms = ConfigLoaded.SerialPortConsoleDeviceCommunicationTimeoutInMsecs;
            if (serialdeviceCommunicationTimeoutInMsecs != 0)
            {
                communicationDeviceTimeoutIn1ms = serialdeviceCommunicationTimeoutInMsecs;
                if (communicationDeviceTimeoutIn1ms > 0 && communicationDeviceTimeoutIn1ms < ConfigLoaded.SerialPortConsoleDeviceCommunicationTimeoutInMsecs)
                {
                    communicationDeviceTimeoutIn1ms = ConfigLoaded.SerialPortConsoleDeviceCommunicationTimeoutInMsecs;
                }
            }

            serialStatus = currConsole.openSerialPortConsole(communicationDeviceTimeoutIn1ms, portBaudRate);
            Tracer.WriteInfo("After calling comm dev open serial port");
            if (serialStatus.completionCode != CompletionCode.Success)
            {
                Tracer.WriteError("Error in Open Serial Port ({0}) and baudRate ({1})", portId, baudRate);
                if (!this.ResetMetadata())
                {
                    Tracer.WriteError("StartSerialPortConsole Error: Unable to reset metadata");
                }
                return response;
            }

            response.completionCode = Contracts.CompletionCode.Success;
            response.serialSessionToken = BitConverter.ToString(randomNumber);
            return response;
        }
 void IGXDLMSBase.SetValue(GXDLMSSettings settings, ValueEventArgs e)
 {
     if (e.Index == 1)
     {
         if (e.Value is string)
         {
             LogicalName = e.Value.ToString();
         }
         else
         {
             LogicalName = GXDLMSClient.ChangeType((byte[])e.Value, DataType.OctetString).ToString();
         }
     }
     else if (e.Index == 2)
     {
         CommSpeed = (BaudRate)Convert.ToInt32(e.Value);
     }
     else
     {
         e.Error = ErrorCode.ReadWriteDenied;
     }
 }
Exemple #53
0
 //Private methods
 private void LoadMembers(XmlTextReader xtr)
 {
     if (xtr.NodeType == XmlNodeType.Element)
     {
         switch (xtr.Name)
         {
             case "PortIndex":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.portIndex = int.Parse(xtr.Value);
                 break;
             case "BaudRate":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.baudRate = (BaudRate)int.Parse(xtr.Value);
                 break;
             case "Parity":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.parity = (Parity)byte.Parse(xtr.Value);
                 break;
             case "DataBits":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.dataBits = (ByteSize)byte.Parse(xtr.Value);
                 break;
             case "StopBits":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.stopBits = (StopBits)byte.Parse(xtr.Value);
                 break;
             case "ReadIntervalTimeout":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.ReadIntervalTimeout = UInt32.Parse(xtr.Value);
                 break;
             case "ReadTotalTimeoutMultiplier":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.ReadTotalTimeoutMultiplier = UInt32.Parse(xtr.Value);
                 break;
             case "ReadTotalTimeoutConstant":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.ReadTotalTimeoutConstant = UInt32.Parse(xtr.Value);
                 break;
             case "WriteTotalTimeoutMultiplier":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.WriteTotalTimeoutMultiplier = UInt32.Parse(xtr.Value);
                 break;
             case "WriteTotalTimeoutConstant":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.WriteTotalTimeoutConstant = UInt32.Parse(xtr.Value);
                 break;
             case "Tag":
                 xtr.Read();
                 if (xtr.NodeType == XmlNodeType.Text)
                     this.tag = xtr.Value;
                 break;
         }
     }
 }
Exemple #54
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);
            }
        }
Exemple #55
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");
        }
Exemple #56
0
 /// <summary>
 /// Set the baud rate for the serial interface on this node.
 /// </summary>
 /// <param name="baudRate"></param>
 /// <returns></returns>
 public async Task SetBaudRateAsync(BaudRate baudRate)
 {
     await ExecuteAtCommandAsync(new BaudRateCommand(baudRate), true);
 }
Exemple #57
0
 public static Boolean IsValid(BaudRate baudRate, SettableBaud settableBaud)
 {
     if (SettableBaud.BaudUser == settableBaud)
     {
         return true;
     }
     for (Int32 index = 0, baud = (Int32) baudRate, setbaud = (Int32) settableBaud;
         0 != setbaud;
         ++index, setbaud = setbaud >> 1)
     {
         if (bauds[index] == baud)
         {
             return 0 != (setbaud & 1);
         }
     }
     return false;
 }
        } // 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()
Exemple #59
0
        private void setBaudRate(BaudRate rate)
        {
            Payload p = new Payload(MessageID.Configure_Serial_Port, new byte[] { 0x00, (byte)rate, 0x02 });
            Write(p);

            if (RESULT.RESULT_ACK == this.waitResult(MessageID.Configure_Serial_Port))
            {
                // 成功したから、COM ポートのボーレートも変更する
                int[] ParaRate = { 4800, 9600, 19200, 38400, 57600, 115200, 230400 };
                _com.BaudRate = ParaRate[(int)rate];

                System.Threading.Thread.Sleep(50);
            }
        }
Exemple #60
0
        /* PRIVATE MEMBERS  */

        // return control ui
        // interact with controls (save/load conifg)
        // update port config and init port


        private void LoadMembers(XmlTextReader xtr)
        {
            if (xtr.NodeType == XmlNodeType.Element)
            {
                switch (xtr.Name)
                {
                    case "PortIndex":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.portIndex = int.Parse(xtr.Value);
                        break;
                    case "BaudRate":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.baudRate = (BaudRate)int.Parse(xtr.Value);
                        break;
                    case "Parity":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.parity = (Parity)byte.Parse(xtr.Value);
                        break;
                    case "DataBits":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.dataBits = (ByteSize)byte.Parse(xtr.Value);
                        break;
                    case "StopBits":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.stopBits = (StopBits)byte.Parse(xtr.Value);
                        break;
                    case "ReadIntervalTimeout":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.ReadIntervalTimeout = UInt32.Parse(xtr.Value);
                        break;
                    case "ReadTotalTimeoutMultiplier":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.ReadTotalTimeoutMultiplier = UInt32.Parse(xtr.Value);
                        break;
                    case "ReadTotalTimeoutConstant":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.ReadTotalTimeoutConstant = UInt32.Parse(xtr.Value);
                        break;
                    case "WriteTotalTimeoutMultiplier":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.WriteTotalTimeoutMultiplier = UInt32.Parse(xtr.Value);
                        break;
                    case "WriteTotalTimeoutConstant":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.WriteTotalTimeoutConstant = UInt32.Parse(xtr.Value);
                        break;
                    case "Tag":
                        xtr.Read();
                        if (xtr.NodeType == XmlNodeType.Text)
                            this.tag = xtr.Value;
                        break;
                }
            }
        }