Exemplo n.º 1
0
 public void Connect(string portName)
 {
     Disconnect();
     Arduino                = new ArduinoSerial(portName);
     Arduino.BytesSent     += (port, bytes) => BytesSent?.Invoke(port, bytes);
     Arduino.BytesReceived += (port, bytes) => BytesReceived?.Invoke(port, bytes);
     Arduino.Connect(false);
     _thread = new Thread(Loop);
     _thread.IsBackground = true;
     _thread.Start();
 }
Exemplo n.º 2
0
        public ConnectResult TryConnect(string portName, bool sayhello)
        {
            if (portName == "")
            {
                return(ConnectResult.InvalidArgument);
            }
            Disconnect();
            EventWaitHandle ewh    = new EventWaitHandle(false, EventResetMode.AutoReset);
            ConnectResult   result = ConnectResult.None;

            Arduino                = new ArduinoSerial(portName);
            Arduino.BytesSent     += (port, bytes) => BytesSent?.Invoke(port, bytes);
            Arduino.BytesReceived += (port, bytes) => BytesReceived?.Invoke(port, bytes);
            ArduinoSerial.StatusChangedHandler statuschanged = status =>
            {
                lock (ewh)
                {
                    if (result != ConnectResult.None)
                    {
                        return;
                    }
                    if (status == ArduinoSerial.Status.Connected || status == ArduinoSerial.Status.ConnectedUnsafe)
                    {
                        result = ConnectResult.Success;
                        ewh.Set();
                    }
                    if (status == ArduinoSerial.Status.Error)
                    {
                        result = ConnectResult.Error;
                        ewh.Set();
                    }
                }
            };
            Arduino.StatusChanged += statuschanged;
            Arduino.Connect(sayhello);
            if (!ewh.WaitOne(300) && sayhello)
            {
                Arduino.Disconnect();
                Arduino = null;
                return(ConnectResult.Timeout);
            }
            if (result != ConnectResult.Success)
            {
                Arduino.Disconnect();
                Arduino = null;
                return(result);
            }
            Arduino.StatusChanged -= statuschanged;
            _thread = new Thread(Loop);
            _thread.IsBackground = true;
            _thread.Start();
            return(ConnectResult.Success);
        }