Giter Club home page Giter Club logo

go-sdk's Introduction

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.

go-sdk's People

Contributors

ni5ni6 avatar rayalex avatar

Stargazers

 avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

go-sdk's Issues

Support API for asset-level pub and sub

Currently all publish and subscribe operations are going though Device API (e.g. device.Publish(...)).

We can introduce the following to enhance it:

  • asset.Publish(state)
  • asset.Subscribe(chan command)

Suppress travis-ci build on Readme changes

Any changes to Readme file trigger TravisCI build. We should add it to the ignore list in order not to rebuild each time docs change, as we currently can't run examples found in Readme file.

Publish device state

AllThingsTalk supports sending multiple asset states in one message, which makes sense when trying to preserve bandwidth and ensure all states are set in one go.

Proposal:

  • device.PublishStates(...) should accept a list of states. In the background, this could either translate to sending one device state message or multiple asset states message. Former is by default. It should also be possible to define custom payload format as well (for ABCL).

  • Custom payload formats may be defined with abcl struct tag (depengind on how ABCL is promoted).

  • We could also support builders to bundle asset states and send them all in one go.

  • Device should have additional encoding configuration option which can be used to specify the encoding - if necessary user choose choose between JSON, CBOR or custom binary format. (?)

  • Prepare API proposal for Binary payload

  • Prepare API proposal for Device State

  • Review

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.