Particle Command Line Interface (CLI)#

This notebook demonstrates the use of the Particle command line interface to

  • login and access a device,

  • create a project,

  • add a library,

  • prepare and save code,

  • compile the code to firmware, and

  • flash the firmware over the air.

This notebook is designed to be opened and run on Google Colab. Several modifications will be needed to run in another environment.

Particle CLI#

Installation#

%%capture
!bash <( curl -sL https://particle.io/install-cli )

# path to the particle cli. May be environment dependent.
particle_cli = "/root/bin/particle"
partiicle_cli = "/Users/bin/particle"

Utility functions#

import re
import subprocess

# regular expression to strip ansi control characters
ansi = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')

# decode byte string and strip ansi control characters
def decode_bytes(byte_string):
    if isinstance(byte_string, bytes):
        result = byte_string.decode("utf-8")
    return ansi.sub("", result)

# streamline call to the particle-cli
def particle(args):
    process = subprocess.run(["/Users/jeff/bin/particle"] + args,
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
    process.stdout = decode_bytes(process.stdout)
    process.stderr = decode_bytes(process.stderr)
    return process

# print the default help message
print(particle(["help"]).stderr)
Welcome to the Particle Command Line Interface!
Version 2.10.1
https://github.com/particle-iot/particle-cli

Usage: particle <command>
Help:  particle help <command>

Commands:
  binary      Inspect binaries
  call        Call a particular function on a device
  cloud       Access Particle cloud functionality
  compile     Compile a source file, or directory using the cloud compiler
  config      Configure and switch between multiple accounts
  device      Manipulate a device
  doctor      Put your device back into a healthy state
  flash       Send firmware to your device
  function    Call functions on your device
  get         Retrieve a value from your device
  identify    Ask for and display device ID via serial
  keys        Manage your device's key pair and server public key
  library     Manage firmware libraries
  list        Display a list of your devices, as well as their variables and functions
  login       Login to the cloud and store an access token locally
  logout      Log out of your session and clear your saved access token
  mesh        Manage mesh networks
  monitor     Connect and display messages from a device
  nyan        Make your device shout rainbows
  preprocess  Preprocess a Wiring file (ino) into a C++ file (cpp)
  product     Access Particle Product functionality [BETA]
  project     Manage application projects
  publish     Publish an event to the cloud
  serial      Simple serial interface to your devices
  setup       Do the initial setup & claiming of your device
  subscribe   Listen to device event stream
  token       Manage access tokens (require username/password)
  udp         Talk UDP to repair devices, run patches, check Wi-Fi, and more!
  update      Update the system firmware of a device via USB
  update-cli  Update the Particle CLI to the latest version
  usb         Control USB devices
  variable    Retrieve and monitor variables on your device
  webhook     Manage webhooks that react to device event streams
  whoami      prints signed-in username

Global Options:
  -v, --verbose  Increases how much logging to display  [count]
  -q, --quiet    Decreases how much logging to display  [count]

Options:
  --version  Show the version of particle-cli installed.  [boolean]

Examples:
  particle setup                                     Set up your Particle account and your device
  particle list                                      Show all your devices and their functions and variables
  particle flash my_device tinker                    Remotely update your device to run the default Tinker app
  particle call my_device_name digitalwrite D7=HIGH  Call a function on your device running Tinker to toggle the onboard LED

For more information, visit our documentation at https://docs.particle.io

Login to Particle#

import getpass

# prompt for username and password
username = getpass.getpass(prompt="Username: ")
password = getpass.getpass(prompt="Password: ")

# attempt login
output = particle(["login", "--username", username, "--password", password])

# report results
if output.returncode:
    print(f"Return code = {output.returncode}")
    print(output.stderr)
else:
    print(output.stdout)
Username:  ···········
Password:  ·······
Return code = 1
! User credentials are invalid

Select a device#

The following cell downloads a list of all user devices and creates a list of device names. Here we choose the first name in the list for the rest of this notebook. If this is not the device to be used, then modify this cell accordingly.

devices = [line.split()[0] for line in particle(["list"]).stdout.splitlines()]
device_name = devices[0]
print(particle(["list", device_name]).stdout)
jck_argon_01 [e00fce68eaceb1faa7cf7193] (Argon) is online

Project: Timer display#

To demonstrate use of the Paricle CLI, for this project we will create a simple timer display using the Grove 4-Digit Display that is shipped with the Argon Starter Kit available from Particle.io. The goal of the project is to display time since start device startup measure in seconds. The display will show seconds to two decimal digits for up to 100 seconds. The timer and display will roll over after 100 seconds.

Particle Argon#

Grove 4-Digit Display#

Grove 4-Digit Display

Documentation

Grove Shield FeeatherWing#

Connect the Grove 4-digit display to connector D2 on the Grove Shield FeatherWing adapater.

Create Project#

print(particle(["project", "create", "--name", "display4", "."]).stdout)
Initializing project in directory display4...
> A new project has been initialized in directory display4

Change working directory#

The Particle CLI assumes one is working in the top project directory.

%cd display4
/content/display4

Add relevant libraries#

library = "Grove_4Digit_Display"
print(particle(["library", "add", library]).stdout)
> Library Grove_4Digit_Display 1.0.2 has been added to the project.
> To get started using this library, run particle library view Grove_4Digit_Display to view the library documentation and sources.

Create source file#

%%writefile src/display4.ino

#define CLK D2     /* display clock pin */
#define DIO D3     /* display data pin */
#define DIGITS 4   /* number of display digits */

#include "Grove_4Digit_Display.h"

TM1637 tm1637(CLK, DIO);
unsigned long start;

void setup() {
    tm1637.init();
    tm1637.set(BRIGHT_TYPICAL);
    tm1637.point(POINT_ON);
    start = millis();
}

void loop() {
    unsigned long time = (millis() - start) % 100000;
    display(time / 10); /* displaying 100th's of seconds */
}

void display(unsigned int number) {
    for (int i = 0; i < 4; i++) {
        int digit = DIGITS - 1 - i;
        if (number != 0) {
            tm1637.display(digit, number % 10);
        } else {
            tm1637.display(digit, 0x7f); /* display blank */
        }
        number /= 10;
    }
}
Overwriting src/display4.ino

Compiling#

print(particle(["compile", "argon", "--saveTo", "display4.bin"]).stdout)
Compiling code for argon

Including:
    src/display4.ino
    project.properties

attempting to compile firmware
downloading binary from: /v1/binaries/5f90989f305a91469e6df9ec
saving to: display4.bin
Memory use:
   text	   data	    bss	    dec	    hex	filename
   6316	    108	   1072	   7496	   1d48	/workspace/target/workspace.elf

Compile succeeded.
Saved firmware to: /content/display4/display4.bin

Flash firmware#

print(particle(["flash", device_name, "display4.bin"]).stdout)
Including:
    display4.bin

attempting to flash firmware to your device jck_argon_01
Flash device OK: Update started

Flash success!