private async void Listener_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args) { byte[] message = new byte[150]; Device newDevice = new Device(); char c; using (DataReader reader = args.GetDataReader()) reader.ReadBytes(message); for (int i = 0; i < 32; i += 2) { c = Convert.ToChar(message[i]); if (c == 0) break; newDevice.BoardName += c; } for (int i = 66; i < 96; i += 2) { c = Convert.ToChar(message[i]); if (c == 0) break; newDevice.IpAddress += c; } newDevice.LastPing = DateTime.Now; for (int i = 100; i < 146; i += 2) { c = Convert.ToChar(message[i]); if (c == 0) break; newDevice.MacAddress += c; } int index = -1; for (int i = 0; i < App.Devices.Count; i++) { Device knownDevice = App.Devices[i]; if (knownDevice.MacAddress == newDevice.MacAddress) { index = i; break; } } await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync( CoreDispatcherPriority.Normal, () => { if (index != -1) { App.Devices[index].BoardName = newDevice.BoardName; App.Devices[index].IpAddress = newDevice.IpAddress; App.Devices[index].LastPing = newDevice.LastPing; App.Devices[index].Online = new SolidColorBrush(Colors.Green); } else { newDevice.Index = App.Devices.Count(); newDevice.Online = new SolidColorBrush(Colors.Green); App.Devices.Add(newDevice); } }); }
private void MessageHandler(object sender, DoWorkEventArgs e) { byte[] message = e.Argument as byte[]; Device newDevice = new Device(); char c; for (int i = 0; i < 32; i += 2) { c = Convert.ToChar(message[i]); if (c == 0) break; newDevice.BoardName += c; } for (int i = 66; i < 96; i += 2) { c = Convert.ToChar(message[i]); if (c == 0) break; newDevice.IpAddress += c; } newDevice.LastPing = DateTime.Now; for (int i = 100; i < 146; i += 2) { c = Convert.ToChar(message[i]); if (c == 0) break; newDevice.MacAddress += c; } int index = -1; for (int i = 0; i < App.Devices.Count; i++) { Device knownDevice = App.Devices[i]; if (knownDevice.MacAddress == newDevice.MacAddress) { index = i; break; } } if (null != App.Current) // avoid exception during closing { App.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (System.Windows.Forms.MethodInvoker)delegate () { if (index != -1) { App.Devices[index].BoardName = newDevice.BoardName; App.Devices[index].IpAddress = newDevice.IpAddress; App.Devices[index].LastPing = newDevice.LastPing; App.Devices[index].Online = new SolidColorBrush(Colors.Green); } else { newDevice.Index = App.Devices.Count(); newDevice.Online = new SolidColorBrush(Colors.Green); App.Devices.Add(newDevice); } }); } }