Daryl Scott
Published © LGPL

Photon Smart LED

Control one or more pins on a Particle Photon through a command-line interface written in Python.

BeginnerProtip30 minutes755
Photon Smart LED

Things used in this project

Story

Read more

Code

smartled.ino

C/C++
Copy and paste code into a new app in Particle Build
#include <map>

// We're going to start by declaring which pins everything is plugged into.
// Use an associative array of string and pin value pairs.
std::map <String, int> pins = {{"red-led", D0}, {"blue-led", D7}};

// Next we go into the setup function.

void setup() {

    // First, declare all of our pins.
    std::map<String, int>::iterator pin;
    for (pin = pins.begin(); pin != pins.end(); ++pin) {
        pinMode(pin->second, OUTPUT);
   }

    // Register functions with Particle cloud
    Particle.function("turnOn", turnOn);
    Particle.function("turnOff", turnOff);
    Particle.function("getStatus", getStatus);
}

// Next is the loop function...

void loop() {
    //pass
}

int _getPin(String arg) {
    // Return pin value from pins or -1 if not found.
    std::map<String, int>::iterator pin;
    for (pin = pins.begin(); pin != pins.end(); ++pin) {
        if (pin->first == arg) {
            return pin->second;
        }
   }

    return -1;
}

int turnOn(String arg) {
    // Turn LED on
    int pin = _getPin(arg);

    if (pin != -1) {
        digitalWrite(pin, HIGH);
        return 1;
    }

    return -1;
}

int turnOff(String arg) {
    // Turn LED off
    int pin = _getPin(arg);

    if (pin != -1) {
        digitalWrite(pin, LOW);
        return 0;
    }

    return -1;
}

int getStatus(String arg) {
    // Return status
    int pin = _getPin(arg);

    if (pin != -1) {
        return digitalRead(pin);;
    }

    return -1;
}

smartled.py

Python
Python 2.7 compatible code. Replace "<MYPARTICLETOKEN>" with access token value in the Settings pane of the Particle Build website.
from argparse import ArgumentParser
import requests

MYPARTICLETOKEN = "<MYPARTICLETOKEN>"

def get_devices():
    """Return list of devices"""
    url = "https://api.particle.io/v1/devices/"
    headers = {"Authorization": "Bearer " + MYPARTICLETOKEN}
    response = requests.request("GET", url, headers=headers)
    response.raise_for_status()
    return response.json()

def get_device_id(name):
    """Return device id"""
    devices = get_devices()
    match = next((device for device in devices if device["name"] == name))
    return match["id"]

def call_function(device_id, func_name, arg=None):
    """Call named function on device and return result"""   
    url = "/".join(["https://api.particle.io/v1/devices", device_id, func_name])
    headers = {"Authorization": "Bearer " + MYPARTICLETOKEN}
    response = requests.request("POST", url, headers=headers, data={arg: arg})
    response.raise_for_status()
    return response.json()

def main(args=None):
    """Command line interface to control pins on device registered with Particle Cloud"""
    parser = ArgumentParser(description="Control pins on device registered with Particle Cloud")
    parser.add_argument("device_name")
    parser.add_argument("func_name", choices=['turnOn', 'turnOff', 'getStatus'])
    parser.add_argument("pin_name")

    values = parser.parse_args(args)
    device_id = get_device_id(values.device_name)
    func_name = values.func_name
    pin_name = values.pin_name

    response = call_function(device_id, func_name, pin_name)

    if response["return_value"] is 1:
        print "'%s' is on" % pin_name
    elif response["return_value"] is 0:
        print "'%s' is off" % pin_name
    else:
        raise RuntimeError("An unspecified error occurred.")

if __name__ == "__main__":
    main()

Credits

Daryl Scott

Daryl Scott

0 projects • 0 followers

Comments