tinygo.org/x/drivers@v0.27.1-0.20240509133757-7dbca2a54349/examples/net/mqttclient/paho/main.go (about)

     1  // This example is an MQTT client built with the paho-mqtt package.  It sends
     2  // machine.CPUFrequency() readings to the broker every second for 10 seconds.
     3  //
     4  // Note: It may be necessary to increase the stack size when using
     5  // paho.mqtt.golang.  Use the -stack-size=4KB command line option.
     6  
     7  //go:build ninafw || wioterminal || challenger_rp2040
     8  
     9  package main
    10  
    11  import (
    12  	"fmt"
    13  	"log"
    14  	"machine"
    15  	"math/rand"
    16  	"time"
    17  
    18  	mqtt "github.com/eclipse/paho.mqtt.golang"
    19  	"tinygo.org/x/drivers/netlink"
    20  	"tinygo.org/x/drivers/netlink/probe"
    21  )
    22  
    23  var (
    24  	ssid   string
    25  	pass   string
    26  	broker string = "tcp://test.mosquitto.org:1883"
    27  )
    28  
    29  var messagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
    30  	fmt.Printf("Message %s received on topic %s\n", msg.Payload(), msg.Topic())
    31  }
    32  
    33  var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
    34  	fmt.Println("Connected")
    35  }
    36  
    37  var connectionLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
    38  	fmt.Printf("Connection Lost: %s\n", err.Error())
    39  }
    40  
    41  func main() {
    42  	waitSerial()
    43  
    44  	link, _ := probe.Probe()
    45  
    46  	err := link.NetConnect(&netlink.ConnectParams{
    47  		Ssid:       ssid,
    48  		Passphrase: pass,
    49  	})
    50  	if err != nil {
    51  		log.Fatal(err)
    52  	}
    53  
    54  	clientId := "tinygo-client-" + randomString(10)
    55  	fmt.Printf("ClientId: %s\n", clientId)
    56  
    57  	options := mqtt.NewClientOptions()
    58  	options.AddBroker(broker)
    59  	options.SetClientID(clientId)
    60  	options.SetDefaultPublishHandler(messagePubHandler)
    61  	options.OnConnect = connectHandler
    62  	options.OnConnectionLost = connectionLostHandler
    63  
    64  	fmt.Printf("Connecting to MQTT broker at %s\n", broker)
    65  	client := mqtt.NewClient(options)
    66  	token := client.Connect()
    67  	if token.Wait() && token.Error() != nil {
    68  		panic(token.Error())
    69  	}
    70  
    71  	topic := "cpu/freq"
    72  	token = client.Subscribe(topic, 1, nil)
    73  	if token.Wait() && token.Error() != nil {
    74  		panic(token.Error())
    75  	}
    76  	fmt.Printf("Subscribed to topic %s\n", topic)
    77  
    78  	for i := 0; i < 10; i++ {
    79  		freq := float32(machine.CPUFrequency()) / 1000000
    80  		payload := fmt.Sprintf("%.02fMhz", freq)
    81  		token = client.Publish(topic, 0, false, payload)
    82  		if token.Wait() && token.Error() != nil {
    83  			panic(token.Error())
    84  		}
    85  		time.Sleep(time.Second)
    86  	}
    87  
    88  	client.Disconnect(100)
    89  
    90  	for {
    91  		select {}
    92  	}
    93  }
    94  
    95  // Returns an int >= min, < max
    96  func randomInt(min, max int) int {
    97  	return min + rand.Intn(max-min)
    98  }
    99  
   100  // Generate a random string of A-Z chars with len = l
   101  func randomString(len int) string {
   102  	bytes := make([]byte, len)
   103  	for i := 0; i < len; i++ {
   104  		bytes[i] = byte(randomInt(65, 90))
   105  	}
   106  	return string(bytes)
   107  }
   108  
   109  // Wait for user to open serial console
   110  func waitSerial() {
   111  	for !machine.Serial.DTR() {
   112  		time.Sleep(100 * time.Millisecond)
   113  	}
   114  }