Back to godoc.org
gobot.io/x/gobot

Package gobot

v1.14.0
Latest Go to latest

The latest major version is .

Published: Oct 15, 2019 | License: Apache-2.0 | Module: gobot.io/x/gobot

Overview

Package gobot is the primary entrypoint for Gobot (http://gobot.io), a framework for robotics, physical computing, and the Internet of Things written using the Go programming language .

It provides a simple, yet powerful way to create solutions that incorporate multiple, different hardware devices at the same time.

Classic Gobot

Here is a "Classic Gobot" program that blinks an LED using an Arduino:

package main

import (
	"time"

	"gobot.io/x/gobot"
	"gobot.io/x/gobot/drivers/gpio"
	"gobot.io/x/gobot/platforms/firmata"
)

func main() {
	firmataAdaptor := firmata.NewAdaptor("/dev/ttyACM0")
	led := gpio.NewLedDriver(firmataAdaptor, "13")

	work := func() {
		gobot.Every(1*time.Second, func() {
			led.Toggle()
		})
	}

	robot := gobot.NewRobot("bot",
		[]gobot.Connection{firmataAdaptor},
		[]gobot.Device{led},
		work,
	)

	robot.Start()
}

Metal Gobot

You can also use Metal Gobot and pick and choose from the various Gobot packages to control hardware with nothing but pure idiomatic Golang code. For example:

package main

import (
	"gobot.io/x/gobot/drivers/gpio"
	"gobot.io/x/gobot/platforms/intel-iot/edison"
	"time"
)

func main() {
	e := edison.NewAdaptor()
	e.Connect()

	led := gpio.NewLedDriver(e, "13")
	led.Start()

	for {
		led.Toggle()
		time.Sleep(1000 * time.Millisecond)
	}
}

Master Gobot

Finally, you can use Master Gobot to add the complete Gobot API or control swarms of Robots:

package main

import (
	"fmt"
	"time"

	"gobot.io/x/gobot"
	"gobot.io/x/gobot/api"
	"gobot.io/x/gobot/platforms/sphero"
)

func NewSwarmBot(port string) *gobot.Robot {
	spheroAdaptor := sphero.NewAdaptor(port)
	spheroDriver := sphero.NewSpheroDriver(spheroAdaptor)
	spheroDriver.SetName("Sphero" + port)

	work := func() {
		spheroDriver.Stop()

		spheroDriver.On(sphero.Collision, func(data interface{}) {
			fmt.Println("Collision Detected!")
		})

		gobot.Every(1*time.Second, func() {
			spheroDriver.Roll(100, uint16(gobot.Rand(360)))
		})
		gobot.Every(3*time.Second, func() {
			spheroDriver.SetRGB(uint8(gobot.Rand(255)),
				uint8(gobot.Rand(255)),
				uint8(gobot.Rand(255)),
			)
		})
	}

	robot := gobot.NewRobot("sphero",
		[]gobot.Connection{spheroAdaptor},
		[]gobot.Device{spheroDriver},
		work,
	)

	return robot
}

func main() {
	master := gobot.NewMaster()
	api.NewAPI(master).Start()

	spheros := []string{
		"/dev/rfcomm0",
		"/dev/rfcomm1",
		"/dev/rfcomm2",
		"/dev/rfcomm3",
	}

	for _, port := range spheros {
		master.AddRobot(NewSwarmBot(port))
	}

	master.Start()
}

Copyright (c) 2013-2018 The Hybrid Group. Licensed under the Apache 2.0 license.

Index

Examples

Constants

const (
	EveryWorkKind = "every"
	AfterWorkKind = "after"
)

func After

func After(t time.Duration, f func())

After triggers f after t duration.

Example

Code:

package main

import (
	"fmt"
	"gobot.io/x/gobot"
	"time"
)

func main() {
	gobot.After(1*time.Second, func() {
		fmt.Println("Hello")
	})
}

func DefaultName

func DefaultName(name string) string

DefaultName returns a sensible random default name for a robot, adaptor or driver

func Every

func Every(t time.Duration, f func()) *time.Ticker

Every triggers f every t time.Duration until the end of days, or when a Stop() is called on the Ticker that is returned by the Every function. It does not wait for the previous execution of f to finish before it fires the next f.

Example

Code:

package main

import (
	"fmt"
	"gobot.io/x/gobot"
	"time"
)

func main() {
	gobot.Every(1*time.Second, func() {
		fmt.Println("Hello")
	})
}

func FromScale

func FromScale(input, min, max float64) float64

FromScale returns a converted input from min, max to 0.0...1.0.

Example

Code:

package main

import (
	"fmt"
	"gobot.io/x/gobot"
)

func main() {
	fmt.Println(gobot.FromScale(5, 0, 10))
}
0.5

func Rand

func Rand(max int) int

Rand returns a positive random int up to max

Example

Code:

package main

import (
	"fmt"
	"gobot.io/x/gobot"
)

func main() {
	i := gobot.Rand(100)
	fmt.Printf("%v is > 0 && < 100", i)
}

func Rescale

func Rescale(input, fromMin, fromMax, toMin, toMax float64) float64

Rescale performs a direct linear rescaling of a number from one scale to another.

func ToScale

func ToScale(input, min, max float64) float64

ToScale returns a converted input from 0...1 to min...max scale. If input is less than min then ToScale returns min. If input is greater than max then ToScale returns max

Example

Code:

package main

import (
	"fmt"
	"gobot.io/x/gobot"
)

func main() {
	fmt.Println(gobot.ToScale(500, 0, 10))
}
10

func Version

func Version() string

Version returns the current Gobot version

type Adaptor

type Adaptor interface {
	// Name returns the label for the Adaptor
	Name() string
	// SetName sets the label for the Adaptor
	SetName(n string)
	// Connect initiates the Adaptor
	Connect() error
	// Finalize terminates the Adaptor
	Finalize() error
}

Adaptor is the interface that describes an adaptor in gobot

type Commander

type Commander interface {
	// Command returns a command given a name. Returns nil if the command is not found.
	Command(string) (command func(map[string]interface{}) interface{})
	// Commands returns a map of commands.
	Commands() (commands map[string]func(map[string]interface{}) interface{})
	// AddCommand adds a command given a name.
	AddCommand(name string, command func(map[string]interface{}) interface{})
}

Commander is the interface which describes the behaviour for a Driver or Adaptor which exposes API commands.

func NewCommander

func NewCommander() Commander

NewCommander returns a new Commander.

type Connection

type Connection Adaptor

A Connection is an instance of an Adaptor

type Connections

type Connections []Connection

Connections represents a collection of Connection

func (*Connections) Each

func (c *Connections) Each(f func(Connection))

Each enumerates through the Connections and calls specified callback function.

func (*Connections) Finalize

func (c *Connections) Finalize() (err error)

Finalize calls Finalize on each Connection in c

func (*Connections) Len

func (c *Connections) Len() int

Len returns connections length

func (*Connections) Start

func (c *Connections) Start() (err error)

Start calls Connect on each Connection in c

type Device

type Device Driver

A Device is an instnace of a Driver

type Devices

type Devices []Device

Devices represents a collection of Device

func (*Devices) Each

func (d *Devices) Each(f func(Device))

Each enumerates through the Devices and calls specified callback function.

func (*Devices) Halt

func (d *Devices) Halt() (err error)

Halt calls Halt on each Device in d

func (*Devices) Len

func (d *Devices) Len() int

Len returns devices length

func (*Devices) Start

func (d *Devices) Start() (err error)

Start calls Start on each Device in d

type Driver

type Driver interface {
	// Name returns the label for the Driver
	Name() string
	// SetName sets the label for the Driver
	SetName(s string)
	// Start initiates the Driver
	Start() error
	// Halt terminates the Driver
	Halt() error
	// Connection returns the Connection associated with the Driver
	Connection() Connection
}

Driver is the interface that describes a driver in gobot

type Event

type Event struct {
	Name string
	Data interface{}
}

Event represents when something asynchronous happens in a Driver or Adaptor

func NewEvent

func NewEvent(name string, data interface{}) *Event

NewEvent returns a new Event and its associated data.

type Eventer

type Eventer interface {
	// Events returns the map of valid Event names.
	Events() (eventnames map[string]string)

	// Event returns an Event string from map of valid Event names.
	// Mostly used to validate that an Event name is valid.
	Event(name string) string

	// AddEvent registers a new Event name.
	AddEvent(name string)

	// DeleteEvent removes a previously registered Event name.
	DeleteEvent(name string)

	// Publish new events to any subscriber
	Publish(name string, data interface{})

	// Subscribe to events
	Subscribe() (events eventChannel)

	// Unsubscribe from an event channel
	Unsubscribe(events eventChannel)

	// Event handler
	On(name string, f func(s interface{})) (err error)

	// Event handler, only executes one time
	Once(name string, f func(s interface{})) (err error)
}

Eventer is the interface which describes how a Driver or Adaptor handles events.

func NewEventer

func NewEventer() Eventer

NewEventer returns a new Eventer.

type JSONConnection

type JSONConnection struct {
	Name    string `json:"name"`
	Adaptor string `json:"adaptor"`
}

JSONConnection is a JSON representation of a Connection.

func NewJSONConnection

func NewJSONConnection(connection Connection) *JSONConnection

NewJSONConnection returns a JSONConnection given a Connection.

type JSONDevice

type JSONDevice struct {
	Name       string   `json:"name"`
	Driver     string   `json:"driver"`
	Connection string   `json:"connection"`
	Commands   []string `json:"commands"`
}

JSONDevice is a JSON representation of a Device.

func NewJSONDevice

func NewJSONDevice(device Device) *JSONDevice

NewJSONDevice returns a JSONDevice given a Device.

type JSONMaster

type JSONMaster struct {
	Robots   []*JSONRobot `json:"robots"`
	Commands []string     `json:"commands"`
}

JSONMaster is a JSON representation of a Gobot Master.

func NewJSONMaster

func NewJSONMaster(gobot *Master) *JSONMaster

NewJSONMaster returns a JSONMaster given a Gobot Master.

type JSONRobot

type JSONRobot struct {
	Name        string            `json:"name"`
	Commands    []string          `json:"commands"`
	Connections []*JSONConnection `json:"connections"`
	Devices     []*JSONDevice     `json:"devices"`
}

JSONRobot a JSON representation of a Robot.

func NewJSONRobot

func NewJSONRobot(robot *Robot) *JSONRobot

NewJSONRobot returns a JSONRobot given a Robot.

type Master

type Master struct {
	AutoRun bool

	Commander
	Eventer
	// contains filtered or unexported fields
}

Master is the main type of your Gobot application and contains a collection of Robots, API commands that apply to the Master, and Events that apply to the Master.

func NewMaster

func NewMaster() *Master

NewMaster returns a new Gobot Master

func (*Master) AddRobot

func (g *Master) AddRobot(r *Robot) *Robot

AddRobot adds a new robot to the internal collection of robots. Returns the added robot

func (*Master) Robot

func (g *Master) Robot(name string) *Robot

Robot returns a robot given name. Returns nil if the Robot does not exist.

func (*Master) Robots

func (g *Master) Robots() *Robots

Robots returns all robots associated with this Gobot Master.

func (*Master) Running

func (g *Master) Running() bool

Running returns if the Master is currently started or not

func (*Master) Start

func (g *Master) Start() (err error)

Start calls the Start method on each robot in its collection of robots. On error, call Stop to ensure that all robots are returned to a sane, stopped state.

func (*Master) Stop

func (g *Master) Stop() (err error)

Stop calls the Stop method on each robot in its collection of robots.

type Pinner

type Pinner interface {
	Pin() string
}

Pinner is the interface that describes a driver's pin

type Porter

type Porter interface {
	Port() string
}

Porter is the interface that describes an adaptor's port

type Robot

type Robot struct {
	Name string
	Work func()

	AutoRun bool

	WorkEveryWaitGroup *sync.WaitGroup
	WorkAfterWaitGroup *sync.WaitGroup
	Commander
	Eventer
	// contains filtered or unexported fields
}

Robot is a named entity that manages a collection of connections and devices. It contains its own work routine and a collection of custom commands to control a robot remotely via the Gobot api.

func NewRobot

func NewRobot(v ...interface{}) *Robot

NewRobot returns a new Robot. It supports the following optional params:

	name:	string with the name of the Robot. A name will be automatically generated if no name is supplied.
[]Connection: Connections which are automatically started and stopped with the robot
	[]Device: Devices which are automatically started and stopped with the robot
	func(): The work routine the robot will execute once all devices and connections have been initialized and started

func (*Robot) AddConnection

func (r *Robot) AddConnection(c Connection) Connection

AddConnection adds a new connection to the robots collection of connections. Returns the added connection.

func (*Robot) AddDevice

func (r *Robot) AddDevice(d Device) Device

AddDevice adds a new Device to the robots collection of devices. Returns the added device.

func (*Robot) After

func (r *Robot) After(ctx context.Context, d time.Duration, f func()) *RobotWork

After calls the given function after the provided duration has elapsed

func (*Robot) Connection

func (r *Robot) Connection(name string) Connection

Connection returns a connection given a name. Returns nil if the Connection does not exist.

func (*Robot) Connections

func (r *Robot) Connections() *Connections

Connections returns all connections associated with this robot.

func (*Robot) Device

func (r *Robot) Device(name string) Device

Device returns a device given a name. Returns nil if the Device does not exist.

func (*Robot) Devices

func (r *Robot) Devices() *Devices

Devices returns all devices associated with this Robot.

func (*Robot) Every

func (r *Robot) Every(ctx context.Context, d time.Duration, f func()) *RobotWork

Every calls the given function for every tick of the provided duration.

func (*Robot) Running

func (r *Robot) Running() bool

Running returns if the Robot is currently started or not

func (*Robot) Start

func (r *Robot) Start(args ...interface{}) (err error)

Start a Robot's Connections, Devices, and work.

func (*Robot) Stop

func (r *Robot) Stop() error

Stop stops a Robot's connections and Devices

func (*Robot) WorkRegistry

func (r *Robot) WorkRegistry() *RobotWorkRegistry

WorkRegistry returns the Robot's WorkRegistry

type RobotWork

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

RobotWork and the RobotWork registry represent units of executing computation managed at the Robot level. Unlike the utility functions gobot.After and gobot.Every, RobotWork units require a context.Context, and can be cancelled externally by calling code.

Usage:

someWork := myRobot.Every(context.Background(), time.Second * 2, func(){
	fmt.Println("Here I am doing work")
})

someWork.CallCancelFunc() // Cancel next tick and remove from work registry

goroutines for Every and After are run on their own WaitGroups for synchronization:

someWork2 := myRobot.Every(context.Background(), time.Second * 2, func(){
	fmt.Println("Here I am doing more work")
})

somework2.CallCancelFunc()

// wait for both Every calls to finish
robot.WorkEveryWaitGroup().Wait()

func (*RobotWork) CallCancelFunc

func (rw *RobotWork) CallCancelFunc()

CallCancelFunc calls the context.CancelFunc used to cancel the work

func (*RobotWork) CancelFunc

func (rw *RobotWork) CancelFunc() context.CancelFunc

CancelFunc returns the context.CancelFunc used to cancel the work

func (*RobotWork) Duration

func (rw *RobotWork) Duration() time.Duration

Duration returns the timeout until an After fires or the period of an Every

func (*RobotWork) ID

func (rw *RobotWork) ID() uuid.UUID

ID returns the UUID of the RobotWork

func (*RobotWork) String

func (rw *RobotWork) String() string

func (*RobotWork) TickCount

func (rw *RobotWork) TickCount() int

TickCount returns the number of times the function successfully ran

func (*RobotWork) Ticker

func (rw *RobotWork) Ticker() *time.Ticker

Ticker returns the time.Ticker used in an Every so that calling code can sync on the same channel

type RobotWorkRegistry

type RobotWorkRegistry struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

RobotWorkRegistry contains all the work units registered on a Robot

func (*RobotWorkRegistry) Get

func (rwr *RobotWorkRegistry) Get(id uuid.UUID) *RobotWork

Get returns the RobotWork specified by the provided ID. To delete something from the registry, it's necessary to call its context.CancelFunc, which will perform a goroutine-safe delete on the underlying map.

type Robots

type Robots []*Robot

Robots is a collection of Robot

func (*Robots) Each

func (r *Robots) Each(f func(*Robot))

Each enumerates through the Robots and calls specified callback function.

func (*Robots) Len

func (r *Robots) Len() int

Len returns the amount of Robots in the collection.

func (*Robots) Start

func (r *Robots) Start(args ...interface{}) (err error)

Start calls the Start method of each Robot in the collection

func (*Robots) Stop

func (r *Robots) Stop() (err error)

Stop calls the Stop method of each Robot in the collection

Package Files

Documentation was rendered with GOOS=linux and GOARCH=amd64.

Jump to identifier

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to identifier