public void Init(string portName, int baudRate)
        {
            _portName = portName;
            _baudRate = baudRate;

            _disposables?.Dispose();
            _disposables = new CompositeDisposable();

            _sp?.Close();
            _sp = new SerialPort(_portName, _baudRate, 0)
            {
                ReadTimeout = 500, WriteTimeout = 500
            };

            Observable
            .Interval(TimeSpan.FromSeconds(0.1))
            .Select(_ => _sp?.IsOpen ?? false)
            .StartWith(false)
            .DistinctUntilChanged()
            .SubscribeOn(NewThreadScheduler.Default)
            .Subscribe(s => _connectionState.OnNext(s))
            .DisposeWith(_disposables);

            Observable
            .FromEventPattern(_sp, nameof(SerialPort.DataReceived))
            .SubscribeOn(NewThreadScheduler.Default)
            .Subscribe(b =>
            {
                var bs = new byte[_sp.BytesToRead];
                _sp.Read(bs, 0, bs.Length);
                _received.OnNext(bs);
            })
            .DisposeWith(_disposables);
        }
Exemple #2
0
    /// <summary>
    /// 自動的にポートを探す.見つからなければnull
    /// </summary>
    public void FindPort()
    {
        Port?.Close();
        Port = null;

        foreach (var name in SerialPort.GetPortNames())
        {
            var p = new SerialPort(name, 19200, Parity.None, 8, StopBits.One);
            p.Open();
            p.DtrEnable   = true;
            p.RtsEnable   = true;
            p.ReadTimeout = 100;
            p.Write(CheckCmd, 0, CheckCmd.Length);
            Int32 result = p.ReadByte();
            // UFOは機種識別用のデータに対して0x02を返す。なおA10は0x01を返すらしい。
            if (result == 2)
            {
                PortName = name;
                Port     = p;
                break;
            }
            else
            {
                p.Close();
            }
        }
        if (Port == null)
        {
            PortName = "なし";
        }
    }
Exemple #3
0
 public void Disconnect()
 {
     isConnected = false;
     serialPort?.Close();
     serialPort?.Dispose();
     serialPort = null;
 }
Exemple #4
0
    //-- Constructor
    public Chronopic(SerialPort sp)
    {
        //-- Comprobar si puerto serie ya estaba abierto
        if (sp != null)
            if (sp.IsOpen)
                sp.Close();

        //-- Abrir puerto serie
        sp.Open();

        //-- Configurar timeout por defecto
        //de momento no en windows (hasta que no encontremos por qué falla)
        //OperatingSystem os = Environment.OSVersion;
        //not used, now there's no .NET this was .NET related
        //on mono timeouts work on windows and linux
        //if( ! os.Platform.ToString().ToUpper().StartsWith("WIN"))
            sp.ReadTimeout = DefaultTimeout;

        //-- Guardar el puerto serie
        this.sp = sp;

        //		//-- Vaciar buffer
        //		//done in a separate method
        //		this.flush();
    }
Exemple #5
0
 private void ShowSerialConfigForm()
 {
     if (serialPortConfig.PortIsOpen == false)
     {
         var form   = new Form_SerialConfig(serialPortConfig);
         var result = form.ShowDialog();
         if (result == DialogResult.OK)
         {
             baudComboBox.SelectedIndex     = serialPortConfig.BaudRateIndex;
             stopBitsComboBox.SelectedIndex = serialPortConfig.StopBitsIndex;
             dataBitsComboBox.SelectedIndex = serialPortConfig.DataBitsIndex;
             parityComboBox.SelectedIndex   = serialPortConfig.ParityIndex;
             protocolComboBox.SelectedIndex = serialPortConfig.ProtocolIndex;
             comName = form.ComText;
             btnConnect_Click(null, null);
         }
     }
     else
     {
         master = null;
         serialPort?.Close();
         serialPort?.Dispose();
         timerDraw.Enabled           = false;
         timerSave.Enabled           = false;
         labelConnect.Text           = "未连接";
         pictureBoxConnect.BackColor = Color.Red;
         serialPortConfig.PortIsOpen = false;
         labelStatus.Text            = "端口关闭";
         MessageBox.Show("断开连接!");
     }
 }
Exemple #6
0
 /// <summary>
 /// Close connection with rflink
 /// </summary>
 public void Close()
 {
     serialPort?.Close();
     libraryStatus = LibraryStatus.NotReady;
     versionReceived.Reset();
     statusReceived.Reset();
 }
    // The state object is necessary for a TimerCallback.
    public void checkConnection(object stateObject)
    {
        Process p = new Process();
        Ping pingSender = new Ping ();
        p.StartInfo.FileName = "arp";
        p.StartInfo.Arguments = "-a";
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;

        string data = "a";
         byte[] buffer = Encoding.ASCII.GetBytes (data);

        for(int i = 0; i < 25 ; i++){
            pingSender.Send ("10.0.0."+i.ToString(),10,buffer);
        }

        p.Start();

        string output = p.StandardOutput.ReadToEnd();
        p.WaitForExit();

        string MAC = "xx-xx-xx-xx-xx-xx";
        if(output.Contains(MAC)){
            SerialPort port = new SerialPort("COM5", 9600);
            port.Open();
            port.Write("u");
            port.Close();
        }
        else{
            SerialPort port = new SerialPort("COM5", 9600);
            port.Open();
            port.Write("l");
            port.Close();
        }
    }
 protected override void OverridableDispose()
 {
     _serialPort?.Close();
     _serialPort?.Dispose();
     Task.Delay(250)
     .Wait();     // Based on MSDN Documentation, should sleep after calling Close or some functionality will not be determinant.
 }
Exemple #9
0
        //private static Logger logger = LogManager.GetLogger("port");
        public static SerialPort InitializePort1()
        {
            logger.Info("Port1Initialize()");
            port?.Close();
            port?.Dispose();

            try
            {
                port = new SerialPort(PublicData.port1Name);
                port.WriteTimeout = 1500;
                port.ReadTimeout  = 1500;
                logger.Debug($"new SerialPort() {port.PortName}");
            }
            catch (TimeoutException ex)
            {
                logger.Error(ex, ex.Message);
            }
            catch (Exception ex)
            {
                ex.Show($"port1: COM-порт \"{PublicData.port1Name}\" не корректен.");
                port = new SerialPort();
            }
            try
            {
                port.BaudRate = int.Parse(PublicData.port1_rate);
            }
            catch
            {
                port.BaudRate = 9600;
            }
            PublicData.port1_rate = port.BaudRate.ToString();
            return(port);
        }
        private void Disconnect_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                PrintProcessMessage(Environment.NewLine + "Closing port...");


                port?.Close();

                ConnectButton.Visibility    = Visibility.Visible;
                DisconnectButton.Visibility = Visibility.Collapsed;
                ReconnectButton.Visibility  = Visibility.Collapsed;
                ComPorts.IsEnabled          = true;

                MessageToSend.IsEnabled = false;
                SendButton.IsEnabled    = false;

                Settings.IsEnabled = true;

                PrintSuccessMessage("Port closed!" + Environment.NewLine + Environment.NewLine);
            }
            catch (Exception ex)
            {
                PrintErrorMessage(ex.Message);
            }
        }
    // Use this for initialization
    void Start()
    {
        Debug.Log(SerialPort.GetPortNames().ToString());
        mySerialPort = new SerialPort("\\\\.\\COM18");
        mySerialPort.BaudRate = 9600;
        //mySerialPort.Parity = Parity.None;
        //mySerialPort.StopBits = StopBits.One;
        //mySerialPort.DataBits = 8;
        //mySerialPort.Handshake = Handshake.None;
        //mySerialPort.RtsEnable = true;

        //mySerialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

        if ( mySerialPort != null )
        {
            if ( mySerialPort.IsOpen ) // close if already open
            {
                mySerialPort.Close();
                Debug.Log ("Closed stream");
            }
            mySerialPort.Open();
            Debug.Log ("Opened stream");
        }
        else
        {
            Debug.Log ("ERROR: Uninitialized stream");
        }
          myThread = new Thread(new ThreadStart(GetArduino));
          	  myThread.Start();
    }
Exemple #12
0
        private void Connect()
        {
            try
            {
                Serial?.Close();
                Thread.Sleep(50);

                Serial = new SerialPort(PortName)
                {
                    BaudRate = 9600,
                    DataBits = 8,
                    Parity   = Parity.None,
                    StopBits = StopBits.One
                };
                Serial.Open();

                Modbus = ModbusSerialMaster.CreateRtu(Serial);
                Modbus.Transport.Retries     = 2;
                Modbus.Transport.ReadTimeout = 100;
                Modbus.ReadInputRegisters(1, 0, 4);

                ModbusDeviceStates.Fire(TemperatureDeviceEdge.ConnectionValid);
            }
            catch
            {
                Serial?.Close();
                Thread.Sleep(50);
                ModbusDeviceStates.Fire(TemperatureDeviceEdge.ConnectionInvalid);
            }
        }
 public void CloseConnection()
 {
     if (Opened)
     {
         _serialPort?.Close();
     }
 }
        /// <summary>
        /// キーボードデバイス名を指定してオープンする
        /// </summary>
        /// <param name="friendlyName">キーボードデバイス名</param>
        public void Open(string friendlyName)
        {
            KeyboardDeviceInfo kdi = devices.Find(x => x.FriendlyName == friendlyName) ?? throw new NoKeyboardDeviceException();

            // サーバを閉じる
            myClient?.Close();
            myClient = null;

            // COMポートを閉じる
            myPort?.Close();
            myPort = null;

            switch (kdi.DeviceType)
            {
            case KeyboardDeviceInfo.KeyboardDeviceType.COM:
                OpenCOMPort(kdi);
                break;

            case KeyboardDeviceInfo.KeyboardDeviceType.SERVER:
                OpenServer(kdi);
                break;

            default:
                break;
            }
        }
Exemple #15
0
        public static SerialPort InitializePortGenr()
        {
            genr?.Close();
            genr?.Dispose();
            try
            {
                genr = new SerialPort(PublicData.port2Name);
                genr.WriteTimeout = 1000;
            }
            catch (Exception z)
            {
                z.Show(PublicData.port2Name);
                genr = new SerialPort();
            }
            try
            {
                genr.BaudRate = int.Parse(PublicData.port2_rate);
            }
            catch
            {
                genr.BaudRate = 9600;
            }

            PublicData.port2_rate = genr.BaudRate.ToString();
            return(genr);
        }
Exemple #16
0
 private void DisconnectButton_Click(object sender, RoutedEventArgs e)
 {
     Console.WriteLine("Disconnect.");
     serial?.Close();
     serial?.Dispose();
     serial = null;
 }
Exemple #17
0
        public static void Main(string[] args)
        {
            Console.Error.WriteLine("Hi, i'm juniorcopy");
            if (!(args.Length == 0 || args.Length == 2 && args[0] == "-s"))
            {
                Console.Error.WriteLine("Usage: juniorCopy [-s <file to send>]");
                return;
            }

            string[] ports = SerialPort.GetPortNames();
            if (ports.Length == 0)
            {
                Console.Error.WriteLine("No serial ports found. Bye!");
                return;
            }
            // else
            Console.Error.WriteLine("Ports: " + string.Join(",", ports));

            SerialPort serialPort = OpenSerialPort(ports);

            if (args.Length == 0)
            {
                ReceiveFromJunior(serialPort);
            }
            else
            {
                SendToJunior(serialPort, args[1]);
            }

            serialPort?.Close();
            Console.Error.WriteLine("bye!");
        }
 private void OnConnect(object sender, RoutedEventArgs e)
 {
     try
     {
         _port?.Close();
         _port?.Dispose();
     }
     catch (Exception)
     {
     }
     _port = new SerialPort(SelectedPort.Name);
     _port.Open();
     Task.Run(() =>
     {
         try
         {
             while (true)
             {
                 System.Diagnostics.Debug.WriteLine(_port.ReadLine());
             }
         }
         catch (Exception)
         {
         }
     });
 }
 //Zamyka pozostałe okna gdy główne zostało wyłączone
 private void Window_Closed(object sender, EventArgs e)
 {
     serialPort?.Close();
     comPort?.Close();
     comTool?.Close();
     jogOp?.Close();
     posAdd?.Close();
 }
 public void ModbusDisConnect()
 {
     try
     {
         curSerialPort?.Close();
     }
     catch { }
 }
 /// <summary>
 /// Disconnect from GPIB adapter.
 /// </summary>
 public void Disconnect()
 {
     try
     {
         _serialPort?.Close();
     }
     catch (IOException) { }
 }
Exemple #22
0
 private static void SafeExit(object sender, ConsoleCancelEventArgs e)
 {
     Console.WriteLine("Terminating application...");
     running = false;
     port?.Close();
     Console.WriteLine("Resources disposed...");
     Environment.Exit(0);
 }
Exemple #23
0
        public bool Open(string portName = null)
        {
            try
            {
                m_serialPort?.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

            m_serialPort?.Dispose();

            try
            {
                if (portName == null)
                {
                    portName = m_portName;
                }
                else
                {
                    m_portName = portName;
                }
                m_serialPort = new SerialPort(portName);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                return(false);
            }

            m_serialPort.BaudRate  = 115200;
            m_serialPort.Parity    = Parity.None;
            m_serialPort.StopBits  = StopBits.One;
            m_serialPort.DataBits  = 8;
            m_serialPort.Handshake = Handshake.None;
            m_serialPort.RtsEnable = true;
            m_serialPort.DtrEnable = true;

            m_serialPort.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);

            try
            {
                m_serialPort.Open();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);

                m_serialPort.Dispose();
                m_serialPort = null;

                return(false);
            }

            return(true);
        }
Exemple #24
0
 private void Stop()
 {
     if (serialPort != null)
     {
         serialPort?.Close();
         serialPort?.Dispose();
         serialPort = null;
     }
 }
Exemple #25
0
 protected virtual void Dispose(bool disposing)
 {
     if (!isDisposed)
     {
         _serialPort?.Close();
         _serialPort?.Dispose();
         isDisposed = true;
     }
 }
Exemple #26
0
 public void DisConnectPLC()
 {
     try
     {
         Close = true;
         curSerialPort?.Close();
     }
     catch { }
 }
Exemple #27
0
 public void Close()
 {
     try
     {
         _SerialPort?.Close();
     }
     catch (Exception)
     {
     }
 }
Exemple #28
0
        private void DisconnectInternal(bool disposing)
        {
            logger?.LogTrace("ModbusClient.Disconnect");
            if (isDisposed && !disposing)
            {
                throw new ObjectDisposedException(GetType().FullName);
            }

            if (!isStarted)
            {
                return;
            }
            isStarted = false;

            bool wasConnected = IsConnected;

            try
            {
                reconnectTcs?.TrySetResult(false);
                mainCts?.Cancel();
                reconnectTcs = null;
            }
            catch
            { }

            try
            {
                serialPort?.Close();
                serialPort?.Dispose();
                serialPort = null;
            }
            catch
            { }

            if (wasConnected)
            {
                Task.Run(() => Disconnected?.Invoke(this, EventArgs.Empty)).Forget();
            }

            if (driverModified)
            {
                try
                {
                    var rs485 = GetDriverState();
                    rs485.Flags = serialDriverFlags;
                    SetDriverState(rs485);
                    driverModified = false;
                }
                catch (Exception ex)
                {
                    logger?.LogError(ex, "ModbusClient.Disconnect failed to reset the serial driver state.");
                    throw;
                }
            }
        }
Exemple #29
0
 public void DisConnect()
 {
     try
     {
         serial?.Close();
         serial.Dispose();
     }
     catch (Exception)
     {
     }
 }
Exemple #30
0
	// Use this for initialization
	void Start () {
		sp = new SerialPort(serialPortName, 9600);
        if (sp.IsOpen)
        {
            sp.Close();
        }
        else {
            sp.Open();
            sp.ReadTimeout = 1;
        }
	}
Exemple #31
0
        private void Dispose(bool disposing)
        {
            if (disposing)
            {
                serialPort?.Close();
                serialPort?.Dispose();
                serialPort = null;
            }

            isDisposed = true;
        }
Exemple #32
0
 public override void Dispose()
 {
     if (!_isDisposed)
     {
         _isDisposed = true;
         _reciever?.Dispose();
         _serialPort?.Close();
         _serialPort?.Dispose();
         base.Dispose();
     }
 }
Exemple #33
0
        public string Query(string cmd, int sleepMs)
        {
            lock (lockDict[Name])
            {
                try
                {
                    if (_serialPort != null && !_serialPort.IsOpen)
                    {
                        _serialPort?.Open();
                    }

                    _log.Debug($"{Name} Send: {cmd}");
                    Reset();
                    _serialPort?.WriteLine(cmd);

                    Thread.Sleep(sleepMs);

                    List <int> buf = new List <int>();
                    while (_serialPort.BytesToRead > 0)
                    {
                        buf.Add(_serialPort.ReadByte());
                    }
                    string ret = System.Text.Encoding.ASCII.GetString(buf.Select(x => (byte)x).ToArray());
                    _log.Debug($"{Name} Recv: {ret}");

                    return(ret);
                }
                catch (Exception e)
                {
                    _log.Error(Name + "failed to query", e);
                    return("N/A");
                }
                finally
                {
                    if (!IsSuccessiveMode)
                    {
                        _serialPort?.Close();
                    }
                }
            }
        }
Exemple #34
0
 public override void DisConnect()
 {
     try
     {
         cancellation?.Cancel();
         serial?.Close();
         serial?.Dispose();
     }
     catch (Exception)
     {
     }
 }
Exemple #35
0
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        
        _serialPort = new SerialPort();


        _serialPort.PortName = "COM2";
        _serialPort.BaudRate = 9600;
        _serialPort.Parity = Parity.None;
        _serialPort.DataBits = 8;
        _serialPort.StopBits = StopBits.One;
        _serialPort.Handshake = Handshake.XOnXOff;

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(" " + message + " ");
                    //String.Format("{0}:{1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
        _serialPort = null;
    }
Exemple #36
0
    public static void MainS()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while(_continue)
        {
            message = Console.ReadLine();

            if(stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }
Exemple #37
0
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        _serialPort.PortName = "COM3";
        _serialPort.BaudRate = 9600;
        _serialPort.Parity = Parity.None;
        _serialPort.DataBits = 8;
        _serialPort.StopBits = StopBits.One;
        _serialPort.Handshake = Handshake.None;

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        byte[] Command = new byte[] { Convert.ToByte(1), Convert.ToByte(4), Convert.ToByte(1), Convert.ToByte(30) };

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            }
            else
            {
                _serialPort.Write(Command, 0, 4);
            }
        }
        
        _serialPort.Close();
    }
Exemple #38
0
 public static void Main(string[] args)
 {
     SerialPort sp = new SerialPort("/dev/ttyUSB0", 115200);
     sp.Open();
     try {
         byte[] b = new byte[1];
         while (true) {
             int i = Console.Read();
             if (i == -1) break;
             b[0] = (byte)i;
             sp.Write(b, 0, 1);
         }
     } catch {
         sp.Close();
     }
 }
Exemple #39
0
    public static void Main()
    {
        string name;
        string message;
        StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
        Thread readThread = new Thread(Read);

        // Создание нового объекта SerialPort с установками по умолчанию.
        _serialPort = new SerialPort();

        // Позволяем пользователю установить подходящие свойства.
        _serialPort.PortName = SetPortName(_serialPort.PortName);
        _serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate);
        _serialPort.Parity = SetPortParity(_serialPort.Parity);
        _serialPort.DataBits = SetPortDataBits(_serialPort.DataBits);
        _serialPort.StopBits = SetPortStopBits(_serialPort.StopBits);
        _serialPort.Handshake = SetPortHandshake(_serialPort.Handshake);

        // Установка таймаутов чтения/записи (read/write timeouts)
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;
        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (stringComparer.Equals("quit", message))
            {
                _continue = false;
            } else
            {
                _serialPort.WriteLine(
                String.Format("< {0} >: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }
Exemple #40
0
 public static string SendInfo(HttpListenerRequest request)
 {
     string context = "";
     Boolean succeeded = false;
     int count = 0;
     SerialPort serialPort = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
     while (!succeeded)
     {
         try
         {
             serialPort.Open();
             int cm1 = Convert.ToInt32(serialPort.ReadLine());
             int cm2 = Convert.ToInt32(serialPort.ReadLine());
             if (cm1 >= 30)
             {
                 context = "false:" + cm1.ToString();
                 Console.WriteLine(context);
             }
             else
             {
                 context = "true:" + cm1.ToString();
                 Console.WriteLine(context);
             }
             succeeded = true;
             if (cm1 != cm2)
             {
                 succeeded = false;
                 count++;
             }
             if (count>=9){
                 context = "false:outOfRange";
                 Console.WriteLine(context);
                 succeeded = true;
             }
         }
         catch (Exception ex)
         {
             context = "open error " + ex.Message;
         }
         finally
         {
             serialPort.Close();
         }
     }
     return string.Format(context);
 }
Exemple #41
0
    public static void Main()
    {
        string name;
        string message;

        var readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
        _serialPort = new SerialPort();

        // Allow the user to set the appropriate properties.
        InitializePort(_serialPort);

        // Set the read/write timeouts
        _serialPort.ReadTimeout = 500;
        _serialPort.WriteTimeout = 500;

        _serialPort.Open();
        _continue = true;
        readThread.Start();

        Console.Write("Name: ");
        name = Console.ReadLine();

        Console.WriteLine("Type QUIT to exit");

        while (_continue)
        {
            message = Console.ReadLine();

            if (message != null && "quit" ==  message.ToLowerInvariant())
            {
                _continue = false;
            }
            else
            {
                _serialPort.WriteLine(
                    String.Format("<{0}>: {1}", name, message));
            }
        }

        readThread.Join();
        _serialPort.Close();
    }
Exemple #42
0
        private void BUT_getcurrent_Click(object sender, EventArgs e)
        {
            ArdupilotMega.Comms.ICommsSerial comPort = new SerialPort();

            try
            {
                comPort.PortName = MainV2.comPort.BaseStream.PortName;
                comPort.BaudRate = MainV2.comPort.BaseStream.BaudRate;

                comPort.ReadTimeout = 4000;

                comPort.Open();

            }
            catch { CustomMessageBox.Show("Invalid ComPort or in use"); return; }

            lbl_status.Text = "Connecting";

            if (doConnect(comPort))
            {
                comPort.DiscardInBuffer();

                lbl_status.Text = "Doing Command ATI & RTI";

                ATI.Text = doCommand(comPort, "ATI1").Trim();

                RTI.Text = doCommand(comPort, "RTI1").Trim();

                RSSI.Text = doCommand(comPort, "ATI7").Trim();

                lbl_status.Text = "Doing Command ATI5";

                string answer = doCommand(comPort, "ATI5");

                string[] items = answer.Split('\n');

                foreach (string item in items)
                {
                    if (item.StartsWith("S"))
                    {
                        string[] values = item.Split(':', '=');

                        if (values.Length == 3)
                        {
                            Control[] controls = this.Controls.Find(values[0].Trim(), false);

                            if (controls.Length > 0)
                            {
                                if (controls[0].GetType() == typeof(CheckBox))
                                {
                                    ((CheckBox)controls[0]).Checked = values[2].Trim() == "1";
                                }
                                else
                                {
                                    controls[0].Text = values[2].Trim();
                                }
                            }
                        }
                    }
                }

                // remote
                foreach (Control ctl in this.Controls)
                {
                    if (ctl.Name.StartsWith("RS") && ctl.Name != "RSSI")
                        ctl.ResetText();
                }

                comPort.DiscardInBuffer();

                lbl_status.Text = "Doing Command RTI5";

                answer = doCommand(comPort, "RTI5");

                items = answer.Split('\n');

                foreach (string item in items)
                {
                    if (item.StartsWith("S"))
                    {
                        string[] values = item.Split(':', '=');

                        if (values.Length == 3)
                        {
                            Control[] controls = this.Controls.Find("R" + values[0].Trim(), false);

                            if (controls.Length == 0)
                                continue;

                            if (controls[0].GetType() == typeof(CheckBox))
                            {
                                ((CheckBox)controls[0]).Checked = values[2].Trim() == "1";
                            }
                            else if (controls[0].GetType() == typeof(TextBox))
                            {
                                ((TextBox)controls[0]).Text = values[2].Trim();
                            }
                            else if (controls[0].GetType() == typeof(ComboBox))
                            {
                                ((ComboBox)controls[0]).SelectedText = values[2].Trim();
                            }
                        }
                        else
                        {
                            Console.WriteLine("Odd config line :" + item);
                        }
                    }
                }

                // off hook
                doCommand(comPort, "ATO");

                lbl_status.Text = "Done";
            }
            else
            {

                // off hook
                doCommand(comPort, "ATO");

                lbl_status.Text = "Fail";
                CustomMessageBox.Show("Failed to enter command mode");
            }

            comPort.Close();

            BUT_savesettings.Enabled = true;
        }
	void OpenConnection(SerialPort _stream) {
		
		if (_stream != null) {
			
			if (_stream.IsOpen) {
				_stream.Close ();
				Debug.LogError ("Failed to open Serial Port, already open!");
			} else {
				_stream.Open ();
				_stream.ReadTimeout = 10;
				_stream.WriteTimeout = 40;
				
				Debug.Log ("Open Serial port1");      
			}
		}
		
	}
Exemple #44
0
    public static void Main()
    {
        string message;

        //Configuration c = new Configuration();

        //Configuration c = Configuration.Deserialize("u2wits.xml");

         StringComparer stringComparer = StringComparer.OrdinalIgnoreCase;
         Thread readThread = new Thread(Read);

        // Create a new SerialPort object with default settings.
         _uniproPort = new SerialPort();
         _witsPort = new SerialPort();

        // Allow the user to set the appropriate properties.
         if (c.uniproName == "") c.uniproName = SetPortName(_uniproPort.PortName);
         _uniproPort.PortName = c.uniproName;

         if (c.uniproBaudRate == -1) c.uniproBaudRate = SetPortBaudRate(_uniproPort.BaudRate);
         _uniproPort.BaudRate = c.uniproBaudRate;

         if (c.uniproParity == "") c.uniproParity = SetPortParity(_uniproPort.Parity);
         _uniproPort.Parity = (Parity)Enum.Parse(typeof(Parity), c.uniproParity);

         if (c.uniproDataBits == -1) c.uniproDataBits = SetPortDataBits(_uniproPort.DataBits);
         _uniproPort.DataBits = c.uniproDataBits;

         if (c.uniproStopBits == "") c.uniproStopBits = SetPortStopBits(_uniproPort.StopBits);
         _uniproPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits),c.uniproStopBits);

         if (c.uniproHandshake == "") c.uniproHandshake = SetPortHandshake(_uniproPort.Handshake);
         _uniproPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), c.uniproHandshake);

         if (c.uniproPressure == -1) c.uniproPressure = SetPressure();

         if (c.uniproDensity == -1) c.uniproDensity = SetDensity();

         if (c.uniproRate == -1) c.uniproRate = SetRate();

         if (c.uniproVolume == -1) c.uniproVolume = SetVolume();

         if (c.witsName == "") c.witsName = SetPortName(_witsPort.PortName);
         _witsPort.PortName = c.witsName;

         if (c.witsBaudRate == -1) c.witsBaudRate = SetPortBaudRate(_witsPort.BaudRate);
         _witsPort.BaudRate = c.witsBaudRate;

         if (c.witsParity == "") c.witsParity = SetPortParity(_witsPort.Parity);
         _witsPort.Parity = (Parity)Enum.Parse(typeof(Parity), c.witsParity);

         if (c.witsDataBits == -1) c.witsDataBits = SetPortDataBits(_witsPort.DataBits);
         _witsPort.DataBits = c.witsDataBits;

         if (c.witsStopBits == "") c.witsStopBits = SetPortStopBits(_witsPort.StopBits);
         _witsPort.StopBits = (StopBits)Enum.Parse(typeof(StopBits), c.witsStopBits);

         if (c.witsHandshake == "") c.witsHandshake = SetPortHandshake(_witsPort.Handshake);
         _witsPort.Handshake = (Handshake)Enum.Parse(typeof(Handshake), c.witsHandshake);

         if (c.witsHeadder == "") c.witsHeadder = SetHeadder();

         if (c.witsFotter == "") c.witsFotter = SetFotter();

         Configuration.Serialize("u2wits.xml", c);

        // Set the read/write timeouts
         _uniproPort.ReadTimeout = 500;
         _uniproPort.WriteTimeout = 500;
         _witsPort.ReadTimeout = 500;
         _witsPort.WriteTimeout = 500;

         _uniproPort.Open();
         _witsPort.Open();
         _continue = true;
         readThread.Start();

         Console.WriteLine("Type QUIT to exit");

        while (_continue)
         {
         message = Console.ReadLine();

        if (stringComparer.Equals("quit", message))
         {
         _continue = false;
         }
         }

         readThread.Join();
         _uniproPort.Close();
    }
Exemple #45
0
        private void BUT_savesettings_Click(object sender, EventArgs e)
        {
            ArdupilotMega.Comms.ICommsSerial comPort = new SerialPort();

            try
            {
                comPort.PortName = MainV2.comPort.BaseStream.PortName;
                comPort.BaudRate = MainV2.comPort.BaseStream.BaudRate;

                comPort.ReadTimeout = 4000;

                comPort.Open();

            }
            catch { CustomMessageBox.Show("Invalid ComPort or in use"); return; }

            lbl_status.Text = "Connecting";

            if (doConnect(comPort))
            {
                comPort.DiscardInBuffer();

                lbl_status.Text = "Doing Command";

                if (RTI.Text != "")
                {

                    // remote
                    string answer = doCommand(comPort, "RTI5");

                    string[] items = answer.Split('\n');

                    foreach (string item in items)
                    {
                        if (item.StartsWith("S"))
                        {
                            string[] values = item.Split(':', '=');

                            if (values.Length == 3)
                            {
                                Control[] controls = this.Controls.Find("R" + values[0].Trim(), false);

                                if (controls.Length > 0)
                                {
                                    if (controls[0].GetType() == typeof(CheckBox))
                                    {
                                        string value = ((CheckBox)controls[0]).Checked ? "1" : "0";

                                        if (value != values[2].Trim())
                                        {
                                            string cmdanswer = doCommand(comPort, "RT" + values[0].Trim() + "=" + value + "\r");

                                            if (cmdanswer.Contains("OK"))
                                            {

                                            }
                                            else
                                            {
                                                CustomMessageBox.Show("Set Command error");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (controls[0].Text != values[2].Trim() && controls[0].Text != "")
                                        {
                                            string cmdanswer = doCommand(comPort, "RT" + values[0].Trim() + "=" + controls[0].Text + "\r");

                                            if (cmdanswer.Contains("OK"))
                                            {

                                            }
                                            else
                                            {
                                                CustomMessageBox.Show("Set Command error");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // write it
                    doCommand(comPort, "RT&W");

                    // return to normal mode
                    doCommand(comPort, "RTZ");

                    Sleep(100);
                }

                comPort.DiscardInBuffer();
                {
                    //local
                    string answer = doCommand(comPort, "ATI5");

                    string[] items = answer.Split('\n');

                    foreach (string item in items)
                    {
                        if (item.StartsWith("S"))
                        {
                            string[] values = item.Split(':', '=');

                            if (values.Length == 3)
                            {
                                Control[] controls = this.Controls.Find(values[0].Trim(), false);

                                if (controls.Length > 0)
                                {
                                    if (controls[0].GetType() == typeof(CheckBox))
                                    {
                                        string value = ((CheckBox)controls[0]).Checked ? "1" : "0";

                                        if (value != values[2].Trim())
                                        {
                                            string cmdanswer = doCommand(comPort, "AT" + values[0].Trim() + "=" + value + "\r");

                                            if (cmdanswer.Contains("OK"))
                                            {

                                            }
                                            else
                                            {
                                                CustomMessageBox.Show("Set Command error");
                                            }
                                        }
                                    }
                                    else
                                    {
                                        if (controls[0].Text != values[2].Trim())
                                        {
                                            string cmdanswer = doCommand(comPort, "AT" + values[0].Trim() + "=" + controls[0].Text + "\r");

                                            if (cmdanswer.Contains("OK"))
                                            {

                                            }
                                            else
                                            {
                                                CustomMessageBox.Show("Set Command error");
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }

                    // write it
                    doCommand(comPort, "AT&W");

                    // return to normal mode
                    doCommand(comPort, "ATZ");
                }

                lbl_status.Text = "Done";
            }
            else
            {

                // return to normal mode
                doCommand(comPort, "ATZ");

                lbl_status.Text = "Fail";
                CustomMessageBox.Show("Failed to enter command mode");
            }

            comPort.Close();
        }
Exemple #46
0
        private void BUT_getcurrent_Click(object sender, EventArgs e)
        {
            ArdupilotMega.Comms.ICommsSerial comPort = new SerialPort();

            try
            {
                comPort.PortName = MainV2.comPort.BaseStream.PortName;
                comPort.BaudRate = MainV2.comPort.BaseStream.BaudRate;

                comPort.ReadTimeout = 4000;

                comPort.Open();

            }
            catch { CustomMessageBox.Show("Invalid ComPort or in use"); return; }

            lbl_status.Text = "Connecting";

            if (doConnect(comPort))
            {
                // cleanup
                doCommand(comPort, "AT&T");

                comPort.DiscardInBuffer();

                lbl_status.Text = "Doing Command ATI & RTI";

                ATI.Text = doCommand(comPort, "ATI");

                RTI.Text = doCommand(comPort, "RTI");

                    uploader.Uploader.Code freq = (uploader.Uploader.Code)Enum.Parse(typeof(uploader.Uploader.Code), doCommand(comPort, "ATI3"));
                    uploader.Uploader.Code board = (uploader.Uploader.Code)Enum.Parse(typeof(uploader.Uploader.Code), doCommand(comPort, "ATI2"));

                    ATI3.Text = freq.ToString();
                // 8 and 9
                    if (freq == uploader.Uploader.Code.FREQ_915) {
                        S8.DataSource = Range(895000, 1000, 935000);
                        RS8.DataSource = Range(895000, 1000, 935000);

                        S9.DataSource = Range(895000, 1000, 935000);
                        RS9.DataSource = Range(895000, 1000, 935000);
                    }
                    else if (freq == uploader.Uploader.Code.FREQ_433)
                    {
                        S8.DataSource = Range(414000, 100, 454000);
                        RS8.DataSource = Range(414000, 100, 454000);

                        S9.DataSource = Range(414000, 100, 454000);
                        RS9.DataSource = Range(414000, 100, 454000);
                    }
                    else if (freq == uploader.Uploader.Code.FREQ_868)
                    {
                        S8.DataSource = Range(849000, 1000, 889000);
                        RS8.DataSource = Range(849000, 1000, 889000);

                        S9.DataSource = Range(849000, 1000, 889000);
                        RS9.DataSource = Range(849000, 1000, 889000);
                    }

                    if (board == uploader.Uploader.Code.DEVICE_ID_RFD900 || board == uploader.Uploader.Code.DEVICE_ID_RFD900A)
                    {
                        S4.DataSource = Range(1, 1, 30);
                        RS4.DataSource = Range(1, 1, 30);
                    }

                RSSI.Text = doCommand(comPort, "ATI7").Trim();

                lbl_status.Text = "Doing Command ATI5";

                string answer = doCommand(comPort, "ATI5");

                string[] items = answer.Split('\n');

                foreach (string item in items)
                {
                    if (item.StartsWith("S"))
                    {
                        string[] values = item.Split(':', '=');

                        if (values.Length == 3)
                        {
                            Control[] controls = this.Controls.Find(values[0].Trim(), true);

                            if (controls.Length > 0)
                            {
                                controls[0].Enabled = true;

                                if (controls[0].GetType() == typeof(CheckBox))
                                {
                                    ((CheckBox)controls[0]).Checked = values[2].Trim() == "1";
                                }
                                else
                                {
                                    controls[0].Text = values[2].Trim();
                                }
                            }
                        }
                    }
                }

                // remote
                foreach (Control ctl in groupBox2.Controls)
                {
                    if (ctl.Name.StartsWith("RS") && ctl.Name != "RSSI")
                        ctl.ResetText();
                }

                comPort.DiscardInBuffer();

                lbl_status.Text = "Doing Command RTI5";

                answer = doCommand(comPort, "RTI5");

                items = answer.Split('\n');

                foreach (string item in items)
                {
                    if (item.StartsWith("S"))
                    {
                        string[] values = item.Split(':', '=');

                        if (values.Length == 3)
                        {
                            Control[] controls = this.Controls.Find("R" + values[0].Trim(), true);

                            if (controls.Length == 0)
                                continue;

                            controls[0].Enabled = true;

                            if (controls[0].GetType() == typeof(CheckBox))
                            {
                                ((CheckBox)controls[0]).Checked = values[2].Trim() == "1";
                            }
                            else if (controls[0].GetType() == typeof(TextBox))
                            {
                                ((TextBox)controls[0]).Text = values[2].Trim();
                            }
                            else if (controls[0].GetType() == typeof(ComboBox))
                            {
                                ((ComboBox)controls[0]).Text = values[2].Trim();
                            }
                        }
                        else
                        {
                            log.Info("Odd config line :" + item);
                        }
                    }
                }

                // off hook
                doCommand(comPort, "ATO");

                lbl_status.Text = "Done";
            }
            else
            {

                // off hook
                doCommand(comPort, "ATO");

                lbl_status.Text = "Fail";
                CustomMessageBox.Show("Failed to enter command mode");
            }

            comPort.Close();

            BUT_Syncoptions.Enabled = true;

            BUT_savesettings.Enabled = true;
        }
Exemple #47
0
        private void BUT_resettodefault_Click(object sender, EventArgs e)
        {
            ArdupilotMega.Comms.ICommsSerial comPort = new SerialPort();

            try
            {
                comPort.PortName = MainV2.comPort.BaseStream.PortName;
                comPort.BaudRate = MainV2.comPort.BaseStream.BaudRate;

                comPort.ReadTimeout = 4000;

                comPort.Open();

            }
            catch { CustomMessageBox.Show("Invalid ComPort or in use"); return; }

            lbl_status.Text = "Connecting";

            if (doConnect(comPort))
            {
                // cleanup
                doCommand(comPort, "AT&T");

                comPort.DiscardInBuffer();

                lbl_status.Text = "Doing Command ATI & AT&F";

                doCommand(comPort, "AT&F");

                doCommand(comPort, "AT&W");

                lbl_status.Text = "Reset";

                doCommand(comPort, "ATZ");

                comPort.Close();

                BUT_getcurrent_Click(sender, e);
            }
            else
            {

                // off hook
                doCommand(comPort, "ATO");

                lbl_status.Text = "Fail";
                CustomMessageBox.Show("Failed to enter command mode");
            }

            if (comPort.IsOpen)
                comPort.Close();
        }
    /***********************************************************
     * Methode: OpenConnection
     * Beschreibung: Öffnet den Port
     * Parameter: port
     * Rückgabewert: keinen
     ***********************************************************/
    public void OpenConnection(SerialPort port)
    {
        if (port != null){
            if (port.IsOpen){
                port.Close();
                print("Port schliessen, weil bereits offen");
            } else {
                port.DtrEnable = true;
                port.RtsEnable = true;
                port.WriteTimeout = 2000;
                port.ReadTimeout = 5;
                port.Open(); // COM-Port Verbindung öffnen

                print("Port geoeffnet um " + DateTime.Now + "\n");

              }
        } else {
            if (port.IsOpen)
                print("Port bereits offen!");
            else
                print("Port == null");
        }
    }
Exemple #49
0
 public static void cerrarPuerto(SerialPort puerto)
 {
     Debug.Log("Cerrando puerto... ");
     puerto.Close();
 }
    void OpenConnection(SerialPort _stream) {
		if (_stream != null) {
			if (_stream.IsOpen) {
				_stream.Close ();
				Debug.LogError ("Failed to open Serial Port, already open!");
			} else {
                try {
                    _stream.Open();
                    _stream.ReadTimeout = 10;
                    _stream.WriteTimeout = 10;
                    Debug.Log("Open Serial port1");
                }
                catch (System.IO.IOException)
                {
                    Debug.Log("error IOException can not find Arduino");
                }
			}
		}

	}
 private void portConstruct()
 {
     //Cria a porta para ser utilizada durante o projeto.
     stream = new SerialPort(nameCom,speed);
     if(stream.IsOpen){
         stream.Close();
         StartCoroutine(pauseTime(0.2f));
         stream.Open();
     }else{
         stream.Open();
     }
 }
Exemple #52
0
    /// <summary>
    /// Safely closes a serial port and its internal stream even if
    /// a USB serial interface was physically removed from the system
    /// in a reliable manner.
    /// </summary>
    /// <param name="port"></param>
    /// <param name="internalSerialStream"></param>
    /// <remarks>
    /// The <see cref="SerialPort"/> class has 3 different problems in disposal
    /// in case of a USB serial device that is physically removed:
    /// 
    /// 1. The eventLoopRunner is asked to stop and <see cref="SerialPort.IsOpen"/> 
    /// returns false. Upon disposal this property is checked and closing 
    /// the internal serial stream is skipped, thus keeping the original 
    /// handle open indefinitely (until the finalizer runs which leads to the next problem)
    /// 
    /// The solution for this one is to manually close the internal serial stream.
    /// We can get its reference by <see cref="SerialPort.BaseStream" />
    /// before the exception has happened or by reflection and getting the 
    /// "internalSerialStream" field.
    /// 
    /// 2. Closing the internal serial stream throws an exception and closes 
    /// the internal handle without waiting for its eventLoopRunner thread to finish, 
    /// causing an uncatchable ObjectDisposedException from it later on when the finalizer 
    /// runs (which oddly avoids throwing the exception but still fails to wait for 
    /// the eventLoopRunner).
    /// 
    /// The solution is to manually ask the event loop runner thread to shutdown
    /// (via reflection) and waiting for it before closing the internal serial stream.
    /// 
    /// 3. Since Dispose throws exceptions, the finalizer is not suppressed.
    /// 
    /// The solution is to suppress their finalizers at the beginning.
    /// </remarks>
    static void SafeDisconnect(SerialPort port, Stream internalSerialStream)
    {
        GC.SuppressFinalize(port);
        GC.SuppressFinalize(internalSerialStream);

        ShutdownEventLoopHandler(internalSerialStream);

        try
        {
            //s_Log.DebugFormat("Disposing internal serial stream");
            internalSerialStream.Close();
        }
        catch (Exception ex)
        {
            //s_Log.DebugFormat(
            //    "Exception in serial stream shutdown of port {0}: {1}", port.PortName, ex);
        }

        try
        {
            //s_Log.DebugFormat("Disposing serial port");
            port.Close();
        }
        catch (Exception ex)
        {
            //s_Log.DebugFormat("Exception in port {0} shutdown: {1}", port.PortName, ex);
        }
    }
    /// <summary>
    /// Initialisation of the Arduino IO-Box script. 
    /// </summary>
    /// 
    public void Start()
    {
        if ( !scriptVehicleData   ) Debug.LogError("No vehicle data collector script defined!");
        if ( !scriptConfiguration ) Debug.LogError("No simulation configuration script defined!");
        vehicleData = null;
        speedOfSound = scriptConfiguration.GetSpeedOfSound();

        serialPort = new SerialPort(modulePort, moduleSpeed, Parity.None, 8, StopBits.One);
        serialPort.Handshake   = Handshake.None;
        serialPort.RtsEnable   = false;
        serialPort.DtrEnable   = false;  // Disable DTR so NOT to reset Arduino board when connecting
        serialPort.ReadTimeout = 250;    // longer read timeout (module might have had a reset nevertheless)

        bool success = false;
        try
        {
            serialPort.Open();
        }
        catch (IOException)
        {
            serialPort = null;
        }

        if ( (serialPort != null) && serialPort.IsOpen )
        {
            int repeats = 8; // try several times to connect
            while ( (repeats-- > 0) && !success )
            {
                // send the ECHO command
                serialPort.WriteLine(CMD_ECHO);
                try
                {
                    String serialNo = serialPort.ReadLine();
                    if ( serialNo.Length > 1 )
                    {
                        Debug.Log ("Opened serial port " + modulePort + " to Arduino IO (Version: " + serialNo + ")");
                        success  = true;
                        serialPort.ReadTimeout = 50; // from now on, shorter response times, please
                        StartCoroutine(RunDiagnose());
                    }
                }
                catch (TimeoutException)
                {
                    // ignore
                }
            }
        }

        if ( !success )
        {
            Debug.LogError("Could not open serial port " + modulePort + " to the Arduino IO module.");
            if ( serialPort != null )
            {
                serialPort.Close();
                serialPort = null;
            }
        }
    }
Exemple #54
0
 public Device(string portName, int speed, int timeout)
 {
     device = new SerialPort(portName, speed, Parity.None, 8, StopBits.One);
     if (device.IsOpen)
     {
         State = EDeviceState.Busy;
         device.Close();
         State = EDeviceState.Unknown;
     }
     device.Open();
     device.ReadTimeout = timeout;
     device.WriteTimeout = timeout;
 }