adafruitio

package module
v0.0.0-...-2a7144d Latest Latest
Warning

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

Go to latest
Published: Jun 13, 2016 License: MIT Imports: 11 Imported by: 10

README

talk to adafruit io from Go

GoDoc Build Status

A go client library for talking to your io.adafruit.com account.

Requires go version 1.2 or better. Running tests requires the github.com/stretchr/testify library, which can be installed with:

$ go get github.com/stretchr/testify

Usage

import "github.com/adafruit/io-client-go"

The io-client-go repository provides the adafruitio package.

Authentication for Adafruit IO is managed by providing your Adafruit IO token in the head of all web requests via the X-AIO-Key header. This is handled for you by the client library, which expects you API Token when it is initialized.

We recommend keeping the Token in an environment variable to avoid including it directly in your code.

client := adafruitio.NewClient(os.Getenv("ADAFRUIT_IO_KEY"))
feeds, _, err := adafruitio.Feed.All()

Some API calls expect parameters, which must be provided when making the call.

feed := &aio.Feed{Name: "my-new-feed"}
client.Feed.Create(newFeed)

Data related API calls expect a Feed to be set before the call is made.

NOTE: the Feed doesn't have to exist yet if you're using the Data.Send() method, but it still needs to be set. If you're relying on the Data API to create the Feed, make sure you set the Key attribute on the new Feed.

feed := &aio.Feed{Name: "My New Feed", Key: "my-new-feed"}
client.SetFeed(newFeed)
client.Data.Send(&adafruitio.Data{Value: 100})

For full package documentation, visit the godoc page at https://godoc.org/github.com/adafruit/io-client-go

License

Copyright (c) 2016 Adafruit Industries. Licensed under the MIT license.

Contributing

  • Fork it ( http://github.com/adafruit/io-client-go/fork )
  • Create your feature branch (git checkout -b my-new-feature)
  • Commit your changes (git commit -am 'Add some feature')
  • Push to the branch (git push origin my-new-feature)
  • Create new Pull Request

adafruit invests time and resources providing this open source code. please support adafruit and open-source hardware by purchasing products from adafruit.

Documentation

Overview

The adafruitio package is a simple HTTP client for accessing v1 of the Adafruit IO REST API at https://io.adafruit.com.

import "github.com/adafruit/io-client-go"

Authentication for Adafruit IO is managed by providing your Adafruit IO token in the head of all web requests via the `X-AIO-Key` header. This is handled for you by the client library, which expects you API Token when it is initialized.

We recommend keeping the Token in an environment variable to avoid including it directly in your code.

client := adafruitio.NewClient(os.Getenv("ADAFRUIT_IO_KEY"))
feeds, _, err := adafruitio.Feed.All()

Some API calls expect parameters, which must be provided when making the call.

feed := &aio.Feed{Name: "my-new-feed"}
client.Feed.Create(newFeed)

Data related API calls expect a Feed to be set before the call is made.

**NOTE:** the Feed doesn't have to exist yet if you're using the `Data.Send()` method, but it still needs to be set. If you're relying on the Data API to create the Feed, make sure you set the `Key` attribute on the new Feed.

feed := &aio.Feed{Name: "My New Feed", Key: "my-new-feed"}
client.SetFeed(newFeed)
client.Data.Send(&adafruitio.Data{Value: 100})

You can see the v1 Adafruit IO REST API documentation online at https://io.adafruit.com/api/docs/

Example
package main

import (
	"encoding/json"
	"fmt"
	"net/url"
	"os"

	"github.com/adafruit/io-client-go"
)

var (
	key   string
	feeds []*adafruitio.Feed
)

func main() {
	// Load ADAFRUIT_IO_KEY from environment
	client := adafruitio.NewClient(os.Getenv("ADAFRUIT_IO_KEY"))

	// set custom API URL
	client.BaseURL, _ = url.Parse("http://localhost:3002")

	// Get the list of all available feeds
	feeds, _, err := client.Feed.All()
	if err != nil {
		fmt.Println("UNEXPECTED ERROR!", err)
		panic(err)
	}

	// View the resulting feed list
	for _, feed := range feeds {
		jsonBytes, _ := json.MarshalIndent(feed, "", "  ")
		fmt.Printf("[%v]\n", feed.Name)
		fmt.Println(string(jsonBytes))
	}
}
Output:

Index

Examples

Constants

View Source
const (
	BaseURL = "https://io.adafruit.com"
)
View Source
const (
	Version = "1.0.0"
)

Variables

This section is empty.

Functions

func CheckResponse

func CheckResponse(r *http.Response) error

CheckResponse checks the API response for errors, and returns them if present. A response is considered an error if it has a status code outside the 200 range.

adapted from https://github.com/google/go-github

Types

type AIOError

type AIOError struct {
	Message string `json:"error"`
}

type Client

type Client struct {

	// Base URL for API requests. Defaults to public adafruit io URL.
	BaseURL *url.URL

	APIKey string

	// Services that make up adafruit io.
	Data  *DataService
	Feed  *FeedService
	Group *GroupService
	// contains filtered or unexported fields
}

func NewClient

func NewClient(key string) *Client

func (*Client) Do

func (c *Client) Do(req *http.Request, v interface{}) (*Response, error)

Do sends an API request and returns the API response. The API response is JSON decoded and stored in the value pointed to by v, or returned as an error if an API error has occurred. If v implements the io.Writer interface, the raw response body will be written to v, without attempting to first decode it.

adapted from https://github.com/google/go-github

func (*Client) NewRequest

func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error)

NewRequest creates an API request. A relative URL can be provided in urlStr, in which case it is resolved relative to the BaseURL of the Client. Relative URLs should always be specified without a preceding slash. If specified, the value pointed to by body is JSON encoded and included as the request body.

adapted from https://github.com/google/go-github

func (*Client) SetFeed

func (c *Client) SetFeed(feed *Feed)

SetFeed takes a Feed record as a parameter and uses that feed for all subsequent Data related API calls.

A Feed must be set before making calls to the Data service.

type Data

type Data struct {
	ID           int     `json:"id,omitempty"`
	Value        string  `json:"value,omitempty"`
	Position     string  `json:"position,omitempty"`
	FeedID       int     `json:"feed_id,omitempty"`
	GroupID      int     `json:"group_id,omitempty"`
	Expiration   string  `json:"expiration,omitempty"`
	Latitude     float64 `json:"lat,omitempty"`
	Longitude    float64 `json:"lon,omitempty"`
	Elevation    float64 `json:"ele,omitempty"`
	CompletedAt  string  `json:"completed_at,omitempty"`
	CreatedAt    string  `json:"created_at,omitempty"`
	UpdatedAt    string  `json:"updated_at,omitempty"`
	CreatedEpoch float64 `json:"created_epoch,omitempty"`
}

Data are the values contained by a Feed.

type DataFilter

type DataFilter struct {
	StartTime string `url:"start_time,omitempty"`
	EndTime   string `url:"end_time,omitempty"`
}

type DataService

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

func (*DataService) All

func (s *DataService) All(opt *DataFilter) ([]*Data, *Response, error)

All returns all Data for the currently selected Feed. See Client.SetFeed() for details on selecting a Feed.

func (*DataService) Create

func (s *DataService) Create(dp *Data) (*Data, *Response, error)

Create adds a new Data value to an existing Feed.

func (*DataService) Delete

func (s *DataService) Delete(id int) (*Response, error)

Delete the Data identified by the given ID.

func (*DataService) Get

func (s *DataService) Get(id int) (*Data, *Response, error)

Get returns a single Data element, identified by the given ID parameter.

func (*DataService) Last

func (s *DataService) Last() (*Data, *Response, error)

Last returns the last Data in the stream.

func (*DataService) Next

func (s *DataService) Next() (*Data, *Response, error)

Next returns the next Data in the stream.

func (*DataService) Prev

func (s *DataService) Prev() (*Data, *Response, error)

Prev returns the previous Data in the stream.

func (*DataService) Search

func (s *DataService) Search(filter *DataFilter) ([]*Data, *Response, error)

Search has the same response format as All, but it accepts optional params with which your data can be queried.

func (*DataService) Send

func (s *DataService) Send(dp *Data) (*Data, *Response, error)

Send adds a new Data value to an existing Feed, or will create the Feed if it doesn't already exist.

func (*DataService) Update

func (s *DataService) Update(id interface{}, data *Data) (*Data, *Response, error)

Update takes an ID and a Data record, updates the record idendified by ID, and returns a new, updated Data instance.

type ErrorResponse

type ErrorResponse struct {
	Response *http.Response // HTTP response that carried the error message
	Message  string
	AIOError *AIOError
}

ErrorResponse reports one or more errors caused by an API request.

func (*ErrorResponse) Error

func (r *ErrorResponse) Error() string

type Feed

type Feed struct {
	ID          int    `json:"id,omitempty"`
	Name        string `json:"name,omitempty"`
	Key         string `json:"key,omitempty"`
	Description string `json:"description,omitempty"`
	UnitType    string `json:"unit_type,omitempty"`
	UnitSymbol  string `json:"unit_symbol,omitempty"`
	History     bool   `json:"history,omitempty"`
	Visibility  string `json:"visibility,omitempty"`
	License     string `json:"license,omitempty"`
	Enabled     bool   `json:"enabled,omitempty"`
	LastValue   string `json:"last_value,omitempty"`
	Status      string `json:"status,omitempty"`
	GroupID     int    `json:"group_id,omitempty"`
	CreatedAt   string `json:"created_at,omitempty"`
	UpdatedAt   string `json:"updated_at,omitempty"`
}

type FeedService

type FeedService struct {
	// CurrentFeed is the Feed used for all Data access.
	CurrentFeed *Feed
	// contains filtered or unexported fields
}

func (*FeedService) All

func (s *FeedService) All() ([]*Feed, *Response, error)

All lists all available feeds.

func (*FeedService) Create

func (s *FeedService) Create(feed *Feed) (*Feed, *Response, error)

Create takes a Feed record, creates it, and returns the updated record or an error.

func (*FeedService) Delete

func (s *FeedService) Delete(id interface{}) (*Response, error)

Delete the Feed identified by the given ID.

func (*FeedService) Get

func (s *FeedService) Get(id interface{}) (*Feed, *Response, error)

Get returns the Feed record identified by the given parameter. Parameter can be the Feed's Name, Key, or ID.

func (*FeedService) Path

func (s *FeedService) Path(suffix string) (string, error)

Path generates a Feed-specific path with the given suffix.

func (*FeedService) Update

func (s *FeedService) Update(id interface{}, feed *Feed) (*Feed, *Response, error)

Update takes an ID and a Feed record, updates it, and returns an updated record instance or an error.

Only the Feed Name and Description can be modified.

type Group

type Group struct {
	ID          int      `json:"id,omitempty"`
	Name        string   `json:"name,omitempty"`
	Description string   `json:"description,omitempty"`
	CreatedAt   string   `json:"created_at,omitempty"`
	UpdatedAt   string   `json:"updated_at,omitempty"`
	Source      string   `json:"source,omitempty"`
	SourceKeys  []string `json:"source_keys,omitempty"`
	Feeds       []*Feed  `json:"feeds,omitempty"`
	Visibility  string   `json:"visibility"`
}

type GroupService

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

func (*GroupService) All

func (s *GroupService) All() ([]*Group, *Response, error)

All returns all Groups for the current account.

func (*GroupService) Create

func (s *GroupService) Create(g *Group) (*Group, *Response, error)

Create makes a new Group and either returns a new Group instance or an error.

func (*GroupService) Delete

func (s *GroupService) Delete(id interface{}) (*Response, error)

Delete the Group identified by the given ID.

func (*GroupService) Get

func (s *GroupService) Get(id interface{}) (*Group, *Response, error)

Get returns the Group record identified by the given ID

func (*GroupService) Update

func (s *GroupService) Update(id interface{}, group *Group) (*Group, *Response, error)

Update takes an ID and a Group record, updates it, and returns a new Group instance or an error.

type Response

type Response struct {
	*http.Response
}

Response wraps http.Response and adds fields unique to Adafruit's API.

func (*Response) Debug

func (r *Response) Debug()

Directories

Path Synopsis
examples
data
Demo showing Data listing, creation, updating, and deletion.
Demo showing Data listing, creation, updating, and deletion.
feeds
Demo showing feed listing, creation, updating, and deletion.
Demo showing feed listing, creation, updating, and deletion.
groups
Demo showing Group listing, creation, updating, and deletion.
Demo showing Group listing, creation, updating, and deletion.

Jump to

Keyboard shortcuts

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