mode

package module
v1.1.4 Latest Latest
Warning

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

Go to latest
Published: Sep 13, 2017 License: MIT Imports: 17 Imported by: 0

README

MODE Device SDK for Go

GoDoc

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

Installation

You can install this package simply by doing:

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

However, we strongly recommend you use Glide to manage your package dependencies. This package comes with its own glide.yaml file so that the secondary dependencies are taken care of. To use Glide to install this package, simply do:

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

Using the SDK

The default package name is mode. A trivial example:

package main

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

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)
    }
}

See more examples here.

Documentation

See the full API documentation here.

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

Documentation

Overview

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

If a device wants to receive commands from and send events to the MODE cloud, it must start a connection session. You can choose to connect via HTTP/websocket or MQTT.

Both incoming commands and outgoing events are queued. If the websocket or MQTT 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 (
	ErrorSessionAlreadyStarted = errors.New("session already started")
	ErrorSessionNotStarted     = errors.New("not in session")
	ErrorSessionRecovering     = errors.New("session is recovering")
)

Functions

func ConfigureDeviceEventSender

func ConfigureDeviceEventSender(maxAttempts uint, retryInterval time.Duration)

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 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 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 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 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, useMQTT bool) error

StartSession starts a device connection session for the specified device. By default, the connection is made using HTTP/websocket. If useMQTT is true, the session will connect by MQTT instead

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.

Types

type CommandHandler

type CommandHandler func(*DeviceContext, *DeviceCommand)

A callback function that handles a device command.

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
}

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.

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.

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 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
echo
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.

Jump to

Keyboard shortcuts

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