Exemplo n.º 1
0
        private void ReadWrite_ValueUpdated(object sender, CharacteristicUpdatedEventArgs e)
        {
            var value = e.Characteristic.Value;

            _logger.Debug($"BLE receive: {ByteArrayToString(value)}");
            BytesReceived?.Invoke(this, value);
        }
Exemplo n.º 2
0
        private void EndRead(IAsyncResult result)
        {
            try
            {
                if (TcpStream == null)
                {
                    ClientDisconnected?.Invoke(this, null);
                    return;
                }

                int byteRead = TcpStream.EndRead(result);
                if (byteRead == 0)
                {
                    Close();
                    ClientDisconnected?.Invoke(this, null);
                    return;
                }
                else
                {
                    //Debug.WriteLine("Received " + byteRead + " bytes.");
                    BytesReceived?.Invoke(this, new TcpServerDataEventArgs(this, buffer, byteRead));

                    //Build string until delimeter character is detected.
                    EventHandler <MessageReceivedEventArgs> OnMessageReceived = MessageReceived;
                    for (int x = 0; x < byteRead; x++)
                    {
                        byte b = buffer[x];
                        if (b != MessageDelimiter)
                        {
                            MessageBuffer.Add(b);
                        }
                        else
                        {
                            byte[] messageBytes = MessageBuffer.ToArray();
                            Message = Encoding.ASCII.GetString(messageBytes);
                            MessageBuffer.Clear();
                            OnMessageReceived?.Invoke(this, new MessageReceivedEventArgs()
                            {
                                Client = this, ReceivedMessage = Message, ReceivedBytes = messageBytes
                            });
                            ProcessReceivedMessageCallback?.Invoke(this, Message, messageBytes);
                        }
                    }
                    BeginRead();
                }
            }
            catch (ObjectDisposedException)
            {
                ClientDisconnected?.Invoke(this, null);
                return;
            }
            catch (Exception ex)
            {
                Trace.WriteLine("Exception raised from TcpServerConnection: " + ex.Message);
                Trace.WriteLine("Client disconnected from server.");
                ClientDisconnected?.Invoke(this, null);
                return;
            }
        }
Exemplo n.º 3
0
            private void Receive()
            {
                while (IsRunning)
                {
                    byte[] bytes = m_client.Receive(ref m_receiveEndPoint);
                    BytesReceived?.Invoke(this, bytes);

                    m_buffer.AddRange(bytes);
                    ProcessBuffer();
                }
            }
Exemplo n.º 4
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.º 5
0
        public FakeTransport()
        {
            Task.Run(async() => {
                return;

                while (true)
                {
                    await Task.Delay(1000);
                    BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(GetFakeMessage())));
                }
            });
        }
Exemplo n.º 6
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);
        }
Exemplo n.º 7
0
        void Do()
        {
            try
            {
                _port.Open();
                byte[]      inBuffer  = new byte[255];
                List <byte> outBuffer = new List <byte>();
                while (true)
                {
                    // read
                    if (_port.BytesToRead > 0)
                    {
                        int count = _port.Read(inBuffer, 0, inBuffer.Length);
                        if (DEBUG_MESSAGE)
                        {
                            Debug.WriteLine($"[{_name}] " + string.Join(" ", inBuffer.Take(count).Select(b => b.ToString("X2"))));
                        }
                        lock (_inBuffer)
                            _inBuffer.AddRange(inBuffer.Take(count));
                        BytesReceived?.Invoke(_inBuffer.ToArray());
                        if (DEBUG_MESSAGE && _time != DateTime.MinValue)
                        {
                            Debug.WriteLine("Delay: " + (DateTime.Now - _time).TotalMilliseconds);
                        }
                    }

                    // write
                    lock (_outBuffer)
                    {
                        outBuffer.Clear();
                        _outBuffer.ForEach(item => outBuffer.AddRange(item));
                        _outBuffer.Clear();
                    }
                    if (outBuffer.Count > 0)
                    {
                        _port.Write(outBuffer.ToArray(), 0, outBuffer.Count);
                        lock (_inBuffer)
                            _inBuffer.Clear();
                    }
                }
            }
            finally
            {
                _port.Close();
            }
        }
Exemplo n.º 8
0
        internal virtual void OnBytesReceived(INetworkNode From, int NumberOfBytes)
        {
            if ((BytesReceived == null) || (From == null) || (NumberOfBytes <= 0))
            {
                return;
            }

            Task.Run(() =>
            {
                BytesReceived?.Invoke(this, new InternetBytesTransferredEventArgs
                {
                    Remote    = From,
                    Local     = this,
                    Direction = CommunicationDirection.Inbound,
                    NumBytes  = NumberOfBytes
                });
            });
        }
Exemplo n.º 9
0
        public async Task SendBytes(byte[] bytes)
        {
            var _ = Task.Run(async() => {
                var msg  = Encoding.ASCII.GetString(bytes);
                var cmsg = CbusMessage.FromTransportString(msg);
                switch (cmsg.OpCode)
                {
                case CbusOpCodes.QNN:
                    BytesReceived?.Invoke(this,
                                          new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB060NB60102A5080D;")));
                    BytesReceived?.Invoke(this,
                                          new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB020NB60100A5050F;")));
                    BytesReceived?.Invoke(this,
                                          new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB040NB60101A5050F;")));
                    BytesReceived?.Invoke(this,
                                          new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(":SB080NB60103A5200F;")));
                    break;

                case CbusOpCodes.RQNPN:
                    var m = cmsg as ReadNodeParameterByIndexMessage;
                    BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(new ReadNodeParameterByIndexResponseMessage {
                        NodeNumber     = m.NodeNumber,
                        ParameterIndex = 1,
                        ParameterValue = 165
                    }.TransportString)));
                    BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(new ReadNodeParameterByIndexResponseMessage {
                        NodeNumber     = m.NodeNumber,
                        ParameterIndex = 3,
                        ParameterValue = (byte)((m.NodeNumber == 256 || m.NodeNumber == 257) ? 8 : (m.NodeNumber == 258 ? 5 : 32))
                    }.TransportString)));
                    BytesReceived?.Invoke(this, new BytesReceivedEventArgs(Encoding.ASCII.GetBytes(new ReadNodeParameterByIndexResponseMessage {
                        NodeNumber     = m.NodeNumber,
                        ParameterIndex = 6,
                        ParameterValue = (byte)((m.NodeNumber == 259) ? 127 : 10)
                    }.TransportString)));
                    break;
                }
            });
        }
Exemplo n.º 10
0
        public async Task Open()
        {
            _cts  = new CancellationTokenSource();
            _port = new SerialPort(_portName);
            try {
                _port.Open();
            } catch (Exception e) {
            }

            var buffer = new byte[30];

            while (!_cts.IsCancellationRequested)
            {
                try {
                    var read = await _port.BaseStream.ReadAsync(buffer, 0, buffer.Length, _cts.Token);

                    BytesReceived?.Invoke(this, new BytesReceivedEventArgs(buffer.Take(read).ToArray()));
                } catch (TaskCanceledException) {
                    //ok
                } catch (Exception e) {
                }
            }
        }
Exemplo n.º 11
0
    void OnDataReceive(ArduinoBuffer data)
    {
        if (_command != data.cmd)
        {
            return;
        }
        if (_dataType != data.dataType)
        {
            return;
        }

        if (_dataType == ArduinoDataType.Bytearray)
        {
            byte[] ba = data.buffer;
            _bytesReceived.Invoke(ba);
        }
        else if (_dataType == ArduinoDataType.Bool)
        {
            bool b = BitConverter.ToBoolean(data.buffer, 0);
            _boolReceived.Invoke(b);
        }
        else if (_dataType == ArduinoDataType.Int)
        {
            int i = BitConverter.ToInt32(data.buffer, 0);
            _intReceived.Invoke(i);
        }
        else if (_dataType == ArduinoDataType.Float)
        {
            float f = BitConverter.ToSingle(data.buffer, 0);
            _floatReceived.Invoke(f);
        }
        else if (_dataType == ArduinoDataType.String)
        {
            string s = System.Text.Encoding.ASCII.GetString(data.buffer);
            _stringReceived.Invoke(s);
        }
        else if (_dataType == ArduinoDataType.Int2)
        {
            Vector2Int v = new Vector2Int(
                BitConverter.ToInt32(data.buffer, 0),
                BitConverter.ToInt32(data.buffer, 4));
            _int2Received.Invoke(v);
        }
        else if (_dataType == ArduinoDataType.Int3)
        {
            Vector3Int v = new Vector3Int(
                BitConverter.ToInt32(data.buffer, 0),
                BitConverter.ToInt32(data.buffer, 4),
                BitConverter.ToInt32(data.buffer, 8));
            _int3Received.Invoke(v);
        }
        else if (_dataType == ArduinoDataType.Float2)
        {
            Vector2 v = new Vector2(
                BitConverter.ToSingle(data.buffer, 0),
                BitConverter.ToSingle(data.buffer, 4));
            _float2Received.Invoke(v);
        }
        else if (_dataType == ArduinoDataType.Float3)
        {
            Vector3 v = new Vector3(
                BitConverter.ToSingle(data.buffer, 0),
                BitConverter.ToSingle(data.buffer, 4),
                BitConverter.ToSingle(data.buffer, 8));
            _float3Received.Invoke(v);
        }
        else if (_dataType == ArduinoDataType.Float4)
        {
            Vector4 v = new Vector4(
                BitConverter.ToSingle(data.buffer, 0),
                BitConverter.ToSingle(data.buffer, 4),
                BitConverter.ToSingle(data.buffer, 8),
                BitConverter.ToSingle(data.buffer, 12));
            _float4Received.Invoke(v);
        }
    }
 protected virtual void OnBytesReceived(BytesReceivedEventArgs e) => BytesReceived?.Invoke(this, e);
Exemplo n.º 13
0
 private void OnBytesReceived(UDPPacketReceivedEventArgs e)
 {
     BytesReceived?.Invoke(this, e);
 }
Exemplo n.º 14
0
 protected internal override void RaiseBytesReceived(IClientInfo client, byte[] data)
 {
     BytesReceived?.Invoke(client, data);
 }
 protected virtual void OnBytesReceived(byte[] e)
 {
     BytesReceived?.Invoke(this, e);
 }
Exemplo n.º 16
0
 protected void RaiseBytesReceived(byte[] message)
 {
     BytesReceived?.Invoke(this, message);
 }