mode

package module
v2.6.0 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2025 License: MIT Imports: 19 Imported by: 0

README

MODE Device SDK for Go

This version of the device-sdk-go module has been deprecated.

GoDoc

This SDK is for anyone implementing MODE device drivers in the Go language. It is being released as a public Go module that provides a Go API for devices to interact with the MODE cloud.

Installation

Our recommendation is to use the package as a module. In module mode, Go will automatically download the module when it sees an import statement referencing this repository. If it is not already, your workspace should be a Go module which will be able to consume this one:

$ go mod init <your module path>

This will allow go you to download and install the module at build or run time.

If you are not yet using Go modules and are still in GOPATH mode, you may use 'go get' to fetch the SDK:

$ go get github.com/moderepo/device-sdk-go/v2

Using the SDK

The package name is mode (which does not match the import path). For example:

    package main

    import (
        "fmt"
        "github.com/moderepo/device-sdk-go/v2"
    )

    func main() {
        dc := &mode.DeviceContext{
            DeviceID:  __DEVICE_ID__,
            AuthToken: "__DEVICE_TOKEN__",
        }

        if d, err := dc.GetInfo(); err == nil {
            fmt.Printf("I am %v\n", d)
        }
    }

Code and documentation copyright 2019 Mode, Inc. Released under the MIT license.

Documentation

Overview

This package provides a Go API for devices to interact with the MODE cloud.

This page documents Version 2 of the API. For Version 3, visit https://godoc.org/github.com/moderepo/device-sdk-go/v3

If a device wants to receive commands from and send events to the MODE cloud, it must start a connection session. Connection session is also required for the device to use the Device Data Proxy (device key-value store) feature.

Both incoming commands and outgoing events are queued. If the connection is disrupted, commands already in the queue will be processed. Likewise, events already in the queue will be delivered when the connection resumes.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrorKeyValuesNotReady = errors.New("key-values not ready")
	ErrorKeyNotFound       = errors.New("key not found")
)
View Source
var (
	ErrorSessionAlreadyStarted = errors.New("session already started")
	ErrorSessionNotStarted     = errors.New("not in session")
	ErrorSessionRecovering     = errors.New("session is recovering")
)

Functions

func ConfigureDeviceEventSender deprecated

func ConfigureDeviceEventSender(_ uint, retryInterval time.Duration)

Deprecated: Use ConfigureDeviceEventTimeout ConfigureDeviceEventSender overrides the default parameters used by the device event sender. These config parameters are used when sending device events with QoS1 (at least once).

func ConfigureDeviceEventTimeout

func ConfigureDeviceEventTimeout(retryInterval time.Duration)

ConfigureDeviceEventTimeout overrides the default parameters used by the timeout of device event sender. These config parameters are used when sending device events with QoS1 (at least once).

func ConfigurePings

func ConfigurePings(interval time.Duration, timeout time.Duration)

When the device's connection session is in the "active" state, "pings" are periodically sent to the server. A ping fails if the server doesn't respond. ConfigurePings overrides the default time interval between pings and the timeout for the server's responses to pings.

func DeleteKeyValue

func DeleteKeyValue(key string) error

DeleteKeyValue deletes a key-value pair from the Device Data Proxy. It returns an error if the device connection session is in idle or recovery state.

IMPORTANT: Race condition may arise if both the device and someone else are updating the same key-value pair.

Note: Functions that access the Device Data Proxy should be called only after the local cache has been loaded. To get notified of this event, use SetKeyValuesReadyCallback() to assign a callback function.

func SendBulkData

func SendBulkData(streamID string, blob []byte, qos QOSLevel) error

SendBulkData queues up a device BulkData to be delivered to the MODE cloud. It returns an error if the device connection session is in idle or recovery state.

func SendBulkDataRequest added in v2.4.0

func SendBulkDataRequest(streamID string, requestID string, payload map[string]interface{}, qos QOSLevel) error

SendBulkDataRequest queues up a device bulkDataEvent to be delivered to the MODE cloud. It returns an error if the device connection session is in idle or recovery state.

func SendEvent

func SendEvent(eventType string, eventData map[string]interface{}, qos QOSLevel) error

SendEvent queues up a device event to be delivered to the MODE cloud. It returns an error if the device connection session is in idle or recovery state.

func SetBulkDataResponseReceiver added in v2.4.0

func SetBulkDataResponseReceiver(streamID string, receiver BulkDataResponseReceiver) error

SetBulkDataResponseReceiver register a callback function when it received request from a DataStream.

func SetCommandHandler

func SetCommandHandler(action string, h CommandHandler)

SetCommandHandler assigns a function to handle device commands coming from the MODE cloud with the specified action.

IMPORTANT: Incoming device commands are queued and handled serially by a goroutine. In your handler function, you should decide whether to spawn goroutines to do certain work.

func SetDefaultCommandHandler

func SetDefaultCommandHandler(h CommandHandler)

SetDefaultCommandHandler assigns a function to handle device commands that don't have dedicated handlers. If default command handler is not set, these unhandled commands will be dropped.

IMPORTANT: Incoming device commands are queued and handled serially by a goroutine. In your handler function, you should decide whether to spawn goroutines to do certain work.

func SetErrorLogger

func SetErrorLogger(l *log.Logger)

SetErrorLogger overrides the default error logger, which writes to STDERR.

func SetInfoLogger

func SetInfoLogger(l *log.Logger)

SetInfoLogger overrides the default debug logger, which writes to STDOUT.

func SetKeyValue

func SetKeyValue(key string, value interface{}) error

SetKeyValue stores a key-value pair to the Device Data Proxy. It returns an error if the device connection session is in idle or recovery state.

IMPORTANT: Race condition may arise if both the device and someone else are updating the same key-value pair.

Note: Functions that access the Device Data Proxy should be called only after the local cache has been loaded. To get notified of this event, use SetKeyValuesReadyCallback() to assign a callback function.

func SetKeyValueDeletedCallback

func SetKeyValueDeletedCallback(f KeyValueDeletedCallback)

SetKeyValueDeletedCallback designates a function to be called whenever a key-value pair has been deleted by someone else.

IMPORTANT: key-value callbacks are queued and executed serially by a goroutine. In your callback function, you should decide whether to spawn goroutines to do certain work.

func SetKeyValueStoredCallback

func SetKeyValueStoredCallback(f KeyValueStoredCallback)

SetKeyValueStoredCallback designates a function to be called whenever a key-value pair has been added or updated by someone else.

IMPORTANT: key-value callbacks are queued and executed serially by a goroutine. In your callback function, you should decide whether to spawn goroutines to do certain work.

func SetKeyValuesReadyCallback

func SetKeyValuesReadyCallback(f KeyValuesReadyCallback)

SetKeyValuesReadyCallback designates a function to be called when the Device Data Proxy is ready to be accessed.

IMPORTANT: key-value callbacks are queued and executed serially by a goroutine. In your callback function, you should decide whether to spawn goroutines to do certain work.

func SetMQTTHostPort

func SetMQTTHostPort(host string, port int, useTLS bool)

SetMQTTHostPort overrides the default MQTT server host and port, and specifies whether TLS connection should be used. (TLS is used by default.)

func SetRESTHostPort

func SetRESTHostPort(host string, port int, useTLS bool)

SetRESTHostPort overrides the default REST API server host and port, and specifies whether TLS connection should be used. (TLS is used by default.)

func SetSessionStateCallback

func SetSessionStateCallback(f SessionStateCallback)

SetSessionStateCallback designates a function to be called when the device's connection session changes state.

func StartSession

func StartSession(dc *DeviceContext) error

StartSession starts a device connection session for the specified device. You can only have one session at a time. If you call StartSession again after a session has started, an error will be returned.

func StopSession

func StopSession() error

StopSession terminates any connection session that is currently in progress. (in "active" or "recovering" state). It returns an error if the session is currently in "idle" state.

func WriteBulkData

func WriteBulkData(streamID string, blob []byte) error

WriteBulkData is similar to SendBulkData, but instead of queueing up the data, this funciton will block until the data has been successfully sent at least once (QoS1). It returns an error if the device connection session is in idle or recovery state, or if the data cannot be sent after several retries.

Types

type BulkDataResponseReceiver added in v2.4.0

type BulkDataResponseReceiver func(*DeviceContext, *DeviceBulkDataResponse)

BulkDataResponseReceiver receive a response of a bulk data request from Stream.

type CommandHandler

type CommandHandler func(*DeviceContext, *DeviceCommand)

A callback function that handles a device command.

type DeviceBulkData

type DeviceBulkData struct {
	StreamID string
	Blob     []byte
	// contains filtered or unexported fields
}

BulkData represents a batch of opaque data to be sent to the MODE cloud.

type DeviceBulkDataRequest added in v2.4.0

type DeviceBulkDataRequest struct {
	StreamID  string                 `json:"-"`
	RequestID string                 `json:"requestId"`
	Payload   map[string]interface{} `json:"payload"`
	// contains filtered or unexported fields
}

DeviceBulkDataRequest is request struct of "request/response" for bulkData.

type DeviceBulkDataResponse added in v2.4.0

type DeviceBulkDataResponse struct {
	StreamID  string                 `json:"-"`
	RequestID string                 `json:"requestId"`
	Status    string                 `json:"status"`
	Payload   map[string]interface{} `json:"payload,omitempty"`
}

DeviceBulkDataResponse is response struct of "request/response" for bulkData.

type DeviceCommand

type DeviceCommand struct {
	Action string
	// contains filtered or unexported fields
}

DeviceCommand represents a command received from the MODE cloud.

func (*DeviceCommand) BindParameters

func (cmd *DeviceCommand) BindParameters(v interface{}) error

BindParameters maps the command parameters from JSON to the provided struct.

func (*DeviceCommand) String

func (cmd *DeviceCommand) String() string

type DeviceContext

type DeviceContext struct {
	DeviceID      uint64
	AuthToken     string
	TLSClientAuth bool
	TLSConfig     *tls.Config
}

An initialized DeviceContext is needed for most API calls. Normally, DeviceID and AuthToken are provisioned using the MODE Developer Console. If on-demand device provisioning is enabled for your MODE project, you can call ProvisionDevice to create a new DeviceContext. If you want to use client certificate instead of AuthToken, set TLSClientAuth to true and call SetPKCS12ClientCertificate function.

func ProvisionDevice

func ProvisionDevice(token string) (*DeviceContext, error)

ProvisionDevice is used for on-demand device provisioning. It takes a provisioning token which is obtained by the user who initiated the process. If successful, the device should store the returned DeviceContext for all future API calls.

func (*DeviceContext) DisableClaimMode

func (dc *DeviceContext) DisableClaimMode() error

DisableClaimMode turns off the device's "claim mode", disallowing it to be added to a different home.

func (*DeviceContext) EnableClaimMode

func (dc *DeviceContext) EnableClaimMode(duration time.Duration) error

EnableClaimMode activates the device's "claim mode", i.e. allows the device to be added to a different home. The claim mode will be active for the time period specified by "duration".

func (*DeviceContext) GetInfo

func (dc *DeviceContext) GetInfo() (*DeviceInfo, error)

GetInfo fetches the device's information from MODE.

func (*DeviceContext) SetPKCS12ClientCertificate

func (dc *DeviceContext) SetPKCS12ClientCertificate(fileName string, password string, insecureSkipVerify bool) error

SetPKCS12ClientCertificate set PKCS#12 client certificate to device context. Set fileName and password of the certificate. If insecureSkipVerify is true, TLS accepts any certificate presented by the server and any host name in that certificate. This should be used only for testing.

type DeviceEvent

type DeviceEvent struct {
	EventType string                 `json:"eventType"`
	EventData map[string]interface{} `json:"eventData,omitempty"`
	// contains filtered or unexported fields
}

DeviceEvent represents an event to be sent to the MODE cloud.

type DeviceInfo

type DeviceInfo struct {
	ID          uint64 `json:"id"`
	ProjectID   uint64 `json:"projectId"`
	Name        string `json:"name"`
	Tag         string `json:"tag"`
	DeviceClass string `json:"deviceClass"`
}

DeviceInfo contains the key information fetched from the MODE API.

func (*DeviceInfo) String

func (d *DeviceInfo) String() string

type DeviceSubscribeBulkDataResponse added in v2.4.0

type DeviceSubscribeBulkDataResponse struct {
	StreamID string
	// contains filtered or unexported fields
}

DeviceSubscribeBulkDataResponse is request of subscribing bulk data response topic.

type DeviceSyncedBulkData

type DeviceSyncedBulkData struct {
	StreamID string
	Blob     []byte
	// contains filtered or unexported fields
}

BulkData represents a batch of opaque data to be sent to the MODE cloud.

type KeyValue

type KeyValue struct {
	Key              string      `json:"key"`
	Value            interface{} `json:"value"`
	ModificationTime time.Time   `json:"modificationTime"`
}

KeyValue represents a key-value pair stored in the Device Data Proxy.

func GetAllKeyValues

func GetAllKeyValues() ([]*KeyValue, error)

GetAllKeyValues returns all key-value pairs stored in the Device Data Proxy. It returns an error if the device connection session is in idle state. When the session is in recovery state, the key-value pairs returned will contain the last known values in the local memory cache.

Note: Functions that access the Device Data Proxy should be called only after the local cache has been loaded. To get notified of this event, use SetKeyValuesReadyCallback() to assign a callback function.

func GetKeyValue

func GetKeyValue(key string) (*KeyValue, error)

GetKeyValue looks up a key-value pair from the Device Data Proxy. It returns an error if the device connection session is in idle state. When the session is in recovery state, the key-value pair returned will contain the last known value in the local memory cache.

Note: Functions that access the Device Data Proxy should be called only after the local cache has been loaded. To get notified of this event, use SetKeyValuesReadyCallback() to assign a callback function.

func (*KeyValue) String

func (kv *KeyValue) String() string

type KeyValueDeletedCallback

type KeyValueDeletedCallback func(*DeviceContext, string)

A callback function that is invoked when a key-value pair has been deleted. The key of the deleted key-value is passed in the argument.

type KeyValueStoredCallback

type KeyValueStoredCallback func(*DeviceContext, *KeyValue)

A callback function that is invoked when a key-value pair has been added or updated.

type KeyValuesReadyCallback

type KeyValuesReadyCallback func(*DeviceContext)

A callback function that is invoked when the Device Data Proxy is ready to be accessed.

type QOSLevel

type QOSLevel int

QoS level of message delivery. This is used in sending events to MODE.

const (
	// QoS 0 - message delivery is not guaranteed.
	QOSAtMostOnce QOSLevel = iota

	// QoS 1 - message is delivered at least once, but duplicates may happen.
	QOSAtLeastOnce

	// QoS 2 - message is always delivered exactly once. This is currently not supported.
	QOSExactlyOnce
)

type RESTError

type RESTError struct {
	// contains filtered or unexported fields
}

RESTError represents an error returned by the MODE REST API.

func (*RESTError) Data

func (e *RESTError) Data() map[string]interface{}

Data returns any additional data associated with this error, or nil.

func (*RESTError) Error

func (e *RESTError) Error() string

Error returns a summary of the error.

func (*RESTError) Reason

func (e *RESTError) Reason() string

Reason returns the specific reason for the error.

func (*RESTError) StatusCode

func (e *RESTError) StatusCode() int

StatusCode returns the HTTP status code provided by the API server.

type SessionState

type SessionState int

SessionState represents a state of the device's connection session.

const (
	// Device is currently not connected to the MODE cloud.
	SessionIdle SessionState = iota

	// Device is currently connected to the MODE cloud.
	SessionActive

	// Connection to the MODE cloud has been disrupted and is waiting to
	// be re-established.
	SessionRecovering
)

func GetSessionState

func GetSessionState() SessionState

GetSessionState returns the current state of the device's connection session.

func (SessionState) String

func (s SessionState) String() string

type SessionStateCallback

type SessionStateCallback func(SessionState)

A callback function that is invoked when the device's connection session changes state.

Directories

Path Synopsis
examples
ddp command
This is an example of how a device can communicate with the MODE cloud via Device Data Proxy.
This is an example of how a device can communicate with the MODE cloud via Device Data Proxy.
echo command
In this example, the device sends an "echo" event whenever it receives a "doEcho" command.
In this example, the device sends an "echo" event whenever it receives a "doEcho" command.
mutual_tls_ddp command
This is an example of how a device can communicate with the MODE cloud via Device Data Proxy.
This is an example of how a device can communicate with the MODE cloud via Device Data Proxy.
mutual_tls_echo command
In this example, the device sends an "echo" event whenever it receives a "doEcho" command.
In this example, the device sends an "echo" event whenever it receives a "doEcho" command.
Package packet implements functionality for encoding and decoding MQTT 3.1.1 (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/) packets.
Package packet implements functionality for encoding and decoding MQTT 3.1.1 (http://docs.oasis-open.org/mqtt/mqtt/v3.1.1/) packets.

Jump to

Keyboard shortcuts

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