コード例 #1
0
ファイル: main.go プロジェクト: hakobera/osx-cpu-temp
func Subscribe(client *MQTT.MqttClient, topic string) {
	filter, _ := MQTT.NewTopicFilter(topic, byte(MQTT.QOS_ZERO))
	if receipt, err := client.StartSubscription(f, filter); err != nil {
		fmt.Println(err)
		os.Exit(1)
	} else {
		<-receipt
	}
}
コード例 #2
0
ファイル: mqtt.go プロジェクト: kyokomi-sandbox/sandbox
func Subscribe(client *MQTT.MqttClient, topic string) error {
	topicName := config.user + "/" + topic
	// 無料枠はQoS 0のみ
	qos := 0

	// Subscribeするtopicを設定します
	topicFilter, err := MQTT.NewTopicFilter(topicName, byte(qos))
	if err != nil {
		return err
	}

	// Subscribeします
	// onMessageReceived はメッセージが届いたら呼び出されるコールバックです
	_, err = client.StartSubscription(onMessageReceived, topicFilter)
	if err != nil {
		return err
	}

	// そのままではプロセスが終わってしまいますので、待ち受けます
	for {
		time.Sleep(1 * time.Second)
	}
}
コード例 #3
0
ファイル: main.go プロジェクト: voxadam/cascades-caf
// mainLoop initiates all ports and handles the traffic
func mainLoop() {
	openPorts()
	defer closePorts()

	waitCh := make(chan bool)
	go func() {
		total := 0
		for {
			v := <-outCh
			if !v {
				log.Println("An OUT port is closed. Interrupting execution")
				exitCh <- syscall.SIGTERM
				break
			} else {
				total++
			}
			// At least one output ports are opened
			if total >= 1 && waitCh != nil {
				waitCh <- true
			}
		}
	}()

	log.Println("Waiting for options to arrive...")
	var (
		ip            [][]byte
		clientOptions *mqtt.ClientOptions
		client        *mqtt.MqttClient
		defaultTopic  string
		qos           mqtt.QoS
	)

	// Setup socket poll items
	poller := zmq.NewPoller()
	poller.Add(optsPort, zmq.POLLIN)
	poller.Add(tmplPort, zmq.POLLIN)

	for {
		sockets, err := poller.Poll(-1)
		if err != nil {
			log.Println("Error polling ports:", err.Error())
			continue
		}
		for _, socket := range sockets {
			if socket.Socket == nil {
				log.Println("ERROR: could not find socket in polling items array")
				continue
			}
			ip, err = socket.Socket.RecvMessageBytes(0)
			if err != nil {
				log.Println("Error receiving message:", err.Error())
				continue
			}
			if !runtime.IsValidIP(ip) || !runtime.IsPacket(ip) {
				log.Println("Invalid IP:", ip)
				continue
			}
			switch socket.Socket {
			case optsPort:
				err = json.Unmarshal(ip[1], &options)
				if err != nil {
					log.Println("ERROR: failed to unmarshal options:", err.Error())
					continue
				}
				clientOptions, defaultTopic, qos, err = helper.ParseOptionsURI(options.OptionsURI)
				if err != nil {
					log.Printf("Failed to parse connection uri. Error: %s", err.Error())
					continue
				}
				log.Println("Options specified:", options)
			case tmplPort:
				err = json.Unmarshal(ip[1], &propTemplate)
				if err != nil {
					log.Println("ERROR: failed to unmarshal template:", err.Error())
					continue
				}
				log.Printf("Template specified: %+v", propTemplate)

			default:
				log.Println("ERROR: IP from unhandled socket received!")
				continue
			}

			if defaultTopic != "" && clientOptions != nil && propTemplate != nil {
				log.Println("Component configured. Moving on...")
				break
			}
		}

		client = mqtt.NewClient(clientOptions)
		if _, err = client.Start(); err != nil {
			log.Printf("Failed to create MQTT client. Error: %s", err.Error())
			continue
		}

		defer client.Disconnect(1e6)

		optsPort.Close()
		tmplPort.Close()
		break
	}

	log.Println("Started...")
	topicFilter, err := mqtt.NewTopicFilter(defaultTopic, byte(qos))
	utils.AssertError(err)
	_, err = client.StartSubscription(messageHandler, topicFilter)
	utils.AssertError(err)

	ticker := time.Tick(1 * time.Second)
	for _ = range ticker {
	}
}