public VehicleDataPacket Read() { ValueSet valuesToSend = new ValueSet(); valuesToSend.Add("ADDRESS", (int)_simulatedDevice); valuesToSend.Add("REQUEST", ""); ValueSet dataReceived = Task.Run(() => _simulatorCommunication.RequestDataAsync(valuesToSend)).GetAwaiter().GetResult(); //TODO: (ref. issue #4) This is a temporary hack that blocks the async method. WARNING MAY CAUSE ISSUES!. See if Read() can be rewritten to be async. See Figure 7 "The Thread Pool Hack" on https://msdn.microsoft.com/en-us/magazine/mt238404.aspx NewDataReceived?.Invoke(this, EventArgs.Empty); return(ConvertData(dataReceived)); }
private void ReadCallback(IAsyncResult ar) { //get the client from the asynchronous state object TConnection C = null; try { C = AllConnections[(string)ar.AsyncState]; } catch { ReportError?.Invoke("ReadCallback received from a client that is no longer in the database", ""); return; } int bytesread = 0; try { bytesread = C.ConnectionSocket.EndReceive(ar); //acknowledge the data receipt } catch { ReportError?.Invoke("EndReceive failed during ReadCallback", C.Address); } if (bytesread > 0) { C.ConnStats.LastComm.Restart(); C.ConnStats.Receivedpackets++; //call external function to process the data NewDataReceived?.Invoke(C.Address, C.IncomingData, bytesread); C.NrReceivedBytes = bytesread; C.DataReceived = true; //call the data processing method of the connection itself C.ProcessData(); C.ProcessDataAction?.Invoke(); //set the socket back to listening mode try { C.ConnectionSocket.BeginReceive(C.IncomingData, 0, C.IncomingData.Length, 0, new AsyncCallback(ReadCallback), C.Address); } catch { ReportError?.Invoke("BeginReceive failed during ReadCallback", C.Address); } } }
/// <summary> /// Init driver communication - means autorefresh of the messages /// </summary> /// <param name="nft"></param> /// <returns></returns> public override async Task Init(INFT nft) { CancelToken = CancelTokenSource.Token; _ = Task.Run(async() => { IsRunning = true; var quit = false; while (!quit) { if (CancelToken.IsCancellationRequested) { quit = true; } try { var res = await RequestNewMessageFromAPI(); if (res.Item1 && !string.IsNullOrEmpty(res.Item2.id)) { if (res.Item2.id != lastmessageid) { NewDataReceived?.Invoke(this, JsonConvert.SerializeObject(res.Item2)); lastmessageid = res.Item2.id; } } } catch (Exception ex) { Console.WriteLine("Cannot obtain new message from the HARDWARIO Cloud API. " + ex.Message); } await Task.Delay(CommonConnParams.CommonRefreshInterval); } }, CancelToken); IsRunning = false; }
internal void OnNewDataReceived() { NewDataReceived?.Invoke(); }
private BluetoothImpl() { try { if (PlatformUtils.IsWindows && SettingsProvider.Instance.UseBluetoothWinRT && PlatformUtils.IsWindowsContractsSdkSupported) { Log.Debug("BluetoothImpl: Using WinRT.BluetoothService"); _backend = new Bluetooth.WindowsRT.BluetoothService(); } #if WindowsNoARM else if (PlatformUtils.IsWindows) { Log.Debug("BluetoothImpl: Using Windows.BluetoothService"); _backend = new Bluetooth.Windows.BluetoothService(); } #else else if (PlatformUtils.IsWindows && PlatformUtils.IsWindowsContractsSdkSupported) { Log.Debug("BluetoothImpl: Using WinRT.BluetoothService (ARM)"); _backend = new Bluetooth.WindowsRT.BluetoothService(); } #endif else if (PlatformUtils.IsLinux) { Log.Debug("BluetoothImpl: Using Linux.BluetoothService"); _backend = new Bluetooth.Linux.BluetoothService(); } else { Log.Warning("BluetoothImpl: Using Dummy.BluetoothService"); _backend = new Dummy.BluetoothService(); } } catch (PlatformNotSupportedException) { Log.Error("BluetoothImpl: Critical error while preparing bluetooth backend"); Log.Error("BluetoothImpl: Backend swapped out with non-functional dummy object in order to prevent crash"); _backend = new Dummy.BluetoothService(); } _cancelSource = new CancellationTokenSource(); _loop = Task.Run(DataConsumerLoop, _cancelSource.Token); _backend.Connecting += (sender, args) => Connecting?.Invoke(this, EventArgs.Empty); _backend.NewDataAvailable += OnNewDataAvailable; _backend.NewDataAvailable += (sender, bytes) => NewDataReceived?.Invoke(this, bytes); _backend.BluetoothErrorAsync += (sender, exception) => OnBluetoothError(exception); _backend.RfcommConnected += (sender, args) => Task.Run(async() => await Task.Delay(150).ContinueWith((_) => { if (RegisteredDeviceValid) { Connected?.Invoke(this, EventArgs.Empty); } else { Log.Error("BluetoothImpl: Suppressing Connected event, device not properly registered"); } })); _backend.Disconnected += (sender, reason) => { if (!SuppressDisconnectionEvents) { Disconnected?.Invoke(this, reason); } }; MessageReceived += SPPMessageHandler.Instance.MessageReceiver; }
public void startReaderTask() { if (state != ConnectionState.CONNECTED) { throw new InvalidOperationException("[TCPConnection2]: Unable to start reader task! ConnectionState != CONNECTED - state = " + state); } // Ensure no other reader task is running: if (readingCTS != null && !readingCTS.IsCancellationRequested) { readingCTS.Cancel(); } readingCTS = new CancellationTokenSource(); try { Task.Run(async() => { TCPReadResult readResult = null; int lastReadingFailedCount = 0; int errorCount = 0; DateTime lastReadingFailed = DateTime.MinValue; while (state == ConnectionState.CONNECTED && errorCount < 3) { try { readResult = await readAsync(); // Check if reading failed: switch (readResult.STATE) { case TCPReadState.SUCCESS: lastReadingFailedCount = 0; errorCount = 0; Logger.Debug("[TCPConnection2]: Received from (" + account.serverAddress + "):" + readResult.DATA); // Trigger the NewDataReceived event: NewDataReceived?.Invoke(this, new NewDataReceivedEventArgs(readResult.DATA)); break; case TCPReadState.FAILURE: if (lastReadingFailedCount++ <= 0) { lastReadingFailed = DateTime.Now; } // Read 5 empty or null strings in an interval lower than 1 second: double c = DateTime.Now.Subtract(lastReadingFailed).TotalSeconds; if (lastReadingFailedCount > 5 && c < 1) { lastConnectionError = new ConnectionError(ConnectionErrorCode.READING_LOOP); errorCount = int.MaxValue; continue; } break; case TCPReadState.END_OF_STREAM: Logger.Info("Socket closed because received 0-length message from: " + account.serverAddress); disconnect(); break; } } catch (OperationCanceledException) { lastConnectionError = new ConnectionError(ConnectionErrorCode.READING_CANCELED); errorCount++; } catch (Exception e) { SocketErrorStatus status = SocketErrorStatus.Unknown; if (e is AggregateException aggregateException && aggregateException.InnerException != null) { status = SocketError.GetStatus(e.InnerException.HResult); } else { Exception baseException = e.GetBaseException(); if (baseException != null) { status = SocketError.GetStatus(e.GetBaseException().HResult); } else { status = SocketError.GetStatus(e.HResult); } } lastConnectionError = new ConnectionError(status, e.Message); switch (status) { // Some kind of connection lost: case SocketErrorStatus.ConnectionTimedOut: case SocketErrorStatus.ConnectionRefused: case SocketErrorStatus.NetworkDroppedConnectionOnReset: case SocketErrorStatus.SoftwareCausedConnectionAbort: case SocketErrorStatus.ConnectionResetByPeer: errorCount = int.MaxValue; break; default: errorCount++; break; } }