Example #1
0
func main() {
	flag.Parse()

	if flag.NArg() != 2 {
		topic = "many"
		payload = proto.BytesPayload([]byte("hello"))
	} else {
		topic = flag.Arg(0)
		payload = proto.BytesPayload([]byte(flag.Arg(1)))
	}

	if *conns == 0 {
		*conns = -1
	}

	i := 0
	for {
		go client(i)
		i++

		*conns--
		if *conns == 0 {
			break
		}
		time.Sleep(time.Duration(*wait) * time.Millisecond)
	}

	// sleep forever
	<-make(chan struct{})
}
Example #2
0
File: main.go Project: rexpie/mqtt
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()
}
Example #3
0
/**
 * 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()
}
Example #4
0
//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
}
Example #5
0
func (b *TinyBus) Publish(topic string, payload []byte) {
	b.connecting.Wait()

	b.publish(&proto.Publish{
		TopicName: topic,
		Payload:   proto.BytesPayload(payload),
	})

}
Example #6
0
func receiver(rs rs, cc *mqtt.ClientConn, mu *sync.Mutex) error {
	for {
		if ok := rs.Advance(); !ok {
			return rxerr(rs.Err())
		}
		m1 := rs.Value()

		mu.Lock()
		cc.Publish(&proto.Publish{
			Header:    proto.Header{Retain: false},
			TopicName: string(m1.Topic),
			Payload:   proto.BytesPayload(m1.Payload),
		})
		mu.Unlock()
	}
}
Example #7
0
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)
	}
}
Example #8
0
File: main.go Project: rexpie/mqtt
func pub(i int) {
	topic := fmt.Sprintf("loadtest/%v", i)

	var cc *mqtt.ClientConn
	if cc = connect(); cc == nil {
		return
	}

	for i := 0; i < *messages; i++ {
		cc.Publish(&proto.Publish{
			Header:    proto.Header{QosLevel: proto.QosAtMostOnce},
			TopicName: topic,
			Payload:   proto.BytesPayload([]byte("loadtest payload")),
		})
	}

	cc.Disconnect()
}
Example #9
0
//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),
	})

}
Example #10
0
File: mqtt.go Project: x4rMa/jeebus
// 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),
		})
	}
}
Example #11
0
func teding_client(client_id, topic string) {
	//   log.Print("starting client ", i)
	defer func() {
		if err := recover(); err != nil {
			log.Printf("发生错误啦,重连!!!!! %s\n", err)
			time.Sleep(10 * time.Second)
			client(client_id, topic)
		}
	}()

	will_subscribe_count++

	var conn net.Conn
	var err error

	if *ssl {
		conn, err = tls.Dial("tcp", *host, &tls.Config{
			InsecureSkipVerify: true,
		})
		if err != nil {
			panic("failed to connect: " + err.Error())
		}
	} else {
		conn, err = net.Dial("tcp", *host)
		if err != nil {
			log.Print("dial: ", err)
			panic(err)
		}
	}

	cc := mqtt.NewClientConn(conn)
	cc.ClientId = client_id
	cc.KeepAliveTimer = 60
	cc.Dump = *dump

	if publish {
		log.Printf("teding_client %s :尝试连接到:%s\n", client_id, topic)
		if err := cc.Connect(*user, *pass); err != nil {
			log.Fatalf("connect: %v\n", err)
			os.Exit(1)
		}

		//   half := int32(*pace / 2)

		_ = cc.Subscribe([]proto.TopicQos{
			{topic, proto.QosAtLeastOnce},
		})
		subscribe_count++
		log.Printf("已连接上: %d\n", subscribe_count)
	} else {
		return
	}
	//   fmt.Printf("suback: %#v\n", ack)
	if *dump {
	}

	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("ping 出错: %s\n", err)
				time.Sleep(10 * time.Second)
			}
		}()

		for {
			if publish {
				cc.Ping(&proto.PingReq{Header: proto.Header{}})
				time.Sleep(time.Minute)
			} else {
				return
			}
		}
	}()

	go func() {
		//     for _ = range cc.Incoming {
		for incom := range cc.Incoming {
			//TODO: 解析收到消息时的时间,把消息里的时间和现在的时间一起打印
			time_now := time.Now().UnixNano()
			fmt.Printf("{payload: %s, now: %d },\n", incom.Payload, time_now)
			//       fmt.Println(pub.Payload)
		}
	}()

	for {
		if publish {
			//     if false {
			var send_topic string
			var payload proto.Payload

			//       r := rand.Int31n(5)
			r := 4
			switch r {
			case 0:
				send_topic = topic
				payload = proto.BytesPayload(fmt.Sprintf("%d", time.Now().UnixNano()))
			case 1:
				send_topic = broadcast_topic
				msg := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("%d", time.Now().UnixNano())))
				message, err := json.Marshal(&BroadCastMessage{Clients: small_qunliao, Payload: msg})
				//         fmt.Println((string)(message))
				if err != nil {
					log.Printf("marshal failed: %s \n", err)
				}
				payload = proto.BytesPayload(message)
			case 2:
				send_topic = broadcast_topic
				msg := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("%d", time.Now().UnixNano())))
				message, err := json.Marshal(&BroadCastMessage{Clients: middle_qunliao, Payload: msg})
				//         fmt.Println((string)(message))
				if err != nil {
					log.Printf("marshal failed: %s \n", err)
				}
				payload = proto.BytesPayload(message)
			case 3:
				send_topic = broadcast_topic
				msg := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("%d", time.Now().UnixNano())))
				message, err := json.Marshal(&BroadCastMessage{Clients: big_qunliao, Payload: msg})
				//         fmt.Println((string)(message))
				if err != nil {
					log.Printf("marshal failed: %s \n", err)
				}
				payload = proto.BytesPayload(message)
			case 4:
				send_topic = broadcast_topic
				msg := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("%d", time.Now().UnixNano())))
				message, err := json.Marshal(&BroadCastMessage{Clients: super_big_qunliao, Payload: msg})
				//         fmt.Println((string)(message))
				if err != nil {
					log.Printf("marshal failed: %s \n", err)
				}
				payload = proto.BytesPayload(message)
			default:
			}

			cc.Publish(&proto.Publish{
				Header:    proto.Header{},
				TopicName: send_topic,
				Payload:   payload,
			})

			//     sltime := rand.Int31n(half) - (half / 2) + int32(*pace)
			time.Sleep((time.Duration)(*tpace) * time.Millisecond)
		} else {
			return
		}
	}
}
Example #12
0
func client(client_id, topic string) {
	//   log.Print("starting client ", i)
	defer func() {
		if err := recover(); err != nil {
			log.Printf("client_id: %s, 发生错误啦,重连!!!!! %s\n", client_id, err)
			time.Sleep(5 * time.Second)
			client(client_id, topic)
		}
	}()

	send_count := 0

	// First, create the set of root certificates. For this example we only
	// have one. It's also possible to omit this in order to use the
	// default root set of the current operating system.

	var conn net.Conn

	if *ssl {
		now_port++
		var port uint16 = now_port + uint16(*start_port)
		laddr_string := fmt.Sprintf("%s:%d", *laddr, port)
		laddr, err := net.ResolveTCPAddr("tcp", laddr_string)
		if err != nil {
			log.Print("addr err:", err)
			panic(err)
		}
		d := &net.Dialer{LocalAddr: laddr}

		conn, err = tls.DialWithDialer(d, "tcp", *host, &tls.Config{
			//     conn, err = tls.Dial("tcp", *host, &tls.Config{
			InsecureSkipVerify: true,
		})
		if err != nil {
			panic("failed to connect: " + err.Error())
		}
	} else {
		//     conn, err = net.Dial("tcp", *host)
		now_port++
		var port uint16 = now_port + uint16(*start_port)
		laddr_string := fmt.Sprintf("%s:%d", *laddr, port)
		laddr, err := net.ResolveTCPAddr("tcp", laddr_string)
		if err != nil {
			log.Print("addr err:", err)
			panic(err)
		}

		conn, err = net.DialTCP("tcp", laddr, raddr)

		if err != nil {
			log.Print("dial: ", err)
			panic(err)
		}
	}

	cc := mqtt.NewClientConn(conn)
	cc.ClientId = client_id
	cc.KeepAliveTimer = 60
	cc.Dump = *dump

	will_subscribe_count++

	if *reconnect_after > 0 {
		go func(conn net.Conn) {
			time.Sleep(time.Duration(*reconnect_after) * time.Second)
			conn.Close()
		}(conn)
	}

	tmp_id := will_subscribe_count
	if publish {
		log.Printf("client %d :尝试连接到: %s, %s\n", will_subscribe_count, client_id, topic)
		if err := cc.Connect(*user, *pass); err != nil {
			log.Fatalf("connect: %v\n", err)
			os.Exit(1)
		}

		//   half := int32(*pace / 2)

		_ = cc.Subscribe([]proto.TopicQos{
			{topic, proto.QosAtLeastOnce},
		})
		subscribe_count++
		log.Printf("已连接上: %d\n", subscribe_count)
	} else {
		return
	}
	//   fmt.Printf("suback: %#v\n", ack)
	if *dump {
	}

	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("ping 出错: %s\n", err)
				time.Sleep(10 * time.Second)
			}
		}()

		for {
			if publish {
				cc.Ping(&proto.PingReq{Header: proto.Header{}})
				time.Sleep(time.Minute)
			} else {
				return
			}
		}
	}()

	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Printf("出错: %s\n", err)
				time.Sleep(10 * time.Second)
			}
		}()

		//     for _ = range cc.Incoming {
		for incom := range cc.Incoming {
			time_now := time.Now().UnixNano()
			fmt.Printf("{payload: %s, now: %d },\n", incom.Payload, time_now)
			//       recv_count++
			//       if recv_count%100 == 0 {
			//         log.Printf("%s 接收消息: %d \n", client_id, recv_count)
			//       }
			//       fmt.Printf("%s\n", incom.Payload)
		}
	}()

	time.Sleep(time.Duration(*start_wait) * time.Second)

	//   log.Printf("%d 哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈\n", will_subscribe_count)
	_ = tmp_id
	if *ping_only {
		<-make(chan bool)
	} else if tmp_id < 250 {
		//   if true {
		//   if false {
		for {
			if publish {
				//         payload := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("hello, I'm %s, now message count is %d", client_id, send_count)))
				payload := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("%d", time.Now().UnixNano())))
				message, err := json.Marshal(&BroadCastMessage{Clients: recv_qunliao, Payload: payload})
				//         fmt.Println((string)(message))
				if err != nil {
					log.Printf("marshal failed: %s \n", err)
				}
				marshaled_message := proto.BytesPayload(message)
				//         message_payload := proto.BytesPayload(base64.StdEncoding.EncodeToString(marshaled_message))

				cc.Publish(&proto.Publish{
					Header:    proto.Header{},
					TopicName: broadcast_topic,
					Payload:   marshaled_message,
				})
				log.Printf("%s 发送群聊 \n", client_id)
				send_count++
				time.Sleep((time.Duration)(*pace) * time.Second)
				//     sltime := rand.Int31n(half) - (half / 2) + int32(*pace)
			} else {
				return
			}
		}
	} else if tmp_id < 8000 {
		for {
			if publish {
				//         payload := proto.BytesPayload(fmt.Sprintf("hello, I'm %s, now message count is %d", client_id, send_count))
				payload := proto.BytesPayload(fmt.Sprintf("%d", time.Now().UnixNano()))
				//         payload := base64.StdEncoding.EncodeToString(([]byte)(fmt.Sprintf("%d", time.Now().UnixNano())))
				//         message_payload := proto.BytesPayload(base64.StdEncoding.EncodeToString(marshaled_message))

				cc.Publish(&proto.Publish{
					Header:    proto.Header{},
					TopicName: topic,
					Payload:   payload,
				})
				log.Printf("%s 发送私聊 \n", client_id)
				send_count++
				time.Sleep((time.Duration)(*pace) * time.Second)
				//     sltime := rand.Int31n(half) - (half / 2) + int32(*pace)
			} else {
				return
			}
		}
	}
}
Example #13
0
func ping(i int) {
	wsubReady.Wait()

	topic := fmt.Sprintf("pingtest/%v/request", i)
	topic2 := fmt.Sprintf("pingtest/%v/reply", i)

	start := make(chan struct{})
	stop := make(chan struct{})

	// the goroutine to reply to pings for this pair
	go func() {
		payload := []byte("ok")
		cc := connect()
		ack := cc.Subscribe([]proto.TopicQos{
			{topic, proto.QosAtLeastOnce},
		})
		if *dump {
			fmt.Printf("suback: %#v\n", ack)
		}

		close(start)
		for {
			select {
			// for each incoming message, send it back unchanged
			case in := <-cc.Incoming:
				if *dump {
					fmt.Printf("request: %#v\n", in)
				}
				in.TopicName = topic2
				in.Payload = proto.BytesPayload(payload)
				cc.Publish(in)
			case _ = <-stop:
				cc.Disconnect()
				return
			}
		}
	}()

	_ = <-start

	cc := connect()

	ack := cc.Subscribe([]proto.TopicQos{
		{topic2, proto.QosAtLeastOnce},
	})
	if *dump {
		fmt.Printf("suback: %#v\n", ack)
	}

	for i := 0; i < *messages; i++ {
		payload := []byte(fmt.Sprintf("ping %v", i))

		timeStart := time.Now()
		cc.Publish(&proto.Publish{
			Header:    proto.Header{QosLevel: proto.QosAtMostOnce},
			TopicName: topic,
			Payload:   proto.BytesPayload(payload),
		})

		in := <-cc.Incoming
		if *dump {
			fmt.Printf("reply: %#v\n", in)
		}

		elapsed := time.Now().Sub(timeStart)
		stddev.add(elapsed)

		buf := &bytes.Buffer{}
		err := in.Payload.WritePayload(buf)
		if err != nil {
			log.Println("payload data:", err)
			panic("ugh")
		}

		if !bytes.Equal(buf.Bytes(), []byte("ok")) {
			log.Println("unexpected reply: ", string(buf.Bytes()))
			break
		}
	}

	cc.Disconnect()
	close(stop)
}
Example #14
0
func (b *TinyBus) connect() {

	b.connecting.Add(1)
	defer func() {
		b.connecting.Done()

		b.publish(&proto.Publish{
			Header: proto.Header{
				Retain: true,
			},
			TopicName: fmt.Sprintf("node/%s/module/%s/state/connected", config.Serial(), b.id),
			Payload:   proto.BytesPayload([]byte("true")),
		})
	}()

	var conn wrappedConn
	for {
		tcpConn, err := net.Dial("tcp", b.host)
		if err == nil {
			conn = wrappedConn{
				Conn: tcpConn,
				done: make(chan bool, 1),
			}
			break
		}

		//log.Warningf("Failed to connect to: %s", err)
		time.Sleep(time.Millisecond * 500)
	}

	if b.mqtt != nil {
		log.Infof("Reconnected to mqtt server")
	}

	mqtt := mqtt.NewClientConn(conn)
	mqtt.ClientId = b.id

	err := mqtt.ConnectCustom(&proto.Connect{
		WillFlag:    true,
		WillQos:     0,
		WillRetain:  true,
		WillTopic:   fmt.Sprintf("$node/%s/module/%s/state/connected", config.Serial(), b.id),
		WillMessage: "false",
	})

	if err != nil {
		log.Fatalf("MQTT Failed to connect to: %s", err)
	}

	b.mqtt = mqtt

	b.connected()

	for _, s := range b.subscriptions {
		if !s.cancelled {
			b.subscribe(s)
		}
	}

	go func() {
		for m := range mqtt.Incoming {
			b.onIncoming(m)
		}
	}()

	go func() {
		<-conn.done
		b.disconnected()
		if !b.destroyed {
			b.connect()
		}
	}()
}
Example #15
0
func decode(cc *mqtt.ClientConn, src *net.UDPAddr, pkt []byte) {
	// Parse packet
	code := pkt[0]
	groupId := pkt[1]
	nodeId := pkt[2] & 0x1f
	ack := 0 // really need to decode pkt[2]
	data := pkt[3:]

	// Record the groupId -> addr mapping
	newGroup := saveGroupToAddr(groupId, src)

	// If this is a new group subscribe to the topic
	if newGroup {
		sub := []proto.TopicQos{
			{Topic: fmt.Sprintf("/rf/%d/+/tx", groupId), Qos: proto.QosAtMostOnce},
			{Topic: fmt.Sprintf("/rf/%d/+/tb", groupId), Qos: proto.QosAtMostOnce},
		}
		cc.Subscribe(sub)
	}

	// Create the topic
	if code > RF_Debug && code != RF_BootReply {
		log.Printf("Dropping UDP packet due to unprocessable code=%d", code)
		log.Printf("%#v", pkt[0:9])
		return
	}
	// handle boot protocol
	rxrb := "rx"
	kind := ""
	switch code {
	case RF_Pairing:
		rxrb = "rb"
		kind = "pairing"
	case RF_BootReq:
		rxrb = "rb"
		kind = "boot"
	}
	// handle packets with no source node id
	switch code {
	case RF_DataPush, RF_DataReq, RF_AckBcast, RF_BootReply, RF_Debug:
		nodeId = 0
	}
	// finally the topic
	topic := fmt.Sprintf("/rf/%d/%d/%s", groupId, nodeId, rxrb)

	// Create the payload
	payload, _ := json.Marshal(RFMessage{
		AsOf:   time.Now().UnixNano() / 1000000, // Javascript time: milliseconds
		Base64: base64.StdEncoding.EncodeToString(data),
		Kind:   kind,
	})

	// Send it off
	cc.Publish(&proto.Publish{
		Header:    proto.Header{QosLevel: proto.QosLevel(ack)},
		TopicName: topic,
		Payload:   proto.BytesPayload(payload),
	})

	// Log message, if appropriate
	if code == 9 {
		log.Printf("JeeUDP: %s", data)
	}
	log.Printf("MQTT PUB %s code=%d len=%d", topic, code, len(pkt))
}