sdk

package module
v1.0.1 Latest Latest
Warning

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

Go to latest
Published: May 10, 2018 License: Apache-2.0 Imports: 12 Imported by: 0

README

Go SDK Build Status Go Report Card RELEASE GoDoc LICENSE

AllThingsTalk Golang SDK provides APIs to implement AllThingsTalk devices.

Installation

Install Go, and then:

go get -u github.com/allthingstalk/go-sdk

Import:

import "github.com/allthingstalk/go-sdk"

Quickstart

You should create an AllThingsTalk Maker account, and a simple device. All examples require DeviceID and DeviceToken, which can be found under Device Settings.

package main

import (
	"github.com/allthingstalk/go-sdk"
	"time"
)

const (
	deviceID    = "<YOUR_DEVICE_ID>"
	deviceToken = "<YOUR_DEVICE_TOKEN>"
)

// A device which counts from 1 to 10 with a 1-second interval
func main() {
	// initialize a device
	device, err := sdk.NewDevice(deviceID, deviceToken)
	if err != nil {
		panic(err)
	}

	// add an asset named `counter` of `Integer` type
	counter, err := device.AddInteger("counter")
	if err != nil {
		panic(err)
	}
	
	// just count from 1 to 10 and send that value to Maker
	for i := 1; i <= 10; i++ {
		time.Sleep(1 * time.Second)
		device.Publish(counter, i)
	}
}

HowTo

Please go through examples for more comprehensive tutorials on how to use this package.

Initializing a device

To manage a device, you must obtain a DeviceID (which is an unique device identifier within AllThingsTalk Maker) and DeviceToken (which this SDK uses to obtain access to APIs), both of which can be found on Device Settings page within AllThingsTalk Maker.

Device can be initialized by:

device, _ := sdk.NewDevice(deviceID, deviceToken)

You can also customize behind-the-scenes functionality, in this case - HTTP and MQTT clients, by optionally providing endpoints for them. By default these are securely connecting to Maker:

device, _ := sdk.NewDevice("<DEVICE_ID>", "<DEVICE_TOKEN>",
	sdk.WithHTTP("https://api.allthingstalk.io"),
	sdk.WithMQTT("ssl://api.allthingstalk.io:8883"))
Creating Assets

Assets represent a typed property of a device which can be used either to sense some physical value (a Sensor), or send a value to a device (an Actuator). Each asset is described by name (unique identifier within a device) and profile (a JSON Schema which describes data format).

Creating simple Sensors

Sensors of simple types (integers, number, boolean, string) can be created by Add* functions of a Device:

// create a Sensor named `hello` with `integer` profile.
sensor, _ := device.AddInteger("hello")

Please check API reference for all available methods.

Creating Sensors and Actuators

Sensors and Actuators can be created with NewSensor and NewActuator functions. These functions expect name (unique identifier within a device) and profile (JSON Schema describing data).

Afterwards, just to device.Add(...) to create that asset on the AllThingsTalk maker:

numberSensor := sdk.NewSensor("number", profile.Number())
device.Add(numberSensor)
Profiles
import "github.com/allthingstalk/go-sdk/profile"

Profiles are JSON Schemas which describe kind of data an Asset is working with. When creating an asset, we have to specify it's profile as well. Simplest way of doing this is using one of the pre-set types in profile package:

profile := profile.String()

These functions just wrap profile.New(...) and provide schema type.

Alternatively, you can specify a complete JSON schema for more complex profile types:


// a profile describing a Geo location
const locationProfile = `
{
   "type":"object",
   "properties":{
	  "lat":  {"type": "number"},
	  "long": {"type": "number"}
   }
}`

// try creating it from JSON string
prof, err := profile.JSON(locationProfile)
if err != nil {
	panic(err)
}

// create a location sensor asset with a location profile
location := sdk.NewAsset("location", sdk.Sensor, prof)

Check out profile package for more details.

Publishing states

You can publish sensor values using a device.Publish(...) function:

device.Publish(sensor, "value")

Since all sensor state changes carry a timestamp, by default it's set to current UTC time if it's not provided. In order to set a custom one, just use device.PublishState(...):

device.PublishState(sensor, State{Value: "hello", Timestamp: time.Now().UTC()})
Listening to commands

AllThingsTalk Maker can also send commands to a device. You can set a global command handler which will be invoked every time command is received:

func onMessage(command sdk.Command) {
	fmt.Printf("Received command for %s: %v with timestamp %s\n", command.Name, command.Value, command.Timestamp)
}

func main() {
	// ...
	device.SetCommandHandler(onMessage)
}
Error handling

Most of the SDK APIs return an error in case something goes wrong. As per Go's idiomatic usage, it's always recommended to use something like:

if err != nil {
	// handle error...
}

To check for any error conditions. This library uses plain error model. If you need stack traces, or extended functionality, your production application should probably use pkg/errors or similar.

Logging

You can attach loggers for debugging purposes:

sdk.ERROR = log.New(os.Stdout, "", 0)

Available loggers are ERROR, CRITICAL, WARN, INFO and DEBUG. Go's logging infrastructure being limited as is, it's generally recommended that go-logging or similar is used in production applications.

Documentation

Overview

Package sdk implements a device SDK for AllThingsTalk IoT Platform.

AllThingsTalk Maker is a IoT device prototyping platform and this SDK aims to help developers who prefer Go language use it.

Let's start with the simplest example possible - creating a device which counts from 1 to 10. Start off by going to AllThingsTalk Maker and creating your account and a device (a Custom device will do just fine). Next, let's write some code:

import (
	"fmt"
	"time"
	"github.com/allthingstalk/go-sdk"
)

func main() {
	device, err := sdk.NewDevice("<DEVICE_ID>", "<DEVICE_TOKEN>")
	if err != nil {
		panic(err)
	}

	counter, _ := device.AddInteger("counter")

	for i := 1; i <= 10; i++ {
		time.Sleep(1 * time.Second)
		fmt.Println(i)
		device.Publish(counter, i)
	}
}

You should replace <DEVICE_ID> and <DEVICE_TOKEN> with values that can be found in Device Settings page. If you run the example, the 'counter' asset should be created, and you should see it counting from 1 to 10.

That's it! For more comprehensive examples please check out the repository's README.

Index

Constants

View Source
const (
	// UA identifies the SDK
	UA = "ATTalk-GoSDK/1.0.1"
)

Constants

Variables

View Source
var (
	// ErrAssetNotAdded is returned when asset could not be added
	ErrAssetNotAdded = errors.New("Could not Add Asset")

	// ErrCountNotFetchState is returned when current state could not be obtained
	ErrCountNotFetchState = errors.New("Count not obtain current Asset state")
)

HTTP Errors

View Source
var (
	ERROR *log.Logger
	INFO  *log.Logger
	DEBUG *log.Logger
)

Loggers

View Source
var (
	// ErrMqttNotEstablished is returned when there's an issue with establishing MQTT connection
	ErrMqttNotEstablished = errors.New("Unable to connect to MQTT server, please verify your settings")
)

MQTT Errors

Functions

This section is empty.

Types

type Asset

type Asset struct {
	Kind    Kind        `json:"is"`
	Name    string      `json:"name"`
	Profile interface{} `json:"profile"`
}

Asset defines a structure holding some basic information about an asset, like it's kind and supported data type (profile).

func NewActuator

func NewActuator(name string, profile profile.Profile) *Asset

NewActuator creates a new Actuator asset with a given profile.

func NewAsset

func NewAsset(name string, kind Kind, profile profile.Profile) *Asset

NewAsset creates an asset with a name, kind and profile.

func NewSensor

func NewSensor(name string, profile profile.Profile) *Asset

NewSensor creates a new Sensor asset with a given profile.

type Command

type Command struct {
	Name      string
	Timestamp time.Time   `json:"at"`
	Value     interface{} `json:"value"`
}

Command message describing command intended for an asset.

type CommandHandler

type CommandHandler func(command Command)

CommandHandler can be attached to function to listen to incoming commands.

type Device

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

Device is a representation of a device on AllThingsTalk platform.

func NewDevice

func NewDevice(deviceID string, token string, options ...Option) (*Device, error)

NewDevice creates a new device using a DeviceId and token.

func (*Device) Add

func (device *Device) Add(a *Asset) error

Add adds an asset to a device.

func (*Device) AddBoolean

func (device *Device) AddBoolean(name string) (*Asset, error)

AddBoolean adds an Boolean sensor to a device.

func (*Device) AddInteger

func (device *Device) AddInteger(name string) (*Asset, error)

AddInteger adds an Integer sensor to a device.

func (*Device) AddNumber

func (device *Device) AddNumber(name string) (*Asset, error)

AddNumber adds an Number sensor to a device.

func (*Device) AddString

func (device *Device) AddString(name string) (*Asset, error)

AddString adds an String asset to a device.

func (*Device) GetState

func (device *Device) GetState(asset *Asset) (*State, error)

GetState obtains last known asset state.

func (*Device) Publish

func (device *Device) Publish(a *Asset, value interface{})

Publish publishes raw asset value. Timestamp is set to current UTC time.

func (*Device) PublishState

func (device *Device) PublishState(asset *Asset, state State)

PublishState publishes asset state. Client can supply value and timestamp.

func (*Device) SetCommandHandler

func (device *Device) SetCommandHandler(handler CommandHandler)

SetCommandHandler allows for setting a function to handle incoming commands.

type Kind

type Kind string

Kind of an asset. Can be `Sensor` or `Actuator`

const (
	Sensor   Kind = "sensor"
	Actuator Kind = "actuator"
)

Existing asset kinds. Can be either `sensor` or an `actuator`.

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option is a single option configuration of a device

func WithHTTP

func WithHTTP(endpoint string) Option

WithHTTP sets HTTP REST API endpoint.

func WithMQTT

func WithMQTT(endpoint string) Option

WithMQTT sets MQTT API endpoint.

type Options

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

Options represents general device options, like URL endpoints.

func (*Options) SetAPI

func (o *Options) SetAPI(endpoint string) *Options

SetAPI sets HTTP REST API endpoint.

func (*Options) SetMqtt

func (o *Options) SetMqtt(endpoint string) *Options

SetMqtt sets MQTT API endpoint.

type State

type State struct {
	Timestamp time.Time   `json:"at"`
	Value     interface{} `json:"value"`
}

State message describing asset state in time.

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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