Exemplo n.º 1
0
        private void OnNewDataAvailable(byte[] frame)
        {
            ArrayList data = new ArrayList(frame);

            do
            {
                try
                {
                    SPPMessage msg = SPPMessage.DecodeMessage(data.OfType <byte>().ToArray());

                    MessageReceived?.Invoke(this, msg);

                    if (msg.TotalPacketSize >= data.Count)
                    {
                        break;
                    }
                    data.RemoveRange(0, msg.TotalPacketSize);
                }
                catch (InvalidDataException e)
                {
                    InvalidDataException?.Invoke(this, e);
                }
            } while (data.Count > 0);

            NewDataAvailable?.Invoke(this, frame);
        }
Exemplo n.º 2
0
 public AASService()
 {
     Program.NewDataAvailable += (s, a) =>
     {
         NewDataAvailable?.Invoke(s, a);
     };
 }
Exemplo n.º 3
0
 public AASService()
 {
     Program.NewDataAvailable += (s, a) =>
     {
         NewDataAvailable?.Invoke(this, EventArgs.Empty);
     };
 }
Exemplo n.º 4
0
        public AASService()
        {
            // buildTree();
            // NewDataAvailable?.Invoke(this, EventArgs.Empty);

            Program.NewDataAvailable += (s, a) =>
            {
                // buildTree();
                NewDataAvailable?.Invoke(this, a);
            };
        }
Exemplo n.º 5
0
 public void GetData()
 {
     if (!disposing && !TaskRunning)
     {
         TaskRunning = true;
         float tmpdata;
         tmpdata = DataHandler();
         DateTime tmptime = DateTime.Now;
         CurrentValue = new TimeDataPair(tmptime, tmpdata);
         if (tm.Interval != CurrentInterval)
         {
             tm.Interval = CurrentInterval;
         }
         TaskRunning = false;
         NewDataAvailable?.Invoke();
     }
 }
Exemplo n.º 6
0
        /// <summary>
        /// Handler that is called everytime UART (Serial) data is received
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Port_DataReceived_Handler(object sender, SerialDataReceivedEventArgs e)
        {
            // If we did not receive the ACK bytes YET --> check if got them now
            if (!IsConnected)
            {
                HandleACK();
            }

            // Read out RAW motion Data
            var data = new byte[12];

            BlockingRead(data, 0, 12);

            // Convert to actual values
            Axis_X = BitConverter.ToInt32(data, 0);
            Axis_Y = BitConverter.ToInt32(data, 4);
            Axis_Z = BitConverter.ToInt32(data, 8);

            // Inform User that Data is now available
            NewDataAvailable?.Invoke(this, EventArgs.Empty);
        }
        private async void BluetoothServiceLoop()
        {
            while (true)
            {
                try
                {
                    _loopCancellation.Token.ThrowIfCancellationRequested();
                    Task.Delay(100).Wait(_loopCancellation.Token);
                }
                catch (OperationCanceledException)
                {
                    IsStreamConnected = false;
                    Log.Debug("WindowsRT.BluetoothService: BluetoothServiceLoop cancelled.");
                    return;
                }

                try
                {
                    Stream?incoming = null;
                    if (_socket == null)
                    {
                        Log.Error($"WindowsRT.BluetoothService: StreamSocket is null");
                        BluetoothErrorAsync?.Invoke(this,
                                                    new BluetoothException(BluetoothException.ErrorCodes.ReceiveFailed,
                                                                           "Cannot retrieve incoming data stream. Device probably disconnected."));
                        await DisconnectAsync();

                        return;
                    }

                    lock (_socket)
                    {
                        incoming = _socket?.InputStream.AsStreamForRead();
                    }

                    if (incoming == null)
                    {
                        Log.Error($"WindowsRT.BluetoothService: Cannot retrieve incoming data stream");
                        BluetoothErrorAsync?.Invoke(this,
                                                    new BluetoothException(BluetoothException.ErrorCodes.ReceiveFailed,
                                                                           "Cannot retrieve incoming data stream. Device probably disconnected."));
                        await DisconnectAsync();

                        return;
                    }

                    byte[] buffer = new byte[10000];

                    var b = incoming.Read(buffer, 0, buffer.Length);
                    if (b == 0)
                    {
                        // EOS
                        Log.Warning("WindowsRT.BluetoothService: End of stream. Connection closed by remote host");
                        break;
                    }

                    buffer = buffer.ShrinkTo(b);

                    NewDataAvailable?.Invoke(this, buffer);
                }
                catch (Exception ex)
                {
                    if (_socket == null)
                    {
                        switch ((uint)ex.HResult)
                        {
                        // the user closed the socket.
                        case 0x80072745:

                            BluetoothErrorAsync?.Invoke(this, new BluetoothException(
                                                            BluetoothException.ErrorCodes.ReceiveFailed,
                                                            "Disconnect triggered by remote device"));
                            break;

                        case 0x800703E3:
                            Log.Debug(
                                "WindowsRT.BluetoothService: The I/O operation has been aborted because of either a thread exit or an application request");
                            break;
                        }
                    }
                    else
                    {
                        BluetoothErrorAsync?.Invoke(this, new BluetoothException(
                                                        BluetoothException.ErrorCodes.ReceiveFailed,
                                                        "Failed to read stream: " + ex.Message));
                    }

                    await DisconnectAsync();
                }
            }
        }
Exemplo n.º 8
0
        private void BluetoothServiceLoop()
        {
            Stream?peerStream = null;

            while (true)
            {
                try
                {
                    _cancelSource.Token.ThrowIfCancellationRequested();
                    Task.Delay(50).Wait(_cancelSource.Token);
                }
                catch (OperationCanceledException)
                {
                    peerStream?.Close();
                    _client?.Close();
                    throw;
                }

                if (_client == null || !_client.Connected)
                {
                    continue;
                }

                if (peerStream == null)
                {
                    lock (_btlock)
                    {
                        if (!_client.Connected)
                        {
                            continue;
                        }

                        peerStream = _client.GetStream();
                    }

                    RfcommConnected?.Invoke(this, EventArgs.Empty);
                    continue;
                }


                var available = _client.Available;
                if (available > 0 && peerStream.CanRead)
                {
                    byte[] buffer = new byte[available];
                    try
                    {
                        peerStream.Read(buffer, 0, available);
                    }
                    catch (SocketException ex)
                    {
                        Log.Error($"Windows.BluetoothService: BluetoothServiceLoop: SocketException thrown while reading from socket: {ex.Message}. Cancelled.");
                        BluetoothErrorAsync?.Invoke(this, new BluetoothException(BluetoothException.ErrorCodes.ReceiveFailed, ex.Message));
                        return;
                    }
                    catch (IOException ex)
                    {
                        Log.Error($"Windows.BluetoothService: BluetoothServiceLoop: IOException thrown while writing to socket: {ex.Message}. Cancelled.");
                        BluetoothErrorAsync?.Invoke(this, new BluetoothException(BluetoothException.ErrorCodes.ReceiveFailed, ex.Message));
                    }

                    if (buffer.Length > 0)
                    {
                        NewDataAvailable?.Invoke(this, buffer);
                    }
                }

                lock (TransmitterQueue)
                {
                    if (TransmitterQueue.Count <= 0)
                    {
                        continue;
                    }
                    if (!TransmitterQueue.TryDequeue(out var raw))
                    {
                        continue;
                    }
                    try
                    {
                        peerStream.Write(raw, 0, raw.Length);
                    }
                    catch (SocketException ex)
                    {
                        Log.Error($"Windows.BluetoothService: BluetoothServiceLoop: SocketException thrown while writing to socket: {ex.Message}. Cancelled.");
                        BluetoothErrorAsync?.Invoke(this, new BluetoothException(BluetoothException.ErrorCodes.SendFailed, ex.Message));
                    }
                    catch (IOException ex)
                    {
                        Log.Error($"Windows.BluetoothService: BluetoothServiceLoop: IOException thrown while writing to socket: {ex.Message}. Cancelled.");
                        BluetoothErrorAsync?.Invoke(this, new BluetoothException(BluetoothException.ErrorCodes.SendFailed, ex.Message));
                    }
                }
            }
        }
Exemplo n.º 9
0
 public static void signalNewData(int mode, int sessionNumber = 0)
 {
     signalNewDataMode = mode;
     NewDataAvailable?.Invoke(null, new NewDataAvailableArgs(mode, sessionNumber));
 }
Exemplo n.º 10
0
 /// <summary>
 /// Event invocator for the <see cref="NewDataAvailable"/> event
 /// </summary>
 public void OnNewDataAvailable()
 {
     NewDataAvailable?.Invoke(this, EventArgs.Empty);
 }
Exemplo n.º 11
0
 protected void SignalNewData(DataType dataType, object data)
 {
     NewDataAvailable?.Invoke(this, new CommunicationData(dataType, data));
 }
Exemplo n.º 12
0
 public static void signalNewData(int mode)
 {
     signalNewDataMode = mode;
     NewDataAvailable?.Invoke(null, EventArgs.Empty);
 }
Exemplo n.º 13
0
        private void StatusUpdateInternal()
        {
            PackageStatusRequest requestMessage;

            PeerOverallStatus[] peersToUpdate;
            var elapsed = stopwatch.Elapsed;
            var elapsedThresholdRegular = elapsed.Subtract(settings.PeerUpdateStatusTimer);
            var elapsedThresholdFast    = elapsed.Subtract(settings.PeerUpdateStatusFastTimer);

            // prepare list of peers and list of packages we're interested in
            lock (syncLock)
            {
                if (states.Count == 0)
                {
                    return;
                }

                peersToUpdate = peers.Values
                                .Where(c => c.LastUpdateTry < (c.UseFastUpdate ? elapsedThresholdFast : elapsedThresholdRegular) && c.DoUpdateStatus)
                                .ToArray();

                if (peersToUpdate.Length == 0)
                {
                    return;
                }

                foreach (var item in peersToUpdate)
                {
                    item.UseFastUpdate = false; // reset
                    item.LastUpdateTry = elapsed;
                }

                requestMessage = new PackageStatusRequest()
                {
                    PackageIds = states.Keys.ToArray()
                };
            }

            logger.LogTrace("Sending update request for {0} package(s) to {1} peer(s).", requestMessage.PackageIds.Length, peersToUpdate.Length);

            // build blocks to process and link them
            var fetchClientStatusBlock = new TransformBlock <PeerOverallStatus, (PeerOverallStatus peer, PackageStatusResponse result, bool succes)>(
                p => FetchClientStatusAsync(p, requestMessage),
                new ExecutionDataflowBlockOptions()
            {
                MaxDegreeOfParallelism = ConcurrentStatusUpdates
            }
                );

            var applyClientStatusBlock = new ActionBlock <(PeerOverallStatus peer, PackageStatusResponse result, bool success)>(
                p => ApplyClientStatus(p, requestMessage),
                new ExecutionDataflowBlockOptions()
            {
                MaxDegreeOfParallelism = 1
            }
                );

            fetchClientStatusBlock.LinkTo(applyClientStatusBlock, new DataflowLinkOptions()
            {
                PropagateCompletion = true
            });

            // send
            foreach (var peerToUpdate in peersToUpdate)
            {
                fetchClientStatusBlock.Post(peerToUpdate);
            }
            fetchClientStatusBlock.Complete();
            applyClientStatusBlock.Completion.Wait();


            // apply downloads
            NewDataAvailable?.Invoke();
        }
Exemplo n.º 14
0
 public void OnNewDataAvailable()
 {
     NewDataAvailable?.Invoke();
 }