Created
February 20, 2019 14:03
-
-
Save dustinsoftware/ec157cbeece710a72b6d66171ace4c8f to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Linq; | |
using System.Net; | |
using System.Net.Sockets; | |
using System.Text; | |
using System.Threading; | |
namespace udptest | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
SendColorChangeBytes("535a3030000000000023000000000000000000000000000000001d000000000000000000041d0602ff01c10a00", 0); | |
SendColorChangeBytes("535a3030000000000023000000000000000000000000000000001800000000000000000004180602ff04c40600", 0); | |
SendColorChangeBytes("535a3030000000000023000000000000000000000000000000001200000000000000000004120602ff06bd0280", 0); | |
} | |
private static void SendColorChangeBytes(string requestDataString, int tries) | |
{ | |
using (var client = new UdpClient { EnableBroadcast = true }) | |
{ | |
var requestData = ToByteArray(requestDataString); | |
var broadcast = new IPEndPoint(IPAddress.Parse("192.168.10.255"), 8900); | |
client.Send(requestData, requestData.Length, broadcast); | |
var serverReceiveEndpoint = new IPEndPoint(IPAddress.Any, 0); | |
var asyncResponse = client.BeginReceive(null, null); | |
asyncResponse.AsyncWaitHandle.WaitOne(400); | |
if (asyncResponse.IsCompleted) | |
{ | |
var response = client.EndReceive(asyncResponse, ref serverReceiveEndpoint); | |
if (response.Length == 0) | |
{ | |
throw new InvalidOperationException("Device sent an empty response."); | |
} | |
return; | |
} | |
else | |
{ | |
if (tries == 10) | |
{ | |
throw new InvalidOperationException("Timed out."); | |
} | |
SendColorChangeBytes(requestDataString, tries + 1); | |
} | |
} | |
} | |
private static byte[] ToByteArray(string hex) => Enumerable.Range(0, hex.Length / 2).Select(x => Convert.ToByte(hex.Substring(x * 2, 2), 16)).ToArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment