-
-
Save delfick/80db7b68e638cb288dd2991d3a5ae6ff 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
package main | |
import ( | |
"encoding/binary" | |
"encoding/hex" | |
"net" | |
"time" | |
"github.com/Sirupsen/logrus" | |
) | |
// Send sends packet to dest and gets back one reply from the bulb | |
// Note that the way it's implemented means it's possible it'll get multiple replies | |
// (i.e. ack and a response if those are both asked for in the request) | |
// and only log the first reply | |
func Send(dest string, packet []byte) error { | |
log := logrus.WithField("from", "clientUDP") | |
// Initializes the UDP cient | |
addr, err := net.ResolveUDPAddr("udp", dest) | |
if err != nil { | |
return err | |
} | |
conn, err := net.DialUDP("udp", nil, addr) | |
defer conn.Close() | |
if err != nil { | |
return err | |
} | |
log.Infof("Sending packet to %s", addr.String()) | |
// Sends the UDP packet | |
_, err = conn.Write(packet) | |
if err != nil { | |
return err | |
} | |
// Reads the response | |
var n int | |
conn.SetReadDeadline(time.Now().Add(2 * time.Second)) | |
p := make([]byte, 2048) | |
n, err = conn.Read(p) | |
if err != nil { | |
return err | |
} | |
size := binary.LittleEndian.Uint16(p[0:2]) | |
reply := hex.EncodeToString(p[0:size]) | |
log.WithFields(logrus.Fields{ | |
"response": reply, | |
"length": n, | |
}).Info("packet received") | |
return nil | |
} | |
func main() { | |
// These bytes only have length 44, but we need length 100 | |
// bts, err := hex.DecodeString("2c000034000000000000000000000000000000000000111000000000000000003a0000000123456789abcdef") | |
// These bytes are correct | |
bts, err := hex.DecodeString("6400001492a3e0600000000000000000000000000000010100000000000000003a00000031323334353637383961626364656600000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000") | |
if err != nil { | |
logrus.Fatal(err) | |
} | |
err = Send("192.168.0.4:56700", bts) | |
if err != nil { | |
logrus.Fatal(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment