Example #1
0
 private void port_RawDataReceived(object sender, RawDataReceivedEventArgs e)
 {
     if (!IsCommandMode)
     {
         RawDataReceived.Rise(this, e);
     }
 }
Example #2
0
        protected override object ProcessMessage(string message)
        {
            DateTime timestamp = DateTime.Now;

            RawDataReceived?.Invoke(this, new RawDataReceivedEventArgs(message, timestamp));

            if (message.Length > 4)
            {
                if (message[0] == '4')
                {
                    byte mode = (byte)message[1].GetHexVal();
                    if (mode == (byte)Mode)
                    {
                        byte pid = (byte)message.Substring(2, 2).GetHexVal();
                        Type dataType;
                        if (DataTypeCache.TryGetValue(pid, out dataType))
                        {
                            IOBDData obdData = (IOBDData)Activator.CreateInstance(dataType);
                            obdData.Load(message.Substring(4, message.Length - 4));

                            IDataEventManager dataEventManager;
                            if (_dataReceivedEventHandlers.TryGetValue(dataType, out dataEventManager))
                            {
                                dataEventManager.RaiseEvent(this, obdData, timestamp);
                            }

                            return(obdData);
                        }
                    }
                }
            }
            return(null);
        }
Example #3
0
        private void Update()
        {
            while (IsRunning)
            {
                try
                {
                    if (_inputStream == null)
                    {
                        ConnectDevice();
                    }

                    int count = _inputStream.Read(_buffer, 0, _buffer.Length);
                    if (count > 0)
                    {
                        RawDataReceived?.Invoke(this, new RawDataReceivedEventArgs(_hidDevice, _buffer, count));
                    }
                }
                catch (TimeoutException)
                { /* gogo do something with your device :p */ }
                catch
                {
                    _inputStream?.Dispose();
                    _inputStream = null;
                    Thread.Sleep(1000);
                }
            }
        }
Example #4
0
        private void MqttClientOnApplicationMessageReceived(MqttApplicationMessageReceivedEventArgs e)
        {
            Logger.Debug("OnMessage received. Enqueuing message...");

            string topic = e.ApplicationMessage.Topic;

            byte[] payload = e.ApplicationMessage.Payload;

            if (Settings.Client.RawDataMode)
            {
                RawDataReceived?.Invoke(this, new RawDataReceivedEventArgs(payload, topic));
            }
            else if (m_MessageQueue == null)
            {
                Logger.Debug("Message received without initialized queue!");
            }
            else
            {
                m_MessageQueue.Enqueue(new DecodeMessage.MqttMessage
                {
                    Topic   = topic,
                    Payload = payload
                }
                                       );
            }
        }
Example #5
0
        protected override object ProcessMessage(string message)
        {
            if (message == null)
            {
                return(null);
            }

            DateTime timestamp = DateTime.Now;

            RawDataReceived?.Invoke(this, new RawDataReceivedEventArgs(message, timestamp));

            if (message.Length > 4)
            {
                // DarthAffe 15.08.2020: Splitted messages are prefixed with 0: (first chunk) and 1: (second chunk)
                // DarthAffe 15.08.2020: They also seem to be always preceded by a '009'-message, but since that's to short to be processed it should be safe to ignore.
                // DarthAffe 15.08.2020: Since that behavior isn't really documented (at least I wasn't able to find it) that's all trial and error and might not work for all pids with long results.
                if (message[1] == ':')
                {
                    if (message[0] == '0')
                    {
                        MessageChunk = message.Substring(2, message.Length - 2);
                    }
                    else if (message[0] == '1')
                    {
                        string fullMessage = MessageChunk + message.Substring(2, message.Length - 2);
                        MessageChunk = null;
                        return(ProcessMessage(fullMessage));
                    }
                }
                else if (message[0] == '4')
                {
                    byte mode = (byte)message[1].GetHexVal();
                    if (mode == (byte)Mode)
                    {
                        byte pid = (byte)message.Substring(2, 2).GetHexVal();
                        if (DataTypeCache.TryGetValue(pid, out Type dataType))
                        {
                            IOBDData obdData = (IOBDData)Activator.CreateInstance(dataType);
                            obdData.Load(message.Substring(4, message.Length - 4));

                            if (DataReceivedEventHandlers.TryGetValue(dataType, out IDataEventManager dataEventManager))
                            {
                                dataEventManager.RaiseEvent(this, obdData, timestamp);
                            }

                            if (DataReceivedEventHandlers.TryGetValue(typeof(IOBDData), out IDataEventManager genericDataEventManager))
                            {
                                genericDataEventManager.RaiseEvent(this, obdData, timestamp);
                            }

                            return(obdData);
                        }
                    }
                }
            }
            return(null);
        }
Example #6
0
 /// <summary>
 /// Process chunk read
 /// </summary>
 void ProcessChunk(double[,] buffer, int num)
 {
     for (int s = 0; s < num; s++)
     {
         IBFSample nextSample = new BFSampleImplementation(BoardId);
         nextSample.InitializeFromSample(buffer.GetRow(s));
         RawDataReceived?.Invoke(this, new BFSampleEventArgs(nextSample));
         LogRawDataProcessingPerformance(nextSample);
     }
 }
Example #7
0
        /// <summary>
        /// Handles receiving packets. Should be called in a new Task to avoid blocking the main thread.
        /// </summary>
        public override void ReceiveLoop()
        {
            while (true)
            {
                // Wait to receive something on the socket.
                EndPoint sender = null;
                byte[]   data   = Receive(RecvBuffer, RecvBuffer.Length, out sender);

                // Invoke the data received event.
                IPEndPoint endPoint = sender as IPEndPoint;
                RawDataReceived?.Invoke(data, SEndPoint.Create(endPoint.Address, endPoint.Port));
            }
        }
Example #8
0
        /// <summary>
        /// raises event depends on the received data and format
        /// </summary>
        /// <param name="data"></param>
        private void ProcessReceivedData(string data)
        {
            MqttMessage msg;

            if (MqttMessage.TryParse(data, out msg))
            {
                // nothing on waitlist or response is not expected by waiting tasks
                if (_waitList.Count == 0 || !ReleaseWait(msg))
                {
                    CollectPortInformation(msg);
                    MessageReceived?.Invoke(this, new MessageEventArgs(msg));
                }
            }
            else
            {
                RawDataReceived?.Invoke(this, new DataEventArgs(data));
            }
        }
Example #9
0
 /// <summary>
 /// Calls the Notification.MessageReceived callback
 /// </summary>
 /// <param name="message"></param>
 protected virtual void OnMessageReceived(byte[] message)
 {
     RawDataReceived?.Invoke(this, message);
     if (message != null && message.Length > 0 && UseCompression)
     {
         try
         {
             var msg = message.FromCompressed();
             message = msg;
         }
         catch (System.IO.InvalidDataException)
         {
             //ignore - the public key could be sent uncompressed
             //so just pass it on as is
         }
         catch (Exception e)
         {
             System.Diagnostics.Debug.WriteLine(e.ToString());
             System.Diagnostics.Debugger.Break();
         }
     }
     DataReceived?.Invoke(this, message);
 }
Example #10
0
        private void serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (!pendingClose)
            {
                while (Interlocked.CompareExchange(ref readLock, 1, 0) != 0)
                {
                    Thread.SpinWait(1);
                }

                int    bytesToRead = serialPort.BytesToRead;
                byte[] buffer      = new byte[bytesToRead];
                serialPort.Read(buffer, 0, bytesToRead);

                Interlocked.Decrement(ref readLock);

                RawDataReceived.Rise(this, new RawDataReceivedEventArgs(buffer));

                if (!IsRawModeOnly)
                {
                    //OnIncomingData(buffer);
                    OnIncomingDataEx(Encoding.ASCII.GetString(buffer));
                }
            }
        }
Example #11
0
        protected override object ProcessMessage(string message)
        {
            if (message == null)
            {
                return(null);
            }

            DateTime timestamp = DateTime.Now;

            RawDataReceived?.Invoke(this, new RawDataReceivedEventArgs(message, timestamp));

            if (message.ToUpper() == "CAN ERROR")
            {
                CanError?.Invoke(this, new CanErrorEventArgs {
                    Message = message
                });
            }
            else if (message.Length > 4)
            {
                // DarthAffe 15.08.2020: Splitted messages are prefixed with 0: (first chunk) and 1: (second chunk)
                // DarthAffe 15.08.2020: They also seem to be always preceded by a '009'-message, but since that's to short to be processed it should be safe to ignore.
                // DarthAffe 15.08.2020: Since that behavior isn't really documented (at least I wasn't able to find it) that's all trial and error and might not work for all pids with long results.
                if (message[1] == ':')
                {
                    if (message[0] == '0')
                    {
                        MessageChunk = message.Substring(2, message.Length - 2);
                    }
                    else if (message[0] == '1')
                    {
                        string fullMessage = MessageChunk + message.Substring(2, message.Length - 2);
                        MessageChunk = null;
                        return(ProcessMessage(fullMessage));
                    }
                }
                else
                {
                    string resModeStr = message.Substring(0, 2);
                    try
                    {
                        byte resMode = Convert.ToByte(resModeStr, 16);

                        if (resMode == GetModeByte() + 0x40 || ModeCache.ContainsValue((byte)(resMode - 0x40)))
                        {
                            byte pid     = (byte)message.Substring(2, 2).GetHexVal();
                            int  longPid = message.Substring(2, 4).GetHexVal();
                            if (DataTypeCache.TryGetValue(longPid, out Type dataType) || DataTypeCache.TryGetValue(pid, out dataType))
                            {
                                if (ModeCache.TryGetValue(dataType, out var modeByte) && (modeByte ?? GetModeByte()) != resMode - 0x40)
                                {
                                    // Mode didn't match PID
                                    return(null);
                                }

                                IOBDData obdData = (IOBDData)Activator.CreateInstance(dataType);
                                bool     isLong  = obdData.PID == longPid;
                                int      start   = isLong ? 6 : 4;
                                obdData.Load(message.Substring(start, message.Length - start));

                                if (DataReceivedEventHandlers.TryGetValue(dataType, out IDataEventManager dataEventManager))
                                {
                                    dataEventManager.RaiseEvent(this, obdData, timestamp);
                                }

                                if (DataReceivedEventHandlers.TryGetValue(typeof(IOBDData), out IDataEventManager genericDataEventManager))
                                {
                                    genericDataEventManager.RaiseEvent(this, obdData, timestamp);
                                }

                                return(obdData);
                            }
                        }
                    }
                    catch (FormatException)
                    {
                        // Ignore format exceptions from convert
                    }
                }
            }

            return(null);
        }
Example #12
0
 private static void OnRawDataReceived(byte[] receivedbytes, IPEndPoint ip)
 {
     RawDataReceived?.Invoke(receivedbytes, ip);
 }
Example #13
0
 protected virtual void OnRawDataReceived(string e)
 {
     RawDataReceived?.Invoke(this, e);
 }
Example #14
0
 protected void OnDataReceived(ushort[] data)
 {
     RawDataReceived?.Invoke(this, data);
 }
Example #15
0
 /// <summary>
 /// Calls the RawDataRecieved multi-cast delegate with potentially compressed data
 /// </summary>
 /// <param name="bytes">The received data</param>
 /// <returns>The raw data, potentially compressed, received from the remote machine</returns>
 /// <remarks>If UseCompression is True, this data will be in a compressed state</remarks>
 protected virtual byte[] OnRawDataReceived(byte[] bytes)
 {
     RawDataReceived?.Invoke(this, bytes);
     return(bytes);
 }
        private void parseData(string data)
        {
            data = data.Replace("\r", string.Empty);

            try
            {
                // Forward raw data
                RawDataReceived?.Invoke(data);

                // Result of a command
                if (data.Contains(':'))
                {
                    var cmd    = data.Substring(0, 2);
                    var result = data.Substring(4);

                    switch (cmd)
                    {
                    case "PS":     // Received status summary, change it back to continues status
                        if (result.Equals("1"))
                        {
                            SendCommand("PS", "0");
                        }
                        break;

                    default:     // Other results, publish result to MQTT
                        Logger.LogDebugMessage("Received ACK from OTGW for command {0}, result {1}", cmd, result);

                        CmdResponseReceived?.Invoke(cmd, result);
                        break;
                    }

                    return;
                }

                // Can parse the message, make sure it's 9 characters long
                if (data.Length == 9)
                {
                    var target  = data.Substring(0, 1); // B, T, A, R, E
                    var type    = data.Substring(1, 1);
                    var id      = int.Parse(data.Substring(3, 2), System.Globalization.NumberStyles.HexNumber);
                    var payload = data.GetLast(4);

                    if (target.Equals("B") || target.Equals("T") || target.Equals("A"))
                    {
                        if (type.Equals("1") || type.Equals("4") || type.Equals("C") || type.Equals("9"))
                        {
                            if (openthermIds.ContainsKey(id))
                            {
                                switch (openthermIdsTypes[id])
                                {
                                case "flag8":
                                    if (!target.Equals("A"))
                                    {
                                        values[id] = Convert.ToString(
                                            int.Parse(payload.Substring(0, 2), System.Globalization.NumberStyles.HexNumber),
                                            2).PadLeft(8, '0')
                                                     + "/" +
                                                     Convert.ToString(
                                            int.Parse(payload.Substring(2, 2), System.Globalization.NumberStyles.HexNumber),
                                            2).PadLeft(8, '0');

                                        values[1001] = (values[id] as string).Substring(12, 1);    // Cooling room MsgID=0, LWB, 00000000/00010000
                                        values[1002] = (values[id] as string).Substring(13, 1);    // OpenTherm MsgID=0, LWB, 00000000/00001000
                                        values[1003] = (values[id] as string).Substring(15, 1);    // Heating up room - OpenTherm MsgID=0, LWB, 0000 0100
                                        values[1004] = (values[id] as string).Substring(14, 1);    // Heating up boiler OpenTherm MsgID=0, LWB, 0000 0010
                                        values[1005] = (values[id] as string).Substring(6, 1);     // OpenTherm MsgID=0, HGB, 0000 0100
                                        values[1006] = (values[id] as string).Substring(16, 1);    // Fault indication, LWB 0000 00001
                                    }
                                    break;

                                case "f8.8":
                                    values[id] = Math.Round((float)int.Parse(payload, System.Globalization.NumberStyles.HexNumber) / 256, 2);

                                    break;

                                case "u16":
                                    values[id] = int.Parse(payload, System.Globalization.NumberStyles.HexNumber);
                                    break;
                                }

                                foreach (var key in openthermIds.Keys)
                                {
                                    if (values[key] == null || values[key].Equals(previousValues[key]))
                                    {
                                        continue;
                                    }
                                    previousValues[key] = values[key];

                                    DataReceived?.Invoke(key, openthermIds[key], values[key]);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Logger.LogDebugMessage("An error occurred parsing message '{0}'", data);
                Logger.LogException(e);
            }
        }
 public void HandleRawData(PeerConnection sender, byte[] data)
 {
     RawDataReceived?.Invoke(sender, data);
 }
Example #18
0
 protected void OnRawDataReceived(byte[] data)
 {
     RawDataReceived?.Invoke(this, new RawDataEventArgs(Phase, data));
 }