package main import ( "bytes" "encoding/binary" "fmt" "html/template" "log" "net" "sync" "github.com/codegangsta/martini" "github.com/codegangsta/martini-contrib/render" ) type Header int32 type Packet [50]uint16 var mutex sync.Mutex var templateMap = make(map[string]interface{}) var controlTable, stateTable string func main() { go ListenUDP() m := martini.Classic() m.Use(render.Renderer()) m.Get("/", func(r render.Render) { mutex.Lock() defer mutex.Unlock() r.HTML(200, "main", templateMap) }) m.Run() } func ListenUDP() { addr, err := net.ResolveUDPAddr("udp", ":40001") if err != nil { log.Fatal(err) } conn, err := net.ListenUDP("udp", addr) if err != nil { log.Fatal(err) } defer conn.Close() for { b := make([]byte, 1024) _, _, err := conn.ReadFromUDP(b) if err != nil { log.Fatal(err) } buf := bytes.NewReader(b) var header Header err = binary.Read(buf, binary.LittleEndian, &header) if err != nil { log.Fatal(err) } var packet Packet err = binary.Read(buf, binary.LittleEndian, &packet) if err != nil { log.Fatal(err) } switch header { case 0: mapControl(packet) case 1: mapState(packet) } } } func mapControl(packet Packet) { mutex.Lock() defer mutex.Unlock() controlTable = "" for i, v := range packet { controlTable += fmt.Sprintf("%v0x%04X0x%04X%d\n", 30001+i, i, v, v) } templateMap["Table_Control"] = template.HTML(controlTable) } func mapState(packet Packet) { mutex.Lock() defer mutex.Unlock() stateTable = "" for i, v := range packet { stateTable += fmt.Sprintf("%v0x%04X0x%04X%d\n", 40001+i, i, v, v) } templateMap["Table_State"] = template.HTML(stateTable) }