private byte[] ToJson(NetBatteryState state) { byte[] buffer = null; try { JsonSerializer serializer = new JsonSerializer(); serializer.NullValueHandling = NullValueHandling.Ignore; var stream = new MemoryStream(); using (StreamWriter sw = new StreamWriter(stream)) using (JsonWriter writer = new JsonTextWriter(sw)) { serializer.Serialize(writer, state); writer.Flush(); buffer = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(buffer, 0, buffer.Length); } } catch (Exception ex) { _logger.LogException(Level.Warn, ex, "Не удалось преобразовать BatteryState в Json"); } return(buffer); }
public void SendBatteryState(NetBatteryState batteryState) { try { Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp); sock.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Broadcast, 1); IPEndPoint endPoint = new IPEndPoint(IPAddress.Broadcast, _settingsService.Port); byte[] send_buffer = ToJson(batteryState); if (send_buffer != null) { sock.SendTo(send_buffer, endPoint); } }catch (Exception ex) { _logger.LogException(Level.Warn, ex, "Не удалось отправить UDP пакет"); } }
private void ReceiveCallback(IAsyncResult result) { try { var broadcastAddress = (IPEndPoint)result.AsyncState; byte[] data = _udpClient.EndReceive(result, ref broadcastAddress); NetBatteryState batteryState = FromJson(data); if (batteryState != null && _settingsService.Identifier == batteryState.Identifier) { UpdateBatteryStatus(batteryState.Status, batteryState.Level, batteryState.RemainingTime, batteryState.IsCharging); } _udpClient.BeginReceive(new AsyncCallback(ReceiveCallback), broadcastAddress); } catch (Exception ex) { _logger.LogException(Level.Warn, ex, "Не удалось перезапустить получение UDP пакетов"); } }