Hi,
This is likely an issue with my implementation as I’ve tried sending the same packet using Packet Sender with success on my desktop and the phone I’m testing on. I’m also new to this kind of network programming stuff.
I’m trying to read whether the bulb is on and off so that I can update an icon in the app and know whether to send the turn off or turn on packet to toggle the bulb’s power.
However, whenever I send the packet to the bulb from the app (using the code below), I don’t appear to receive the last 4 characters of hex. I do, however, receive all of the characters leading up to them.
private void updateState() {
final byte[] msg = hexStringToBytes("24 00 00 34 01 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 03 00 00 00 00 00 00 00 00 74 00 00 00");
new Thread(new Runnable() {
public void run() {
try {
InetAddress bulbAddress = InetAddress.getByAddress(ipAddr);
if (!socket.getBroadcast()) socket.setBroadcast(true);
DatagramPacket packet = new DatagramPacket(msg, msg.length, bulbAddress, 56700);
socket.send(packet);
DatagramPacket packet1 = new DatagramPacket(msg, msg.length, bulbAddress, 56700);
socket.receive(packet1);
TextView textView = (TextView) findViewById(R.id.state);
String out = new String(packet1.getData(), packet1.getOffset(), packet1.getLength());
textView.setText(toHex(out));
} catch (Exception ex) {
ex.printStackTrace();
}
}
}).start();
}
private static byte[] hexStringToBytes(String input) {
input = input.toLowerCase(Locale.US);
int n = input.length() / 2;
byte[] output = new byte[n];
int l = 0;
for (int k = 0; k < n; k++) {
char c = input.charAt(l++);
byte b = (byte) ((c >= 'a' ? (c - 'a' + 10) : (c - '0')) << 4);
c = input.charAt(l++);
b |= (byte) (c >= 'a' ? (c - 'a' + 10) : (c - '0'));
output[k] = b;
}
return output;
}
public String toHex(String arg) {
return String.format("%040x", new BigInteger(1, arg.getBytes()));
}
Using a similar method minus the second Datagram Packet and call to socket.Receive, I have been able to turn the bulb on and off without any issues. So it appears I’m able to write, but not read all of the data I need.