public void Shutdown() { this.Log("Stopping realtime server"); NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged; _runningTokenSource?.Cancel(); _inboundReader?.Dispose(); _outboundWriter?.DetachStream(); _outboundWriter?.Dispose(); }
public void WriteBytes([ReadOnlyArray] byte[] bytes) { try { if (_serialDevice != null) { CancellationToken token = _readCancellationTokenSource.Token; token.ThrowIfCancellationRequested(); _dataWriteObject = new DataWriter(_serialDevice.OutputStream); if (bytes.Length != 0) { _dataWriteObject.WriteBytes(bytes); _dataWriteObject.StoreAsync().AsTask(token).Wait(token); } } } catch (Exception ex) { if (ex.GetType().Name != "TaskCanceledException") { throw; } } finally { _dataWriteObject?.DetachStream(); _dataWriteObject = null; } }
private void DeInitialiseSerialDevice() { lock (_serialDeviceLock) { if (Enabled) { Enabled = false; _readCancellationTokenSource?.Cancel(); _listenTask?.Wait(); _listenTask = null; _readCancellationTokenSource?.Dispose(); _readCancellationTokenSource = null; _dataReader?.DetachStream(); _dataReader?.Dispose(); _dataReader = null; _dataWriter?.DetachStream(); _dataWriter?.Dispose(); _dataWriter = null; _serialDevice?.Dispose(); _serialDevice = null; } } }
private void Cleanup() { connectTimeoutCTS?.Cancel(); connectTimeoutCTS = null; connectCTS?.Cancel(); connectCTS = null; readCTS?.Cancel(); readCTS = null; sendCTS?.Cancel(); sendCTS = null; tlsUpgradeCTS?.Cancel(); tlsUpgradeCTS = null; try { dataWriter?.DetachStream(); dataWriter?.Dispose(); dataWriter = null; } catch (Exception) { } try { dataReader?.DetachStream(); dataReader?.Dispose(); dataReader = null; } catch (Exception) { } socket?.Dispose(); socket = null; }
public void Shutdown() { Log("Stopping realtime server"); try { NetworkInformation.NetworkStatusChanged -= OnNetworkStatusChanged; } catch { } try { _runningTokenSource?.Cancel(); } catch { } try { _inboundReader?.Dispose(); _outboundWriter?.DetachStream(); _outboundWriter?.Dispose(); } catch { } try { Socket?.Dispose(); } catch { } }
public async Task <bool> Send(byte[] data) { DataWriter writer = null; try { writer = new DataWriter(_port.OutputStream); writer.WriteBytes(data); Task <UInt32> storeAsyncTask; lock (_mutex) { if (_closeTokenSrc == null || _closeTokenSrc.IsCancellationRequested) { throw new OperationCanceledException(); } storeAsyncTask = writer.StoreAsync().AsTask(_closeTokenSrc.Token); } uint bytesWritten = await storeAsyncTask; return(bytesWritten == data.Length); } catch (OperationCanceledException) { if (_disposing) { FreeResources(); } return(false); } finally { writer?.DetachStream(); writer?.Dispose(); } }
public void disconnect() { if (state == ConnectionState.DISCONNECTED) { return; } setState(ConnectionState.DISCONNECTING); Logger.Info("[TCPConnection2]: Disconnecting"); connectingCTS?.Cancel(); readingCTS?.Cancel(); tlsUpgradeCTS?.Cancel(); sendCTS?.Cancel(); try { dataReader?.DetachStream(); dataReader?.Dispose(); dataReader = null; dataWriter?.DetachStream(); dataWriter?.Dispose(); dataWriter = null; } catch (Exception) { } socket?.Dispose(); socket = null; setState(ConnectionState.DISCONNECTED); Logger.Info("[TCPConnection2]: Disconnected"); }
public void Shutdown() { this.Log("Stopping push server"); _runningTokenSource?.Cancel(); _inboundReader?.Dispose(); _outboundWriter?.DetachStream(); _outboundWriter?.Dispose(); }
public void Shutdown() { _runningTokenSource?.Cancel(); _inboundReader = null; _outboundWriter?.DetachStream(); _outboundWriter?.Dispose(); _outboundWriter = null; Log($"[{_instaApi.GetLoggedUser().UserName}] " + "Stopped pinging push server"); }
public void Close() { _DataWriter?.DetachStream(); _DataWriter = null; _CommentSessionWebSocket?.Close(1000, ""); _CommentSessionWebSocket = null; IsConnected = false; }
public async Task <uint> SendBufferAsync(byte[] buffer, TimeSpan waiTimeout, CancellationToken cancellationToken) { // device must be connected if (EventHandlerForSerialDevice.Current.IsDeviceConnected && !cancellationToken.IsCancellationRequested) { DataWriter outputStreamWriter = new DataWriter(EventHandlerForSerialDevice.Current.Device.OutputStream); Task <UInt32> storeAsyncTask; using (CancellationTokenSource linkedCts = CancellationTokenSource.CreateLinkedTokenSource(SendCancellationTokenSource.Token, cancellationToken)) { try { // write buffer to device outputStreamWriter.WriteBytes(buffer); // Don't start any IO if the task was cancelled lock (SendCancelLock) { cancellationToken.ThrowIfCancellationRequested(); linkedCts.Token.ThrowIfCancellationRequested(); storeAsyncTask = outputStreamWriter.StoreAsync().AsTask(linkedCts.Token.AddTimeout(waiTimeout)); } return(await storeAsyncTask); } catch (TaskCanceledException) { // this is expected to happen, don't do anything with this } catch (Exception ex) { Debug.WriteLine($"SendRawBufferAsync-Serial-Exception occurred: {ex.Message}\r\n {ex.StackTrace}"); throw ex; } finally { // detach stream outputStreamWriter?.DetachStream(); outputStreamWriter = null; } } } else { throw new DeviceNotConnectedException(); } return(0); }
public void Dispose() { Cancel(); Task.Delay(TimeSpan.FromSeconds(CancelTimeoutSeconds)); _dataReader?.DetachBuffer(); _dataReader?.DetachStream(); _dataReader?.Dispose(); _dataWriter?.DetachBuffer(); _dataWriter?.DetachStream(); _dataWriter?.Dispose(); _snocModule?.Dispose(); _readCancellationTokenSource.Dispose(); }
public void DisconnectDevice(NanoDeviceBase device) { if (FindDevice(((device as NanoDevice <NanoSerialDevice>).Device.DeviceInformation as SerialDeviceInformation).DeviceInformation.Id) != null) { EventHandlerForSerialDevice.Current.CloseDevice(); inputStreamReader?.DetachStream(); inputStreamReader?.DetachBuffer(); inputStreamReader?.Dispose(); outputStreamWriter?.DetachStream(); outputStreamWriter?.DetachBuffer(); outputStreamWriter?.Dispose(); } }
public void Dispose() { Cancel(); Task.Delay(TimeSpan.FromSeconds(CancelTimeout)); _dataReader?.DetachBuffer(); _dataReader?.DetachStream(); _dataReader?.Dispose(); _dataWriter?.DetachBuffer(); _dataWriter?.DetachStream(); _dataWriter?.Dispose(); _turrisDongle?.Dispose(); _readCancellationTokenSource.Dispose(); foreach (KeyValuePair <string, JablotronDevice> device in _jablotronDevices) { device.Value.Dispose(); } }
public void Disconnect() { try { dataWriter?.DetachStream(); dataWriter?.Dispose(); dataWriter = null; } catch (Exception) { } try { dataReader?.DetachStream(); dataReader?.Dispose(); dataReader = null; } catch (Exception) { } socket?.Dispose(); socket = null; }
public async void WriteBytes([ReadOnlyArray] byte[] bytes) { try { if (_serialPort != null) { // Create the DataWriter object and attach to OutputStream _dataWriteObject = new DataWriter(_serialPort.OutputStream); await WriteAsync(bytes); } } catch (Exception) { } finally { _dataWriteObject?.DetachStream(); _dataWriteObject = null; } }
/// <summary>Call after the connection is closed. Get ready for new connection</summary> private void CleanUp() { _ReconnectTimer?.Dispose(); try { _webSocket?.Close(1000, SocketCloseMessage); } catch (Exception ex) { Debug.WriteLine(ex.Message); } _messageWriter?.DetachStream(); _messageWriter?.Dispose(); _messageWriter = null; _webSocket?.Dispose(); _webSocket = null; }
/// <summary> /// An implementation task that is dedicated to sending byte packages out to the connected 4D Display. /// </summary> /// <param name="sendMessage"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task <uint> SendBytes(byte[] sendMessage, CancellationToken cancellationToken) { DataWriter dataWriter = null; uint bytesWrote = 0; try { // If send task cancellation was requested, then comply cancellationToken.ThrowIfCancellationRequested(); dataWriter = new DataWriter(this.SerialDevice.OutputStream); dataWriter.WriteBytes(sendMessage); Task <UInt32> storeAsyncTask = dataWriter.StoreAsync().AsTask(cancellationToken); bytesWrote = await storeAsyncTask.ConfigureAwait(false); } finally { dataWriter?.DetachStream(); } return(bytesWrote); }
/* * public void captureImageData() * { * * Resolution cameraResolution = UnityEngine.XR.WSA.WebCam.PhotoCapture.SupportedResolutions.OrderByDescending((res) => res.width * res.height).First(); * targetTexture = new Texture2D(cameraResolution.width, cameraResolution.height); * * // Create a PhotoCapture object * UnityEngine.XR.WSA.WebCam.PhotoCapture.CreateAsync(false, delegate (UnityEngine.XR.WSA.WebCam.PhotoCapture captureObject) { * photoCaptureObject = captureObject; * UnityEngine.XR.WSA.WebCam.CameraParameters cameraParameters = new UnityEngine.XR.WSA.WebCam.CameraParameters(); * cameraParameters.hologramOpacity = 0.0f; * cameraParameters.cameraResolutionWidth = cameraResolution.width; * cameraParameters.cameraResolutionHeight = cameraResolution.height; * cameraParameters.pixelFormat = UnityEngine.XR.WSA.WebCam.CapturePixelFormat.BGRA32; * * // Activate the camera * photoCaptureObject.StartPhotoModeAsync(cameraParameters, delegate (UnityEngine.XR.WSA.WebCam.PhotoCapture.PhotoCaptureResult result) { * // Take a picture * photoCaptureObject.TakePhotoAsync(OnCapturedPhotoToMemory); * }); * }); * } * * void OnCapturedPhotoToMemory(UnityEngine.XR.WSA.WebCam.PhotoCapture.PhotoCaptureResult result, UnityEngine.XR.WSA.WebCam.PhotoCaptureFrame photoCaptureFrame) * { * // Copy the raw image data into the target texture * photoCaptureFrame.UploadImageDataToTexture(targetTexture); * * // Create a GameObject to which the texture can be applied * GameObject quad = GameObject.CreatePrimitive(PrimitiveType.Quad); * Renderer quadRenderer = quad.GetComponent<Renderer>() as Renderer; * quadRenderer.material = new Material(Shader.Find("Custom/Unlit/UnlitTexture")); * * quad.transform.parent = this.transform; * quad.transform.localPosition = new Vector3(0.0f, 0.0f, 3.0f); * * quadRenderer.material.SetTexture("_MainTex", targetTexture); * * // Deactivate the camera * photoCaptureObject.StopPhotoModeAsync(OnStoppedPhotoMode); * } * * void OnStoppedPhotoMode(UnityEngine.XR.WSA.WebCam.PhotoCapture.PhotoCaptureResult result) * { * // Shutdown the photo capture resource * photoCaptureObject.Dispose(); * photoCaptureObject = null; * } */ public async void sendMesh(Mesh m, Vector3 location, Quaternion rotation) { if (!connected) { return; } #if !UNITY_EDITOR try { List <Mesh> meshes = new List <Mesh>(); meshes.Add(m); byte[] meshData = SimpleMeshSerializer.Serialize(meshes); //byte[] vectBytes = BitConverter.GetBytes(location); //byte[] quatBytes = BitConverter.GetBytes(rotation); byte[] bytes = new byte[4 + 12 + 16]; // 4 bytes per float System.Buffer.BlockCopy(BitConverter.GetBytes(32 + meshData.Length), 0, bytes, 0, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(location.x), 0, bytes, 4, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(location.y), 0, bytes, 8, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(location.z), 0, bytes, 12, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(rotation.x), 0, bytes, 16, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(rotation.y), 0, bytes, 20, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(rotation.z), 0, bytes, 24, 4); System.Buffer.BlockCopy(BitConverter.GetBytes(rotation.w), 0, bytes, 28, 4); //byte[] sendData = Compress(Combine(bytes, meshData)); byte[] sendData = Combine(bytes, meshData); //byte[] sendData = Compress(Combine(bytes, SimpleMeshSerializer.Serialize(meshes))); //Byte[] sendData = Encoding.ASCII.GetBytes("WEEEEEE!"); //udpClient.Send(sendData, sendData.Length); //safety catch for huge items //temp for testing //byte[] sendData = meshData; if (sendData.Length > 200000) { Debug.Log("Packet of length " + sendData.Length + " waiting to go out... But can't.. Because it is probably too huge..."); return; } DataWriter writer = new DataWriter(outputStream); writer.UnicodeEncoding = Windows.Storage.Streams.UnicodeEncoding.Utf8; writer.ByteOrder = Windows.Storage.Streams.ByteOrder.LittleEndian; //StreamWriter writer = new StreamWriter(outputStream); //writer.BaseStream.Write(sendData,0,sendData.Length); writer.WriteBytes(sendData); await writer.StoreAsync(); await writer.FlushAsync(); Debug.Log("Sent " + sendData.Length + " bytes."); writer.DetachStream(); //writer.WriteBytes(sendData); //await writer.FlushAsync(); //await writer.StoreAsync(); } catch (Exception e) { Debug.Log(e.ToString()); return; } //Debug.Log("Sent: " + sendData.Length + " bytes"); #endif }
async void connect() { HostName serverHost = new HostName("www.contoso.com"); string serverServiceName = "http"; // For simplicity, the sample omits implementation of the // NotifyUser method used to display status and error messages // Try to connect to contoso using HTTP (port 80) try { // Call ConnectAsync method with a plain socket await clientSocket.ConnectAsync(serverHost, serverServiceName, SocketProtectionLevel.PlainSocket); show.Text = "Connected"; } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } show.Text = "Connect failed with error: " + exception.Message; // Could retry the connection, but for this simple example // just close the socket. clientSocket.Dispose(); clientSocket = null; return; } // Now try to send some data DataWriter writer = new DataWriter(clientSocket.OutputStream); string hello = "Hello, World! ☺ "; Int32 len = (int)writer.MeasureString(hello); // Gets the UTF-8 string length. writer.WriteInt32(len); writer.WriteString(hello); show.Text = "Client: sending hello"; try { // Call StoreAsync method to store the hello message await writer.StoreAsync(); show.Text = "Client: sent data"; writer.DetachStream(); // Detach stream, if not, DataWriter destructor will close it. } catch (Exception exception) { show.Text = "Store failed with error: " + exception.Message; // Could retry the store, but for this simple example // just close the socket. clientSocket.Dispose(); clientSocket = null; return; } // Now upgrade the client to use SSL try { // Try to upgrade to SSL await clientSocket.UpgradeToSslAsync(SocketProtectionLevel.Ssl, serverHost); show.Text = "Client: upgrade to SSL completed"; // Add code to send and receive data // The close clientSocket when done } catch (Exception exception) { // If this is an unknown status it means that the error is fatal and retry will likely fail. if (SocketError.GetStatus(exception.HResult) == SocketErrorStatus.Unknown) { throw; } show.Text = "Upgrade to SSL failed with error: " + exception.Message; clientSocket.Dispose(); clientSocket = null; return; } }
public async void Disconnect(string disconnectReason) { string msg = string.Empty; try { if (_listener != null) { _listener.Dispose(); } } catch (Exception ex) { msg += "Disposing _listener: " + ex.Message; } try { if (_socketWriter != null) { try { _socketWriter.DetachStream(); } catch (Exception exDetachWriter) { msg += "Detaching _socketWriter: " + exDetachWriter.Message; } try { _socketWriter.Dispose(); } catch (Exception exDisposeWriter) { msg += "Disposing _socketWriter: " + exDisposeWriter.Message; } _socketWriter = null; } } catch (Exception ex) { msg += "General error Disposing _socketWriter: " + ex.Message; } try { if (_socketReader != null) { try { _socketReader.DetachStream(); } catch (Exception exDetachReader) { msg += "Detaching _socketReader: " + exDetachReader.Message; } try { _socketReader.Dispose(); } catch (Exception exDisposeReader) { msg += "Disposing _socketReader: " + exDisposeReader.Message; } _socketReader = null; } } catch (Exception ex) { msg += "General error Disposing _socketReader: " + ex.Message; } try { if (_socket != null) { try { await _socket.CancelIOAsync(); } catch (Exception exCancelIO) { msg += "Cancelling _socket IO: " + exCancelIO.Message; } _socket.Dispose(); _socket = null; } } catch (Exception ex) { msg += "Disposing _socket: " + ex.Message; } try { if (_service != null) { _service.Dispose(); _service = null; } } catch (Exception ex) { msg += "Disposing _service: " + ex.Message; } FireCommInfoMessage("Disconnected. " + disconnectReason + " " + msg); }
public async void Run(IBackgroundTaskInstance taskInstance) { var deferral = taskInstance.GetDeferral(); try { var details = taskInstance.TriggerDetails as SocketActivityTriggerDetails; var socketInformation = details.SocketInformation; switch (details.Reason) { case SocketActivityTriggerReason.SocketActivity: var socket = socketInformation.StreamSocket; DataReader dataReader = new DataReader(socket.InputStream); dataReader.InputStreamOptions = InputStreamOptions.Partial; // wait for first 4 bytes to get content size UInt32 stringHeader = await dataReader.LoadAsync(4); if (stringHeader != 0) { // getting content size byte[] bytes = new byte[4]; dataReader.ReadBytes(bytes); int length = BitConverter.ToInt32(bytes, 0); // read avaliable content uint count = await dataReader.LoadAsync((uint)length); byte[] receivedBytes = new byte[count]; dataReader.ReadBytes(receivedBytes); // TO DO // manipulate with received Bytes ShowToast("Data received"); } socket.TransferOwnership(socketInformation.Id); break; case SocketActivityTriggerReason.KeepAliveTimerExpired: socket = socketInformation.StreamSocket; DataWriter writer = new DataWriter(socket.OutputStream); writer.WriteBytes(Encoding.UTF8.GetBytes("Keep alive")); await writer.StoreAsync(); writer.DetachStream(); writer.Dispose(); socket.TransferOwnership(socketInformation.Id); break; case SocketActivityTriggerReason.SocketClosed: socket = new StreamSocket(); socket.EnableTransferOwnership(taskInstance.Task.TaskId, SocketActivityConnectedStandbyAction.Wake); if (ApplicationData.Current.LocalSettings.Values["hostname"] == null) { break; } var hostname = (String)ApplicationData.Current.LocalSettings.Values["hostname"]; var port = (String)ApplicationData.Current.LocalSettings.Values["port"]; await socket.ConnectAsync(new HostName(hostname), port); socket.TransferOwnership(socketId); break; default: break; } deferral.Complete(); } catch (Exception exception) { ShowToast(exception.Message); deferral.Complete(); } }
private async Task <bool> PingDeviceLocalAsync(SerialDevice tentativeDevice) { // dev note: this temporary connection to the device, because it actually connects with the device and sends data, has to be carried on it's own without reusing anything from the EventHandlerForSerialDevice otherwise it would break it // this operation sends a valid ping request and waits for a reply from the connected COM port // considering that the Ping request is valid and properly formatted we are just checking if there is a reply from the device and if it has the expected length // this might look as an oversimplification or simplistic but it's quite safe try { // fake Ping header byte[] pingHeader = new byte[] { 78, 70, 80, 75, 84, 86, 49, 0, 240, 240, 187, 218, 148, 185, 67, 183, 0, 0, 0, 0, 191, 130, 0, 0, 0, 32, 0, 0, 8, 0, 0, 0, }; // fake Ping payload byte[] pingPayload = new byte[] { 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; using (var cts = new CancellationTokenSource()) { DataWriter outputStreamWriter = new DataWriter(tentativeDevice.OutputStream); DataReader inputStreamReader = new DataReader(tentativeDevice.InputStream); Task <UInt32> storeAsyncTask; Task <UInt32> loadAsyncTask; try { /////////////////////////////////////////////////// // write pingHeader to device outputStreamWriter.WriteBytes(pingHeader); storeAsyncTask = outputStreamWriter.StoreAsync().AsTask(cts.Token.AddTimeout(new TimeSpan(0, 0, 1))); var txBytes = await storeAsyncTask; ////////////////////////////////////////////////// // write pingPayload to device outputStreamWriter.WriteBytes(pingPayload); storeAsyncTask = outputStreamWriter.StoreAsync().AsTask(cts.Token.AddTimeout(new TimeSpan(0, 0, 1))); txBytes = await storeAsyncTask; ////////////////////////////////////////////////// // read answer (32 bytes) loadAsyncTask = inputStreamReader.LoadAsync(32).AsTask(cts.Token.AddTimeout(new TimeSpan(0, 0, 1))); UInt32 bytesRead = await loadAsyncTask; if (bytesRead == 32) { // at this point we are just happy to get the expected number of bytes from a valid nanoDevice return(true); } } catch (TaskCanceledException) { // this is expected to happen, don't do anything with this } catch (Exception ex) { throw ex; } finally { // detach stream outputStreamWriter?.DetachStream(); outputStreamWriter = null; // detach stream inputStreamReader?.DetachStream(); inputStreamReader = null; } } } catch { } // default to false return(false); }
private async void onConnectionReceived(StreamSocketListener sender, StreamSocketListenerConnectionReceivedEventArgs args) { //await DispatcherHelper.ExecuteOnUIThreadAsync(async () => //{ try { Dictionary <string, string> resultHeaders = new Dictionary <string, string>(); // Add "\r\n" to remove EndOfLine string[] stringSeparators = new string[] { ": ", "\r\n" }; string[] linesplit; using (DataReader dataReader = new DataReader(args.Socket.InputStream)) { string line = string.Empty; byte[] readByte = new byte[1]; // Read the HTTP-Headers do { uint l = await dataReader.LoadAsync(1); if (l == 0) { break; } dataReader.ReadBytes(readByte); line += Encoding.ASCII.GetString(readByte); if (line.Length > 2 && line.Substring(line.Length - 2) == "\r\n") { linesplit = line.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries); line = string.Empty; if ((linesplit?.Count() ?? 0) == 2) { resultHeaders[linesplit[0]] = linesplit[1]; } } // Blankline == Headers finished; Content starts else if (line.Length == 2 && line == "\r\n") { break; } } while (true); if (resultHeaders.TryGetValue("Content-Length", out string value)) { if (UInt32.TryParse(value, out uint length)) { uint resultLength = 0; string data = string.Empty; resultLength = await dataReader.LoadAsync(length); if (resultLength != 0) { byte[] byteBuffer = new byte[resultLength]; dataReader.ReadBytes(byteBuffer); data += Encoding.UTF8.GetString(byteBuffer); RaumFeldEventPropertySet propset = data.ToString().Deserialize <RaumFeldEventPropertySet>(); if (propset != null) { propset.EventSID = resultHeaders["SID"]; eventAggregator.GetEvent <RaumFeldEventPropertySetReceivedEvent>().Publish(propset); } } } } dataReader.DetachStream(); } using (DataWriter dataWriter = new DataWriter(args.Socket.OutputStream)) { dataWriter.WriteBytes(Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\n\r\n")); await dataWriter.FlushAsync(); dataWriter.DetachStream(); } args.Socket.InputStream.Dispose(); args.Socket.OutputStream.Dispose(); args.Socket.Dispose(); } catch (Exception exception) { var errorStatus = SocketError.GetStatus(exception.HResult); throw; } //}); }