particle-iot/ruby-particlerb

Name: ruby-particlerb

Owner: Particle

Description: Debian package for Ruby gem particlerb

Created: 2016-10-27 21:03:45.0

Updated: 2017-09-16 00:17:56.0

Pushed: 2018-01-03 18:43:49.0

Homepage: null

Size: 36

Language: Ruby

GitHub Committers

UserMost Recent Commit# Commits

Other Committers

UserEmailMost Recent Commit# Commits

README

particlerb

Gem Version Build Status Code Climate RubyDoc

Ruby client for the Particle.io Cloud API with an object-oriented interface

Note: this is not an official gem by Particle. It is maintained by Julien Vanier.

Installation
stall via Rubygems
m install particlerb

 add to your Gemfile
"particlerb", "~> 0.0.3"

quire the gem
ire 'particle'
Providing credentials

A Particle cloud API access token is necessary for most requests. You can use the one from the Web IDE for testing, but it's recommended to generate a new token with this gem using Particle.login or with the Particle CLI using particle token new

ovide acess token as an environment variable
'PARTICLE_ACCESS_TOKEN']

 configure global authentication credentials
 you use Rails, you can put this in config/initializers/particle.rb
icle.configure do |c|
access_token = "38bb7b318cc6898c80317decb34525844bc9db55"


 pass access token when creating a client
 no token is passed to Particle::Client.new, the global or environment one is used
nt = Particle::Client.new(access_token: "38bb7b318cc6898c80317decb34525844bc9db55")
Making requests

API methods are available as module methods (consuming module-level configuration) or as client instance methods.

tch the list of devices using the global client
icle.devices
is is equivalent to
icle.client.devices

 used a newly created client
nt = Particle::Client.new
tch the list of devices
nt.devices

When using this gem in a multi-threaded program like a Rails application running on the puma server, it's safer to use Particle::Client.new in each thread rather than using the global Particle.client.

Interacting with devices

List all devices. Returns an Array of Particle::Device.

ces = Particle.devices

Get a Particle::Device by id or name.

ce = Particle.device('blue_fire')
ce = Particle.device('f8bbe1e6e69e05c9c405ba1ca504d438061f1b0d')

Get information about a device.

ce = Particle.device('blue_fire')
ce.attributes     # Hash of all attributes
ce.id             # ==> 'f8bbe1e6e69e05c9c405ba1ca504d438061f1b0d'
ce.name           # ==> 'blue_fire'
ce.connected?     # true
ce.product        # "Core" or "Photon"
ce.variables      # {:myvar => "double" } or nil if not connected
ce.functions      # ["myfunction"] or nil if not connected
ce.get_attributes # forces refresh of all attributes from the cloud

 you get a Device from the Particle.devices call, you will need to call
t_attributes to get the list of functions and variables since that's not
turned by the cloud when calling Particle.devices
ce = Particle.devices.first
ce.connected?     # ==> true
ce.functions      # ==> nil
ce.get_attributes
ce.functions      # ==> ["myfunction"]

Claim a device by id and add it to your account. Returns a Particle::Device.

icle.device('f8bbe1e6e69e05c9c405ba1ca504d438061f1b0d').claim

Remove a device from your account. Returns true on success.

icle.device('blue_fire').remove
icle.devices.first.remove

Rename a device. Returns true on success.

icle.device('red').rename('green')

Call a function on the firmware with an optional String argument. Returns the result of running the function as as Number.

icle.device('coffeemaker').function('brew')
icle.devices.first.function('digitalWrite', '1')
ce.call('brew') # aliased as call

Get the value of a firmware variable. Returns the result as a String or Number.

icle.device('mycar').variable('battery') # ==> 12.33
ce = Particle.device('f8bbe1e6e69e05c9c405ba1ca504d438061f1b0d')
ce.variable('version') # ==> "1.0.1"
ce.get('version') # aliased as get

Signal a device to start blinking the RGB LED in rainbow patterns. Returns whether the device is signaling.

icle.device('nyan_cat').signal(true)

Create a new device for a product that allows self-provisioning. Currently only the Raspberry Pi (product id 31) allows this. Returns the new device. You can then claim the device when it is online.

ce = Particle.provision_device(product_id: 31)
it for device to be online
ce.claim

Change the product id. The meaning of the product id is specific to your application and account.

icle.device('f8bbe1e6e69e05c9c405ba1ca504d438061f1b0d').change_product(3)

Update the public key for a device. The public key must be in PEM format. See for an example.

ic_key = IO.read('device.pub.pem')
icle.device('f8bbe1e6e69e05c9c405ba1ca504d438061f1b0d').update_public_key(public_key, algorithm: 'rsa')

See the Particle Cloud API documentation about devices for more details.

Interacting with events

Publish an event to your devices. Returns true on success.

icle.publish(name: "wakeup")
icle.publish(name: "server_ip", data: "8.8.8.8", ttl: 3600, private: true)

Data, ttl and private are optional.

Data is converted to JSON if it is a Hash or an Array, otherwise it is converted to a String.

See the Particle Cloud API documentation about publishing events for more details.

Limitation: Subscribe not supported

This gem does not support subscribing (listening) to events from devices.

This would require an HTTP client that supports streaming responses which is not common in Ruby. Some clients like EM-HTTP-Request do support streaming responses, but are tied to specific architectures like EventMachine.

For web server applications, webhooks are better suited to process incoming events.

Interacting with webhooks

List existing webhooks. Returns an Array of Particle::Webhook

icle.webhooks

Get info about an existing webhook by id. Returns a Particle::Webhook

ook = Particle.webhook('ffcddbd30b860ea3cadd22db')
ook.attributes
ook.event
ook.url

Calling attributes will also send a test message to your webhook url and report the response or error.

ook.response
ook.error

ook = Particle.webhooks.first
ook.get_attributes # force reloading attributes from the cloud
t_attributes necessary to get the response when Webhook was returned from the
rticle.webhooks() method as it doesn't do a test message on each webhook
ook.response

Create a new webhook. Pass a hash of any options accepted by the Particle Cloud API. Returns a Particle::Webhook

icle.webhook(event: "weather", url: "http://myserver.com/report").create

Currently the available options are:

Remove a webhook. Returns true on success.

ook = Particle.webhooks.first
ook.remove
icle.webhooks.each(&:remove) # remove all

See the Particle Cloud API documentation about webhooks for more details.

Authentication

Replace the access token on a client

icle.access_token = 'f1d52ea0de921fad300027763d8c5ebd03b1934d'

 client instance
nt = Particle::Client.new
nt.access_token = 'f1d52ea0de921fad300027763d8c5ebd03b1934d'

All these following methods requires the account username (email) and password.

List all tokens that can be used to access an account. Returns an Array of Particle::Token

icle.tokens("me@example.com", "pa$$w0rd")

Log in and create a new token. Returns a Particle::Token. This will also set the token on the client for future calls.

icle.login("me@example.com", "pa$$w0rd")

Create a token but don't set it on the client. Returns a Particle::Token

icle.token.create("me@example.com", "pa$$w0rd")

login and token.create take an optional hash of options.

Invalidate and delete a token. Returns true on success.

icle.token('f1d52ea0de921fad300027763d8c5ebd03b1934d').remove("me@example.com", "pa$$w0rd")
icle.tokens.first.remove("me@example.com", "pa$$w0rd")

See the Particle Cloud API documentation about authentication and token for more details.

Compiling and flashing

Flash new firmware from source. Returns a result struct

lt = device.flash('blink_led.ino')
lt.ok # ==> true

lt = device.flash('bad_code.ino')
lt.ok # ==> false
lt.errors # ==> "Compiler errors\n...\n"

ce.flash(Dir.glob('firmware/*') # all files in a directory
ce.flash('application.bin', binary: true)

Compile firmware for a specific device, platform or product. Returns a result struct

lt = device.compile('blink_led.ino')
lt.ok # ==> true
lt.binary_id # ==> "559061e16b4ba27e4602c5c8"

icle.compile(Dir.glob('firmware/*', platform: :core) # or :photon
icle.compile(Dir.glob('firmware/*', product_id: 1) # meaning depends on your account

Download a compiled binary. Returns the result bytes

lt = device.compile('blink_led.ino')
ry = Particle.download_binary(result.binary_id)
.new('application.bin', 'w') { |f| f.write(binary) }

See the Particle Cloud API documentation about firmware for more details.

Errors

When any API error occurs, a subclass of Particle::Error will be raised.

The actual error classes are

See a description of each error on the Particle API docs.

This gem uses the Faraday HTTP client library, so API call may raise Faraday::ClientError for things like SSL errors, DNS errors, HTTP connection timed out.

Advanced

All API endpoints are availble directly on the client object as method calls like Particle.claim_device(id) but the preferred usage is to call methods on domain objects like Particle.device(id).claim. See the various Particle::Client subclasses for more details.

Accessing HTTP responses

While most methods return a domain object like Device, sometimes you may need access to the raw HTTP response headers. You can access the last HTTP response with Client#last_response:

ce   = Particle.device('123456').claim
onse = Particle.last_response
ers  = response.headers
Tests

This gem uses the VCR gem to record and replay HTTP requests.

To run the tests using pre-recorded HTTP requests:

ndle install
ndle exec rake spec

To run the test against the real API, you will need an account with Particle and a device added to your account.

Set the following environment variables:

Make sure the first Particle device in TEST_PARTICLE_DEVICE_IDS is online and run

ndle install
ndle exec rake spec:rerecord
Support

Open a GitHub issue if you find a bug.

Join the conversion on the awesome Particle community forums to discuss any other topic!

Versioning

particlerb follows the Semantic Versioning standard.

Thanks

This gem is heavily inspired by Octokit by GitHub. I stand on the shoulder of giants. Thanks!

Octokit is copyright (c) 2009-2014 Wynn Netherland, Adam Stacoviak, Erik Michaels-Ober and licensed under the MIT license.

License

Copyright (c) 2015 Julien Vanier

This gem is available under the GNU Lesser General Public License, version 3.0


This work is supported by the National Institutes of Health's National Center for Advancing Translational Sciences, Grant Number U24TR002306. This work is solely the responsibility of the creators and does not necessarily represent the official views of the National Institutes of Health.