func client(i int) { log.Print("starting client ", i) conn, err := net.Dial("tcp", *host) if err != nil { log.Fatal("dial: ", err) } cc := mqtt.NewClientConn(conn) cc.Dump = *dump if err := cc.Connect(*user, *pass); err != nil { log.Fatalf("connect: %v\n", err) os.Exit(1) } half := int32(*pace / 2) for { cc.Publish(&proto.Publish{ Header: proto.Header{}, TopicName: topic, Payload: payload, }) sltime := rand.Int31n(half) - (half / 2) + int32(*pace) time.Sleep(time.Duration(sltime) * time.Second) } }
/** * A subscriber impementation. The subscriber listens for incoming * messages from the publisher and handles those messages. */ func sub() { if flag.NArg() < 2 { fmt.Fprintln(os.Stderr, "usage: sub topic [topic topic...]") return } conn, err := net.Dial("tcp", "localhost:4000") if err != nil { die(err) } cc := mqtt.NewClientConn(conn) //cc.Dump = false //cc.ClientId = "" tq := make([]proto.TopicQos, flag.NArg()) for i := 1; i < flag.NArg(); i++ { tq[i].Topic = flag.Arg(i) tq[i].Qos = proto.QosAtMostOnce } if err := cc.Connect("no-user", "no-pass"); err != nil { fmt.Fprintf(os.Stderr, "connect: %v\n", err) os.Exit(1) } fmt.Println("Connected with client id ", cc.ClientId) cc.Subscribe(tq) for m := range cc.Incoming { fmt.Print("\033[94m\033[1m", m.TopicName, ": \033[0m\033[1m") m.Payload.WritePayload(os.Stdout) fmt.Println("\033[0m") // fmt.Println("\tr: ", m.Header.Retain) } }
// Start listening and subscribing to MQTT. func (w *MQTTSub) Run() { port := getInputOrConfig(w.Port, "MQTT_PORT") sock, err := net.Dial("tcp", port) flow.Check(err) client := mqtt.NewClientConn(sock) err = client.Connect("", "") flow.Check(err) for t := range w.In { topic := t.(string) glog.V(2).Infoln("mqtt-sub", topic) if strings.HasSuffix(topic, "/") { topic += "#" // if it looks like a prefix, append "#" for MQTT } client.Subscribe([]proto.TopicQos{{ Topic: topic, Qos: proto.QosAtMostOnce, }}) } for m := range client.Incoming { payload := []byte(m.Payload.(proto.BytesPayload)) // try to decode as JSON, but leave as []byte if that fails var any interface{} if err = json.Unmarshal(payload, &any); err != nil { any = payload } w.Out.Send(flow.Tag{m.TopicName, any}) } }
func main() { flag.Parse() if flag.NArg() != 2 { fmt.Fprintln(os.Stderr, "usage: pub topic message") return } conn, err := net.Dial("tcp", *host) if err != nil { fmt.Fprint(os.Stderr, "dial: ", err) return } cc := mqtt.NewClientConn(conn) cc.Dump = *dump if err := cc.Connect(*user, *pass); err != nil { fmt.Fprintf(os.Stderr, "connect: %v\n", err) os.Exit(1) } fmt.Println("Connected with client id ", cc.ClientId) cc.Publish(&proto.Publish{ Header: proto.Header{Retain: *retain}, TopicName: flag.Arg(0), Payload: proto.BytesPayload([]byte(flag.Arg(1))), }) if *wait { <-make(chan bool) } cc.Disconnect() }
/** * A publisher implementation. The publisher sends messages to the * subscriber. */ func pub() { conn, err := net.Dial("tcp", "localhost:4000") if err != nil { die(err) } cc := mqtt.NewClientConn(conn) cc.Dump = false if err := cc.Connect("your-username", "your-password"); err != nil { die(err) } fmt.Println("\033[92mConnected with client id ", cc.ClientId) cc.Publish(&proto.Publish{ Header: proto.Header{Retain: false}, TopicName: flag.Arg(1), Payload: proto.BytesPayload([]byte(flag.Arg(2))), }) wait := false if wait { <-make(chan bool) } cc.Disconnect() }
func main() { flag.Parse() // MQTT connection mqttSock, err := net.Dial("tcp", *host) if err != nil { log.Fatalf("MQTT broker: %s", err) } cc := mqtt.NewClientConn(mqttSock) cc.ClientId = *id if err := cc.Connect(*user, *pass); err != nil { log.Fatalf("Mqtt connect failed: %v\n", err) } log.Println("Connected with client id", cc.ClientId) // UDP Socket udpAddr := net.UDPAddr{Port: *udp} udpSock, err := net.ListenUDP("udp4", &udpAddr) if err != nil { log.Fatalf("Can't listen to UDP :%d : %s", *udp, err.Error()) } log.Printf("Listening on UDP port %d", *udp) go udpServer(udpSock, cc) // do some work.. mqttServer(cc, udpSock) }
//Publish MQTT message, takes topic as a string, data as a byte array and retain flag as bool func (c *Client) Publish(topic string, data string, retain bool) error { con, err := net.Dial("tcp", c.Port) if err != nil { return err } ccPub := mqtt.NewClientConn(con) err = ccPub.Connect("", "") if err != nil { return err } ccPub.Publish(&proto.Publish{ Header: proto.Header{ Retain: retain, }, TopicName: topic, Payload: proto.BytesPayload(data), }) ccPub.Disconnect() return nil }
func mqttConnect() (*mqtt.ClientConn, *sync.Mutex, error) { conn, err := net.Dial("tcp", *host) if err != nil { return nil, nil, err } cc := mqtt.NewClientConn(conn) cc.Dump = *dump cc.ClientId = *id if err := cc.Connect(*user, *pass); err != nil { return nil, nil, err } return cc, &sync.Mutex{}, err }
func main() { flag.Parse() conn, err := net.Dial("tcp", *host) if err != nil { fmt.Fprint(os.Stderr, "dial: ", err) return } cc := mqtt.NewClientConn(conn) cc.Dump = *dump cc.ClientId = *id tq := []proto.TopicQos{ {Topic: "tick", Qos: proto.QosAtMostOnce}, } if err := cc.Connect(*user, *pass); err != nil { fmt.Fprintf(os.Stderr, "connect: %v\n", err) os.Exit(1) } cc.Subscribe(tq) // Sender go func() { for { now := time.Now() what := fmt.Sprintf("%v at %v", *who, now) cc.Publish(&proto.Publish{ Header: proto.Header{Retain: false}, TopicName: "tick", Payload: proto.BytesPayload([]byte(what)), }) time.Sleep(*delay) } }() // Receiver for m := range cc.Incoming { fmt.Print(m.TopicName, "\t") m.Payload.WritePayload(os.Stdout) fmt.Println("\tr: ", m.Header.Retain) } }
//Subscribe to MQTT Topic, takes topic as a string func (c *MqttClient) Subscribe(tl []proto.TopicQos) chan *proto.Publish { if ccSub == nil { con, err := net.Dial("tcp", c.Port) gotError(err) ccSub = mqtt.NewClientConn(con) err = ccSub.Connect("", "") gotError(err) } ccSub.Subscribe(tl) return ccSub.Incoming }
func main() { flag.Parse() if flag.NArg() < 1 { log.Fatal("usage: mqttlog topic [topic topic...]") } // Connect to MQTT broker conn, err := net.Dial("tcp", *host) if err != nil { log.Fatalf("MQTT broker: ", err) } cc := mqtt.NewClientConn(conn) // Send connect message if err := cc.Connect(*user, *pass); err != nil { log.Fatalf("connect: %s", err) } // Subscribe to requested topics tq := make([]proto.TopicQos, flag.NArg()) for i := 0; i < flag.NArg(); i++ { tq[i].Topic = flag.Arg(i) tq[i].Qos = proto.QosAtMostOnce } cc.Subscribe(tq) // Print everything we receive log.Println("Connected with client id", cc.ClientId) for m := range cc.Incoming { payload := []byte(m.Payload.(proto.BytesPayload)) log.Printf("%s (%d bytes)", m.TopicName, len(payload)) printable := true for _, c := range payload { printable = printable && c >= ' ' && c <= '~' } if printable { log.Printf(" %s", payload) } else { log.Printf(" %q", payload) } } }
func connect() *mqtt.ClientConn { conn, err := net.Dial("tcp", *host) if err != nil { fmt.Fprintf(os.Stderr, "dial: %v\n", err) os.Exit(2) } cc := mqtt.NewClientConn(conn) cc.Dump = *dump cc.ClientId = *id err = cc.Connect(*user, *pass) if err != nil { fmt.Println(err) return nil } cwg.Done() return cc }
//Publish MQTT message, takes topic as a string, data as a byte array and retain flag as bool func (c *MqttClient) Publish(topic string, data string, retain bool) { if ccPub == nil { con, err := net.Dial("tcp", c.Port) gotError(err) ccPub = mqtt.NewClientConn(con) err = ccPub.Connect("", "") gotError(err) } ccPub.Publish(&proto.Publish{ Header: proto.Header{ Retain: retain, }, TopicName: topic, Payload: proto.BytesPayload(data), }) }
func connect(who string) *mqtt.ClientConn { tok := <-tokens defer func() { tokens <- tok }() conn, err := net.Dial("tcp", *host) if err != nil { fmt.Fprintf(os.Stderr, "dial: %v\n", err) os.Exit(2) } cc := mqtt.NewClientConn(conn) cc.Dump = *dump cc.ClientId = who err = cc.Connect(*user, *pass) if err != nil { fmt.Println(err) return nil } cwg.Done() return cc }
func main() { flag.Parse() if flag.NArg() < 1 { fmt.Fprintln(os.Stderr, "usage: sub topic [topic topic...]") return } conn, err := net.Dial("tcp", *host) if err != nil { fmt.Fprint(os.Stderr, "dial: ", err) return } cc := mqtt.NewClientConn(conn) cc.Dump = *dump cc.ClientId = *id tq := make([]proto.TopicQos, flag.NArg()) for i := 0; i < flag.NArg(); i++ { tq[i].Topic = flag.Arg(i) tq[i].Qos = proto.QosAtMostOnce } if err := cc.Connect(*user, *pass); err != nil { fmt.Fprintf(os.Stderr, "connect: %v\n", err) os.Exit(1) } fmt.Println("Connected with client id ", cc.ClientId) cc.Subscribe(tq) for m := range cc.Incoming { fmt.Print(m.TopicName, "\t") m.Payload.WritePayload(os.Stdout) fmt.Println("\tr: ", m.Header.Retain) } }
// Start publishing to MQTT. func (w *MQTTPub) Run() { port := getInputOrConfig(w.Port, "MQTT_PORT") sock, err := net.Dial("tcp", port) flow.Check(err) client := mqtt.NewClientConn(sock) err = client.Connect("", "") flow.Check(err) for m := range w.In { msg := m.(flow.Tag) glog.V(1).Infoln("mqtt-pub", msg.Tag, msg.Msg) data, ok := msg.Msg.([]byte) if !ok { data, err = json.Marshal(msg.Msg) flow.Check(err) } retain := len(msg.Tag) > 0 && msg.Tag[0] == '/' client.Publish(&proto.Publish{ Header: proto.Header{Retain: retain}, TopicName: msg.Tag, Payload: proto.BytesPayload(data), }) } }