internal async Task GetMessageOnSchedule(CancellationToken cancellationToken) { try { BlynkLogManager.LogMethodBegin(nameof(GetMessageOnSchedule)); while (!cancellationToken.IsCancellationRequested) { try { if (this.Connected) { var receivedMessages = await this.ReceiveAsync(cancellationToken); if (receivedMessages) { BlynkLogManager.LogInformation("received"); } await Task.Delay(this.BackgroundReadIntervalInMilliseconds, cancellationToken); } else { BlynkLogManager.LogInformation("not connected"); await Task.Delay(10 *this.BackgroundReadIntervalInMilliseconds, cancellationToken); } } catch (TaskCanceledException) { } catch (Exception ex) { BlynkLogManager.LogException("Background message receiver", ex); } } BlynkLogManager.LogInformation("canceled"); } finally { BlynkLogManager.LogMethodEnd(nameof(GetMessageOnSchedule)); } }
internal async Task <bool> ReceiveAsync(CancellationToken cancellationToken) { byte[] receiveBuffer = null; try { BlynkLogManager.LogMethodBegin(nameof(ReceiveAsync)); if (this.tcpStream.DataAvailable) { BlynkLogManager.LogInformation("data available"); receiveBuffer = Utility.ArrayManager <byte> .GetArray(this.tcpClient.Available); // new byte[ this.tcpClient.Available ]; int count = await this.tcpStream.ReadAsync(receiveBuffer, 0, receiveBuffer.Length, cancellationToken); var commands = BlynkMessageParser.GetBlynkMessages(receiveBuffer, count); return(await this.ProcessMessagesAsync(commands)); } //else { // Console.Write( "." ); //} return(false); } finally { if (receiveBuffer != null) { Utility.ArrayManager <byte> .ReleaseArray(receiveBuffer); receiveBuffer = null; } BlynkLogManager.LogMethodEnd(nameof(ReceiveAsync)); } }
private async Task SendPingsOnSchedule(CancellationToken cancellationToken) { try { BlynkLogManager.LogMethodBegin(nameof(SendPingsOnSchedule)); while (!cancellationToken.IsCancellationRequested) { try { if (this.Connected) { BlynkLogManager.LogInformation("ping"); var pingCommand = new BlynkCommand(BlynkCommandType.BLYNK_CMD_PING, NextMessageId, false); pingCommand.Append(( Int16 )0); await this.SendAsync(pingCommand.ToArray(), cancellationToken); } else { BlynkLogManager.LogInformation("not connected"); } await Task.Delay(this.PingIntervalInMilliseconds, cancellationToken); } catch (TaskCanceledException) { } catch (Exception ex) { BlynkLogManager.LogException("Background ping sender", ex); } } BlynkLogManager.LogInformation("canceled"); } finally { BlynkLogManager.LogMethodEnd(nameof(SendPingsOnSchedule)); } }
private bool disposedValue = false; // To detect redundant calls protected virtual void Dispose(bool disposing) { try { BlynkLogManager.LogMethodBegin(nameof(Dispose)); if (!disposedValue) { if (disposing) { if (this.tcpClient != null) { this.tcpClient.Dispose(); this.tcpClient = null; } if (this.tcpStream != null) { this.tcpStream.Dispose(); this.tcpStream = null; } } disposedValue = true; } } finally { BlynkLogManager.LogMethodEnd(nameof(Dispose)); } }
protected BlynkMessageParser(IByteProtocolBuffer byteProtocol) { try { BlynkLogManager.LogMethodBegin("BlynkMessageParser.ctor"); byte commandType; UInt16 messageId; UInt16 messageLength; byteProtocol .Extract(out commandType) .Extract(out messageId) .Extract(out messageLength); this.BlynkCommandType = ( BlynkCommandType )commandType; this.MessageId = messageId; if (this.BlynkCommandType == BlynkCommandType.BLYNK_CMD_RESPONSE) { this.ResponseCode = messageLength; this.MessageLength = ( UInt16 )0; this.messageBuffer = null; } else { this.MessageLength = messageLength; byteProtocol.Extract(out this.messageBuffer, messageLength); } } catch (Exception ex) { BlynkLogManager.LogException("Error constructing message parser", ex); } finally { BlynkLogManager.LogMethodEnd("BlynkMessageParser.ctor"); } }
public string GetHardwareCommandType(HardwareCommandType value) { BlynkLogManager.LogMethodBegin(nameof(GetHardwareCommandType)); switch (value) { case HardwareCommandType.VirtualRead: return(BlynkMessageParser.VirtualReadIndicator); case HardwareCommandType.VirtualWrite: return(BlynkMessageParser.VirtualWriteIndicator); case HardwareCommandType.DigitalRead: return(BlynkMessageParser.DigitalReadIndicator); case HardwareCommandType.DigitalWrite: return(BlynkMessageParser.DigitalWriteIndicator); case HardwareCommandType.AnalogRead: return(BlynkMessageParser.AnalogReadIndicator); case HardwareCommandType.AnalogWrite: return(BlynkMessageParser.AnalogWriteIndicator); case HardwareCommandType.PinMode: return(BlynkMessageParser.PinModeIndicator); } BlynkLogManager.LogMethodEnd(nameof(GetHardwareCommandType)); return(string.Empty); }
public IByteProtocolBuffer Extract(List <string> data) { try { BlynkLogManager.LogMethodBegin(nameof(Extract)); return(this.MessageBuffer.Extract(data)); } finally { BlynkLogManager.LogMethodEnd(nameof(Extract)); } }
public void SetValue(ushort data, ushort offset) { try { BlynkLogManager.LogMethodBegin(nameof(SetValue)); this.MessageBuffer.SetValue(data, offset); } finally { BlynkLogManager.LogMethodEnd(nameof(SetValue)); } }
public IByteProtocolBuffer Extract(out string data, int length) { try { BlynkLogManager.LogMethodBegin(nameof(Extract)); return(this.MessageBuffer.Extract(out data, length)); } finally { BlynkLogManager.LogMethodEnd(nameof(Extract)); } }
public void Clear() { try { BlynkLogManager.LogMethodBegin(nameof(Clear)); this.MessageBuffer.Clear(); } finally { BlynkLogManager.LogMethodEnd(nameof(Clear)); } }
public IByteProtocolBuffer Append(ushort data) { try { BlynkLogManager.LogMethodBegin(nameof(Append)); return(this.MessageBuffer.Append(data)); } finally { BlynkLogManager.LogMethodEnd(nameof(Append)); } }
public async Task <bool> SendPinWriteAsync(BlynkConnection connection, BlynkCommand command, CancellationToken cancellationToken) { try { BlynkLogManager.LogMethodBegin(nameof(SendPinWriteAsync)); return(await connection.SendAsync(command.ToArray(), cancellationToken)); } finally { BlynkLogManager.LogMethodEnd(nameof(SendPinWriteAsync)); } }
public IByteProtocolBuffer Append(string data, int length) { try { BlynkLogManager.LogMethodBegin(nameof(Append)); return(this.MessageBuffer.Append(data, length)); } finally { BlynkLogManager.LogMethodEnd(nameof(Append)); } }
public IByteProtocolBuffer Extract(out IByteProtocolBuffer protocolBuffer, int length) { try { BlynkLogManager.LogMethodBegin(nameof(Extract)); protocolBuffer = null; return(this.MessageBuffer.Extract(out protocolBuffer, length)); } finally { BlynkLogManager.LogMethodEnd(nameof(Extract)); } }
public void Disconnect() { try { BlynkLogManager.LogMethodBegin(nameof(Disconnect)); this.backgroundCancellationTokenSource.Cancel(); this.tcpStream.Close(); this.tcpClient.Close(); } finally { BlynkLogManager.LogMethodEnd(nameof(Disconnect)); } }
public async Task <bool> SendAsync(byte[] byteBuffer, CancellationToken cancellationToken) { try { BlynkLogManager.LogMethodBegin(nameof(SendAsync)); await this.tcpStream.WriteAsync(byteBuffer, 0, byteBuffer.Length, cancellationToken); await this.tcpStream.FlushAsync(cancellationToken); return(true); } finally { BlynkLogManager.LogMethodEnd(nameof(SendAsync)); } }
public bool Connect() { try { BlynkLogManager.LogMethodBegin(nameof(Connect)); CancellationTokenSource cancellationTokenSource = new CancellationTokenSource(50000); // this.withSSL ? 10000 : 5000 ); // five seconds for connect & login return(this.ConnectAsync(cancellationTokenSource.Token).GetAwaiter().GetResult()); } catch (Exception ex) { BlynkLogManager.LogException("Exception while connecting", ex); return(false); } finally { BlynkLogManager.LogMethodEnd(nameof(Connect)); } }
public byte[] ToArray() { try { BlynkLogManager.LogMethodBegin(nameof(ToArray)); if (this.appendLength) { UInt16 bodyLength = ( ushort )(this.MessageBuffer.Position - 5); this.MessageBuffer.SetValue(bodyLength, 3); } return(this.MessageBuffer.ToArray()); } finally { BlynkLogManager.LogMethodEnd(nameof(ToArray)); } }
internal async Task <bool> SendResponseAsync(UInt16 originalMessageId, BlynkResponse response = BlynkResponse.OK) { try { BlynkLogManager.LogMethodBegin(nameof(SendResponseAsync)); var command = new BlynkCommand(BlynkCommandType.BLYNK_CMD_RESPONSE, originalMessageId, false); command.Append(( byte )0) .Append(( byte )response); return(await this.SendAsync(command.ToArray(), backgroundCancellationTokenSource.Token)); } finally { BlynkLogManager.LogMethodEnd(nameof(SendResponseAsync)); } }
private async Task <bool> ProcessMessagesAsync(IEnumerable <BlynkMessageParser> blynkMessages) { try { BlynkLogManager.LogMethodBegin(nameof(ProcessMessagesAsync)); bool totalResult = false; foreach (var blynkMessage in blynkMessages) { bool result = await blynkMessage.ParseMessageAsync(this); totalResult = totalResult && result; } return(totalResult); } finally { BlynkLogManager.LogMethodEnd(nameof(ProcessMessagesAsync)); } }
public static IEnumerable <BlynkMessageParser> GetBlynkMessages(byte[] incomingBuffer, int readLength) { try { BlynkLogManager.LogMethodBegin(nameof(GetBlynkMessages)); var byteProtocolBuffer = new ByteProtocolBuffer(incomingBuffer); var result = new List <BlynkMessageParser>(); while (byteProtocolBuffer.Position < readLength) { result.Add(new BlynkMessageParser(byteProtocolBuffer)); } return(result); } finally { BlynkLogManager.LogMethodEnd(nameof(GetBlynkMessages)); } }
public BlynkConnection(string host, int port, string authentication) //, bool withSSL ) { { try { BlynkLogManager.LogMethodBegin("BlynkConnection.ctor"); this.host = host; this.port = port; this.authentication = authentication; this.tcpClient = new TcpClient(AddressFamily.InterNetwork); this.tcpClient.NoDelay = true; this.backgroundCancellationTokenSource = new CancellationTokenSource(); //this.withSSL = withSSL; this.PingIntervalInMilliseconds = 5000; this.BackgroundReadIntervalInMilliseconds = 100; } finally { BlynkLogManager.LogMethodEnd("BlynkConnection.ctor"); } }
public async Task <bool> SendAnalogPinWriteAsync(BlynkConnection connection, UInt16?originalMessageId, CancellationToken cancelationToken) { try { BlynkLogManager.LogMethodBegin(nameof(SendAnalogPinWriteAsync)); using (var command = new BlynkCommand(BlynkCommandType.BLYNK_CMD_HARDWARE, originalMessageId ?? connection.NextMessageId)) { string hardwareCommand = command.GetHardwareCommandType(HardwareCommandType.AnalogWrite); string pinName = this.PinNumber.ToString(); string pinValue = this.Value.ToString(); command.Append(hardwareCommand) .Append(pinName) .Append(pinValue); return(await base.SendPinWriteAsync(connection, command, cancelationToken)); } } finally { BlynkLogManager.LogMethodEnd(nameof(SendAnalogPinWriteAsync)); } }
public HardwareCommandType GetHardwareCommandType() { try { BlynkLogManager.LogMethodBegin(nameof(GetHardwareCommandType)); string stringData; this.messageBuffer.Extract(out stringData); switch (stringData) { case VirtualReadIndicator: return(HardwareCommandType.VirtualRead); case VirtualWriteIndicator: return(HardwareCommandType.VirtualWrite); case DigitalReadIndicator: return(HardwareCommandType.DigitalRead); case DigitalWriteIndicator: return(HardwareCommandType.DigitalWrite); case AnalogReadIndicator: return(HardwareCommandType.AnalogRead); case AnalogWriteIndicator: return(HardwareCommandType.AnalogWrite); case PinModeIndicator: return(HardwareCommandType.PinMode); default: return(HardwareCommandType.Invalid); } } finally { BlynkLogManager.LogMethodEnd(nameof(GetHardwareCommandType)); } }
public async Task <bool> ConnectAsync(CancellationToken cancellationToken) { try { BlynkLogManager.LogMethodBegin(nameof(ConnectAsync)); this.messageID = 1; await this.tcpClient.ConnectAsync(this.host, this.port); if (this.tcpClient.Connected) { this.tcpClient.NoDelay = true; this.tcpStream = this.tcpClient.GetStream(); //if( this.withSSL ) { // this.sslStream = new SslStream( this.tcpStream ); // await this.sslStream.AuthenticateAsClientAsync( this.host ); //} using (var loginCommand = new BlynkCommand(BlynkCommandType.BLYNK_CMD_LOGIN, this.NextMessageId)) { loginCommand.Append(this.authentication, this.authentication.Length); var dummy2 = Task.Run(() => this.GetMessageOnSchedule(this.backgroundCancellationTokenSource.Token)); await this.SendAsync(loginCommand.ToArray(), cancellationToken); } var dummy = Task.Run(() => this.SendPingsOnSchedule(this.backgroundCancellationTokenSource.Token)); return(true); } return(false); } finally { BlynkLogManager.LogMethodEnd(nameof(ConnectAsync)); } }
internal async Task <bool> ParseMessageAsync(BlynkConnection blynkConnection) { bool result = true; try { BlynkLogManager.LogMethodBegin(nameof(ParseMessageAsync)); BlynkLogManager.LogInformation(string.Format("Message Received command type : {0}", this.BlynkCommandType)); switch (this.BlynkCommandType) { case BlynkCommandType.BLYNK_CMD_RESPONSE: blynkConnection.ResponseReceivedNotification?.Invoke(this.ResponseCode); return(result); case BlynkCommandType.BLYNK_CMD_PING: return(await blynkConnection.SendResponseAsync(this.MessageId)); case BlynkCommandType.BLYNK_CMD_BRIDGE: return(await blynkConnection.SendResponseAsync(this.MessageId)); case BlynkCommandType.BLYNK_CMD_HARDWARE: { var hardwareCommandType = this.GetHardwareCommandType(); BlynkLogManager.LogInformation(string.Format("Hardware command type : {0}", hardwareCommandType)); switch (hardwareCommandType) { case HardwareCommandType.VirtualRead: { string pinString; this.messageBuffer.Extract(out pinString); var pinNumber = int.Parse(pinString); var pin = blynkConnection.VirtualPinNotification.PinReadRequest?.Invoke(pinNumber); // blynkConnection.ReadVirtualPinRequest?.Invoke( pinNumber ); if (pin == null) { return(await blynkConnection.SendResponseAsync(this.MessageId, BlynkResponse.NO_DATA)); } else { return(await pin.SendVirtualPinWriteAsync(blynkConnection, this.MessageId, blynkConnection.CancellationToken)); } } case HardwareCommandType.VirtualWrite: { string pinNumberAsString; this.messageBuffer.Extract(out pinNumberAsString); var pin = new VirtualPin() { PinNumber = int.Parse(pinNumberAsString) }; this.messageBuffer.Extract(pin.Values); blynkConnection.VirtualPinNotification.PinWriteNotification?.Invoke(pin); return(await blynkConnection.SendResponseAsync(this.MessageId)); } case HardwareCommandType.DigitalRead: { string pinString; this.messageBuffer.Extract(out pinString); var pinNumber = int.Parse(pinString); var pin = blynkConnection.DigitalPinNotification.PinReadRequest?.Invoke(pinNumber); // blynkConnection.ReadDigitalPinRequest?.Invoke( pinNumber ); if (pin == null) { return(await blynkConnection.SendResponseAsync(this.MessageId, BlynkResponse.NO_DATA)); } else { return(await pin.SendDigitalPinWriteAsync(blynkConnection, this.MessageId, blynkConnection.CancellationToken)); } } case HardwareCommandType.DigitalWrite: { string pinNumberAsString; string valueAsString; this.messageBuffer.Extract(out pinNumberAsString) .Extract(out valueAsString); var pin = new DigitalPin() { PinNumber = int.Parse(pinNumberAsString), Value = int.Parse(valueAsString) == 1 }; //blynkConnection.WriteDigitalPinNotification?.Invoke( pin ); blynkConnection.DigitalPinNotification.PinWriteNotification?.Invoke(pin); return(await blynkConnection.SendResponseAsync(this.MessageId)); } case HardwareCommandType.AnalogRead: { string pinString; this.messageBuffer.Extract(out pinString); var pinNumber = int.Parse(pinString); var pin = blynkConnection.AnalogPinNotification.PinReadRequest?.Invoke(pinNumber); // blynkConnection.ReadAnalogPinRequest( pinNumber ); if (pin == null) { return(await blynkConnection.SendResponseAsync(this.MessageId, BlynkResponse.NO_DATA)); } else { return(await pin.SendAnalogPinWriteAsync(blynkConnection, this.MessageId, blynkConnection.CancellationToken)); } } case HardwareCommandType.AnalogWrite: { string pinNumberAsString; string valueAsString; this.messageBuffer.Extract(out pinNumberAsString) .Extract(out valueAsString); var pin = new AnalogPin() { PinNumber = int.Parse(pinNumberAsString), Value = short.Parse(valueAsString) }; //blynkConnection.WriteAnalogPinNotification?.Invoke( pin ); blynkConnection.AnalogPinNotification.PinWriteNotification?.Invoke(pin); return(await blynkConnection.SendResponseAsync(this.MessageId)); } case HardwareCommandType.PinMode: { string pin; string mode; while (this.messageBuffer.Position < this.MessageLength) { this.messageBuffer.Extract(out pin) .Extract(out mode); PinMode pinMode = PinMode.Invalid; switch (mode) { case "in": pinMode = PinMode.Input; break; case "out": pinMode = PinMode.Output; break; case "pu": pinMode = PinMode.PullUp; break; case "pd": pinMode = PinMode.PullDown; break; case "pwm": pinMode = PinMode.Pwm; break; } if (pinMode != PinMode.Invalid) { blynkConnection.PinModeNotification?.Invoke(pin, pinMode); } } return(await blynkConnection.SendResponseAsync(this.MessageId)); } } break; } } } catch (Exception ex) { BlynkLogManager.LogException("Error parsing message", ex); } finally { BlynkLogManager.LogMethodEnd(nameof(ParseMessageAsync)); } return(result); }