adafruitio

package module
v2.0.0-...-2bfd35c Latest Latest
Warning

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

Go to latest
Published: Jun 28, 2022 License: MIT Imports: 11 Imported by: 0

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.18 or better. Running tests uses the github.com/stretchr/testify library. To run tests, run:

$ go test ./...

Usage

First, add the package:

$ go get github.com/adafruit/io-client-go/v2

Then import it:

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

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

Authentication for Adafruit IO is managed by providing your Adafruit IO username and token. The token is sent 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_USERNAME"), 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"}
feed := client.Feed.Create(newFeed)

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

feed, _, ferr := client.Feed.Get("my-new-feed")
client.SetFeed(feed)
client.Data.Create(&adafruitio.Data{Value: 100})

More detailed example usage can be found in the ./examples directory

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"
	"os"

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

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

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

	// set custom API URL
	client.SetBaseURL("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"
	APIPath = "/api/v2"
)
View Source
const (
	Version = "2.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 {

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

func NewClient

func NewClient(username, 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) GetUserKey

func (c *Client) GetUserKey() (username string, apikey string)

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

func (c *Client) SetBaseURL(baseURL string)

SetBaseURL updates the base URL to use. Mainly here for use in unit testing

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           string  `json:"id,omitempty"`
	Value        string  `json:"value,omitempty"`
	FeedID       int     `json:"feed_id,omitempty"`
	FeedKey      string  `json:"feed_key,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 string) (*Response, error)

Delete the Data identified by the given ID.

func (*DataService) First

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

First returns the first Data in the stream.

func (*DataService) Get

func (s *DataService) Get(id string) (*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) Update

func (s *DataService) Update(id string, 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"`
	Username      string `json:"username,omitempty"`
	Owner         *Owner `json:"owner,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"`
	StatusNotify  bool   `json:"status_notify,omitempty"`
	StatusTimeout int    `json:"status_timeout,omitempty"`
	Shared        bool   `json:"is_shared,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(key string) (*Response, error)

Delete the Feed identified by the given ID.

func (*FeedService) Get

func (s *FeedService) Get(key string) (*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(key string, 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"`
	Key         string  `json:"key,omitempty"`
	Owner       *Owner  `json:"owner,omitempty"`
	UserID      int     `json:"user_id,omitempty"`
	Description string  `json:"description,omitempty"`
	CreatedAt   string  `json:"created_at,omitempty"`
	UpdatedAt   string  `json:"updated_at,omitempty"`
	Feeds       []*Feed `json:"feeds,omitempty"`
	Visibility  string  `json:"visibility"`
	Shared      bool    `json:"is_shared,omitempty"`
}

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(key string) (*Response, error)

Delete the Group identified by the given ID.

func (*GroupService) Get

func (s *GroupService) Get(key string) (*Group, *Response, error)

Get returns the Group record identified by the given ID

func (*GroupService) Update

func (s *GroupService) Update(key string, 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 Owner

type Owner struct {
	ID       int    `json:"id,omitempty"`
	Username string `json:"username,omitempty"`
}

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