blinkygo

package module
v0.0.0-...-5458243 Latest Latest
Warning

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

Go to latest
Published: Jun 24, 2019 License: MIT Imports: 21 Imported by: 1

README

BlinkyGo

GoDoc Go Report Card License

A simple, well featured library that let you control your BlinkyTape LED strip from BlinkyLabs, using the Go Programming language.

Installation
$ go get -u github.com/wI2L/blinkygo

Basics

Create a new BlinkyTape instance. You must pass two parameters:

  • the serial port name to open eg: COM3 (Windows), /dev/tty/usbmodem1421 (OSX)
  • the number of pixels on the LED strip
import blinky "github.com/wI2L/blinkygo"

bt, err := blinky.NewBlinkyTape("/dev/tty.usbmodem1421", 60)
if err != nil {
   log.Fatal(err)
}
defer bt.Close()

When a new BlinkyTape instance is created, all its pixels are initialised to be black; RGB(0, 0, 0). All operations that modify the state of the LED strip are buffered using an internal bytes buffer. You have to manually "commit" the changes when you want them to take effect.

Set the next pixel
// Create a new color
red := blinky.NewRGBColor(255, 0, 0)
// Create the pixel
pixel := blinky.Pixel{Color: red}

for (i := 0; i < bt.PixelCount; i++) {
   err := bt.SetNextPixel(pixel)
}

setNextPixel() will set a pixel to the next available position. The position is incremented each time this function is called and resets when accumulated data is sent to the LED strip. Be carefull not to exceed the number of pixels the instance was initialized for when calling this function or it will return a RangeError

Set a pixel at a specified position

// Set a yellow pixel at the position 1 (second led)
pixel := blinky.Pixel{Color: NewRGBColor(255, 255, 0)}
err := bt.SetPixelAt(pixel, 1)

When you set a pixel at a specified position, it has to internally rewrite the whole buffer, which is slower.

Set a list of pixels
color := NewRGBColor(0, 255, 0)
pixels := [Pixel{Color: color}]

err := bt.SetPixels(pixels)

Set a list of pixels, starting from the beginning. If the slice provided as argument contains more pixels than the BlinkyTape instance was initialized for, the remaining will be gently ignored.

Set a color
white := NewRGBColor(255, 255, 255)
err := bt.SetColor(color)

It set the same color to all the pixels of the LED strip.

Render accumulated data
err := bt.Render()

When you want to apply the changes you made, call this function. It will send all accumulated data to the LED strip and reset it state. The strip will immediately reflects the modifications.

Discard changes
err := bt.Reset()

If you want to discard any previous changes without rendering them, call Reset(). It clear the internal buffer and reset the position of the next pixel to 0.

Switch off LED strip

You can also switch off the LED strip. It will set black color to all pixels and render the changes. This gives the impression the LED strip extinguished.

err := bt.SwitchOff()

// This is similar to writing:
//    bt.SetColor(NewRGBColor(0, 0, 0))
//    bt.Render()

Colors

There is three different ways to create a Color instance.

RGB triplet

blue := blinky.NewRGBColor(0, 0, 255)
white :=  blinky.NewRGBColor(255, 255, 255)
red := blinky.NewRGBColor(255, 0, 0)

HTML hex color-string format

The first character # of the hex color-string format is optional and can be omitted.

purple, _ := blinky.NewHEXColor("#800080")
orange, _ := blinky.NewHEXColor("FFA500")
pink, _ := blinky.NewHEXColor("#F06")

Named color

Supported names are from the colornames package, see https://godoc.org/golang.org/x/image/colornames.

olive, _ := blinky.NewNamedColor("Olive")
violet, _ := blinky.NewNamedColor("Violet")

NewHEXColor() and NewNamedColor() will return an error if the input format is invalid or the name is unknown.

Patterns

A Pattern is a list of Frame, each containing a list of pixels. Patterns can be used to create an Animation. You create them manually, or from an external source like an Arduino C header file exported by PatternPaint, or an image.

Image

A pattern can be decoded from an image. You have to indicate how many pixels should be extracted per frame.

Frames will be extracted from axis y. If the number of pixels to extract is lower than the image's height, the rest of the pixels in each frame will be black. Instead, if the image's height is greater, then it will be resized to the exact dimension while preserving the original image aspect ratio.

Image types png, jpeg, bmp and gif are supported.

pattern, err := blinky.NewPatternFromImage("pattern.png", 60)
Arduino C header export

PatternPaint can export a pattern drawn with it as an Arduino C Header. You can parse them as well to create a pattern.

pattern, err := blinky.NewPatternFromArduinoExport("pattern.h")

Animations

An Animation is the composition of a Pattern and a set of parameters to define how it should be played, and how many times.

You can import an animation from a file

anim, err := NewAnimationFromFile("animation.json")
if err != nil {
   // do whatever you want with the animation
}

or create it literally

p, _ := blinky.NewPatternFromImage("cylon.png", 60)
anim := &blinky.Animation{
   Name:    "clyon",
   Repeat:  10,
   Speed:   50
   Pattern: p,
}
  • repeat indicate how many times the pattern must be played. A negative number will run an infinite loop.
  • speed is a convenient and simple way to add a delay between each frame. The delay, expressed in milliseconds, is calculated as 1000 / speed.
Play an animation
bt, err := blinky.NewBlinkyTape("/dev/tty.usbmodem1421", 60)
// error handling
bt.Play(anim, nil)

You can also provide a configuration struct to override the animation parameters. It allows you to define a specific delay to use between each frame.

// Configure the animation to play the pattern indefinitely,
// with a delay of 66ms between each frame
config := &blinky.AnimationConfig{
   Repeat:  -1,
   Delay:   66 * time.Millisecond,
}
bt.Play(anim, config)

Notes:

  • You can't change the state of the LED strip nor rendering while an animation is being played. This is only possible while an animation is stopped or paused.

  • If Play() is called while an animation is running or paused, it will stop it before launching the new one.

Controls

While an animation is being played on the LED strip, you can control it and retrieve its status.

// Pause a running animation
bt.Pause()
// Resume a paused animation
bt.Resume()
// Stop an animation
// Can be calLED even if the animation is in a paused state
bt.Stop()

// Get the status of the animation loop
status := bt.Status()
switch status {
case blinky.StatusRunning:
   // animation is running
case blinky.StatusPaused:
   // animation is paused
case blinky.StatusStopped:
   // no animation is running
}

// similar to "bt.Status() == StatusRunning"
if bt.IsRunning() {
   fmt.Println("An animation is running on this BlinkyTape")
}
Export to a file

You can export an animation to a file if you want to reuse it later. The file will use the JSON format to represent its content.

// Export
err := anim.SaveToFile("animation.json")
if err != nil {
   // animation has been saved successfully
}

Share yours

If you create a nice pattern manually of with PatternPaint and want to share it with others, send me a mail and i will add it to the repository. You can find a bunch of patterns in this folder

License

Copyright (c) 2016, William Poussier (MIT Licence)

Documentation

Overview

Package blinkygo provides utilities to control a BlinkyTape LED strip.

Index

Constants

View Source
const (
	// ControlHeader is the byte sent to the led strip to render a new state.
	ControlHeader byte = 0xFF

	// AnimationDefaultDelay is the default delay to wait between two frames
	// of a pattern.
	AnimationDefaultDelay time.Duration = 75 * time.Millisecond
)
View Source
const (
	HEX3DigitsForm = "%1x%1x%1x"
	HEX6DigitsForm = "%02x%02x%02x"
)

HTML hecadecimal color-string formats.

Variables

View Source
var (
	// ErrBusyPlaying is returned when a command that attempt to modify the
	// state of the LED strip is called when an animation is currently running.
	ErrBusyPlaying = errors.New("led strip is busy playing an animation")

	// ErrNoPixels is returned when a null number of pixels is used to create
	// a BlinkyTape instance.
	ErrNoPixels = errors.New("number of pixels cannot be null")

	// ErrEmptyBuffer is returned when an attempt to send accumulated data to the
	// led strip find an empty buffer.
	ErrEmptyBuffer = errors.New("nothing to render, the buffer is empty")

	// ErrWriteCtrlHeader is returned when an error occur while attempting to write
	// the control header at the end of the buffer.
	ErrWriteCtrlHeader = errors.New("couldn't write control header at the end of the buffer")

	// ErrOutOfRange is returned when attempting to set a pixel out of the range of
	// the led strip available pixels.
	ErrOutOfRange = errors.New("attempting to set pixel outside of range")

	// ErrUnknownColorName is returned when a named color is unknown.
	ErrUnknownColorName = errors.New("unknown color name")
)
View Source
var (
	RedExponent   = 1.8
	GreenExponent = 1.8
	BlueExponent  = 2.1
)

Exponents are the factors used to convert a color from the screen space to the LED space.

Functions

This section is empty.

Types

type Animation

type Animation struct {
	Name    string  `json:"name"`
	Repeat  int     `json:"repeat"`
	Speed   uint    `json:"speed"`
	Pattern Pattern `json:"pattern"`
}

An Animation is composed of a Pattern to play with a BlinkyTape based on a playback speed and an number of repetitions.

func NewAnimationFromFile

func NewAnimationFromFile(path string) (*Animation, error)

NewAnimationFromFile create a new Animation instance from a file. The animation file must use JSON as its marshalling format.

func (Animation) SaveToFile

func (a Animation) SaveToFile(path string) error

SaveToFile marshall an Animation to JSON format and write it to a file.

type AnimationConfig

type AnimationConfig struct {
	// Repeat indicates how many times the pattern has to be played
	Repeat int
	// Delay is the duration to wait between the rendering of two frames
	Delay time.Duration
}

AnimationConfig represents the configuration of an Animation.

type AnimationStatus

type AnimationStatus int

AnimationStatus represents the animation loop status of a BlinkyTape instance.

const (
	// StatusStopped means no animation is running.
	StatusStopped AnimationStatus = iota
	// StatusRunning means an animations is being played.
	StatusRunning
	// StatusPaused means a running animation is paused.
	StatusPaused
)

Status constants.

type BlinkyTape

type BlinkyTape struct {

	// PixelCount is the number of pixels the LED strip was initialized with.
	PixelCount uint
	// contains filtered or unexported fields
}

A BlinkyTape represents a BlinkyTape LED strip. All operations that modify the state of the strip are buffered.

func NewBlinkyTape

func NewBlinkyTape(portName string, count uint) (*BlinkyTape, error)

NewBlinkyTape creates a new BlinkyTape instance. The led strip is created with all pixels set to black.

func (*BlinkyTape) Close

func (bt *BlinkyTape) Close() error

Close closes the serial port.

func (*BlinkyTape) IsRunning

func (bt *BlinkyTape) IsRunning() bool

IsRunning returns whether or not an animation is running.

func (*BlinkyTape) Pause

func (bt *BlinkyTape) Pause()

Pause pauses the animation being played on the LED strip. If there is no animation being played, do nothing.

func (*BlinkyTape) Play

func (bt *BlinkyTape) Play(a *Animation, cfg *AnimationConfig)

Play plays an Animation with the LED strip. If an animation is already being played, it is stopped in favor of the new one. The animation loop can be paused, resumed or stopped at any moment, regardless its status. A negative number of repetitions will start an infinite loop.

func (*BlinkyTape) Render

func (bt *BlinkyTape) Render() error

Render sends all accumulated pixel data followed by a control byte to the LED strip to render a new state. It also reset the internal buffer and reset the next position to 0.

func (*BlinkyTape) Reset

func (bt *BlinkyTape) Reset() error

Reset discards any changes made to the LED strip's state.

func (*BlinkyTape) Resume

func (bt *BlinkyTape) Resume()

Resume resumes a previous animation that was paused. If the animation was paused during the delay between the render of two frames, the remaining of the delay will be respected. If there is no animation to resume, do nothing.

func (*BlinkyTape) SetColor

func (bt *BlinkyTape) SetColor(c Color) error

SetColor sets all pixels to the same color.

func (*BlinkyTape) SetNextPixel

func (bt *BlinkyTape) SetNextPixel(p Pixel) error

SetNextPixel sets a pixel at the next position.

func (*BlinkyTape) SetPixelAt

func (bt *BlinkyTape) SetPixelAt(p *Pixel, position uint) error

SetPixelAt sets a pixel at the specified position. The operation has to rewrite the whole buffer.

func (*BlinkyTape) SetPixels

func (bt *BlinkyTape) SetPixels(p []Pixel) error

SetPixels sets pixels from a list.

func (*BlinkyTape) Status

func (bt *BlinkyTape) Status() AnimationStatus

Status returns the animation status of the LED strip.

func (*BlinkyTape) Stop

func (bt *BlinkyTape) Stop()

Stop stops the animation being played on the LED strip. A stop can occur at any moment between the render of two frames regardless the delay, or during a pause. If there is no animation being played or paused, do nothing.

func (*BlinkyTape) SwitchOff

func (bt *BlinkyTape) SwitchOff() error

SwitchOff switches off the LED strip. This actually set the color to black for all pixels and calls Render().

type Color

type Color struct {
	R byte `json:"r"`
	G byte `json:"g"`
	B byte `json:"b"`
}

A Color represents a color.

func NewHEXColor

func NewHEXColor(color string) (Color, error)

NewHEXColor returns a new color parsed from its "html" hex color-string format, either in the 3 "#F06" or 6 "#FF0066" digits form. First char '#' is optional.

func NewNamedColor

func NewNamedColor(name string) (Color, error)

NewNamedColor returns a new color from its name. Supported names are from the package "colornames", see https://godoc.org/golang.org/x/image/colornames

func NewRGBColor

func NewRGBColor(r, g, b byte) Color

NewRGBColor returns a new Color from its RGB representation.

type Frame

type Frame []Pixel

A Frame represents a list of pixels.

type InvalidHEXColor

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

InvalidHEXColor describes an error related to an HTML hex-color parsing.

func (InvalidHEXColor) Error

func (e InvalidHEXColor) Error() string

type Pattern

type Pattern []Frame

A Pattern represents a list of frames.

func NewPatternFromArduinoExport

func NewPatternFromArduinoExport(path string) (Pattern, error)

NewPatternFromArduinoExport returns a new pattern created from an Arduino C header file exported from PatternPaint.

func NewPatternFromImage

func NewPatternFromImage(path string, pixelCount uint) (Pattern, error)

NewPatternFromImage returns a new pattern created from an image. Types 'jpeg', 'png', 'gif' and 'bmp' are supported.

type Pixel

type Pixel struct {
	Color Color `json:"color"`
}

A Pixel represents a led of the strip.

type PixelError

type PixelError struct {
	Pixel    Pixel
	Position uint
	// contains filtered or unexported fields
}

PixelError describes an error related to a pixel command. It provides a copy of the pixel, and its position inside the LED strip's pixels range.

func (PixelError) Error

func (e PixelError) Error() string

type RangeError

type RangeError struct {
	Position uint
	MaxRange uint
}

RangeError describes an error related to a range excess. It provides the position that caused the error, and the max range of the led strip's pixels.

func (RangeError) Error

func (e RangeError) Error() string

Jump to

Keyboard shortcuts

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