iotcore

package module
v0.0.0-...-7fc79eb Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 23, 2023 License: MIT Imports: 11 Imported by: 5

README

Google Cloud IoT Core over MQTT in Go

GoDoc Go Report Card

Package iotcore eases interaction with Google Cloud IoT Core over MQTT. It handles TLS configuration and authentication. It also makes it easy to construct the fully-qualified MQTT topics that Cloud IoT Core uses for configuration, telemetry, state, and commands.

Documentation

Overview

Package iotcore eases interaction with Google Cloud IoT Core over MQTT. It handles TLS configuration and authentication. It also makes it easy to construct the fully-qualified MQTT topics that Cloud IoT Core uses for configuration, telemetry, state, and commands.

Example
package main

import (
	"log"
	"time"

	"github.com/mtraver/iotcore"
)

func main() {
	d := iotcore.Device{
		ProjectID:  "my-gcp-project",
		RegistryID: "my-iot-core-registry",
		DeviceID:   "my-device",
		// Path to a .pem file containing trusted root certs. Download Google's from https://pki.google.com/roots.pem.
		CACerts:     "roots.pem",
		PrivKeyPath: "my-device.pem",
		Region:      "us-central1",
	}

	client, err := d.NewClient(iotcore.DefaultBroker)
	if err != nil {
		log.Fatalf("Failed to make MQTT client: %v", err)
	}

	if token := client.Connect(); !token.Wait() || token.Error() != nil {
		log.Fatalf("Failed to connect to MQTT broker: %v", token.Error())
	}

	if token := client.Publish(d.TelemetryTopic(), 1, false, []byte("{\"temp\": 18.0}")); !token.Wait() || token.Error() != nil {
		log.Printf("Failed to publish: %v", token.Error())
	}

	client.Disconnect(250)
	time.Sleep(500 * time.Millisecond)
}
Output:

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	DefaultBroker = MQTTBroker{
		Host: "mqtt.googleapis.com",
		Port: 8883,
	}

	DefaultBroker443 = MQTTBroker{
		Host: "mqtt.googleapis.com",
		Port: 443,
	}

	LTSBroker = MQTTBroker{
		Host: "mqtt.2030.ltsapis.goog",
		Port: 8883,
	}

	LTSBroker443 = MQTTBroker{
		Host: "mqtt.2030.ltsapis.goog",
		Port: 443,
	}
)

Functions

func CacheJWT

func CacheJWT(ttl time.Duration) func(*Device, *mqtt.ClientOptions) error

CacheJWT caches the JWTs created when connecting to the MQTT broker. When (re)connecting the cached JWT is checked for validity (including expiration) and is reused if valid. If the cached JWT is invalid, a new JWT is created and cached. This is an option meant to be passed to NewClient.

func DeviceIDFromCert

func DeviceIDFromCert(certPath string) (string, error)

DeviceIDFromCert gets the Common Name from an X.509 cert, which for the purposes of this package is considered to be the device ID.

func JWTTTL

func JWTTTL(ttl time.Duration) func(*Device, *mqtt.ClientOptions) error

JWTTTL sets the TLL of JWTs created when connecting to the MQTT broker. This is an option meant to be passed to NewClient.

func PersistentlyCacheJWT

func PersistentlyCacheJWT(ttl time.Duration, path string) func(*Device, *mqtt.ClientOptions) error

PersistentlyCacheJWT caches to disk the JWTs created when connecting to the MQTT broker. When (re)connecting the cached JWT is read from disk and checked for validity (including expiration) and is reused if valid. If the cached JWT is invalid, a new JWT is created and saved to disk. This is an option meant to be passed to NewClient.

Types

type Device

type Device struct {
	ProjectID  string `json:"project_id"`
	RegistryID string `json:"registry_id"`
	DeviceID   string `json:"device_id"`
	// CACerts must contain the path to a .pem file containing trusted root certs. Download Google's from https://pki.google.com/roots.pem.
	CACerts     string `json:"ca_certs_path"`
	PrivKeyPath string `json:"priv_key_path"`
	Region      string `json:"region"`
	// contains filtered or unexported fields
}

Device represents a Google Cloud IoT Core device.

func (*Device) ClientID

func (d *Device) ClientID() string

ClientID returns the fully-qualified Google Cloud IoT Core device ID.

func (*Device) CommandTopic

func (d *Device) CommandTopic() string

CommandTopic returns the MQTT topic to which the device can subscribe to get commands. The topic returned ends with a wildcard, which Cloud IoT Core requires. Subscribing to a specific subfolder is not supported. For more information see https://cloud.google.com/iot/docs/how-tos/commands.

func (*Device) ConfigTopic

func (d *Device) ConfigTopic() string

ConfigTopic returns the MQTT topic to which the device can subscribe to get configuration updates.

func (*Device) ID

func (d *Device) ID() string

func (*Device) NewClient

func (d *Device) NewClient(broker MQTTBroker, options ...func(*Device, *mqtt.ClientOptions) error) (mqtt.Client, error)

NewClient creates a github.com/eclipse/paho.mqtt.golang Client that may be used to connect to the given MQTT broker using TLS, which Google Cloud IoT Core requires. By default it sets up a github.com/eclipse/paho.mqtt.golang ClientOptions with the minimal options required to establish a connection:

  • Client ID
  • TLS configuration
  • Broker
  • A credentials provider that creates a new JWT with TTL 1 minute on each connection attempt.

By passing in options you may customize the ClientOptions. Options are functions with this signature:

func(*Device, *mqtt.ClientOptions) error

They modify the ClientOptions. The option functions are applied to the ClientOptions in the order given before the Client is created. Some options are provided in this package (see options.go), but you may create your own as well. For example, if you wish to set the connect timeout, you might write this:

func ConnectTimeout(t time.Duration) func(*Device, *mqtt.ClientOptions) error {
	return func(d *Device, opts *mqtt.ClientOptions) error {
		opts.SetConnectTimeout(t)
		return nil
	}
}

Using option functions allows for sensible defaults — no options are required to establish a connection — without loss of customizability.

For more information about connecting to Google Cloud IoT Core's MQTT brokers see https://cloud.google.com/iot/docs/how-tos/mqtt-bridge.

func (*Device) NewJWT

func (d *Device) NewJWT(ttl time.Duration) (string, error)

NewJWT creates a new JWT signed with the device's key and expiring in the given amount of time.

func (*Device) StateTopic

func (d *Device) StateTopic() string

StateTopic returns the MQTT topic to which the device should publish state information. This is optionally configured in the device registry. For more information see https://cloud.google.com/iot/docs/how-tos/config/getting-state.

func (*Device) TelemetryTopic

func (d *Device) TelemetryTopic() string

TelemetryTopic returns the MQTT topic to which the device should publish telemetry events.

func (*Device) VerifyJWT

func (d *Device) VerifyJWT(jwtStr string) (bool, error)

VerifyJWT checks the validity of the given JWT, including its signature and expiration. It returns true with a nil error if the JWT is valid. Both false and a non-nil error (regardless of the accompanying boolean value) indicate an invalid JWT.

type MQTTBroker

type MQTTBroker struct {
	Host string
	Port int
}

MQTTBroker represents an MQTT server.

func (*MQTTBroker) String

func (b *MQTTBroker) String() string

String returns a string representation of the MQTTBroker.

func (*MQTTBroker) URL

func (b *MQTTBroker) URL() string

URL returns the URL of the MQTT server.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL