Send arbitrary commands to a Particle Photon (new version of Spark Core) via express
var express = require('express'); | |
var app = express(), | |
var spark = require('spark'); | |
var _ = require('lodash'); | |
require('dotenv').load(); // reads particle username and password from a file named .env that you can .gitignore | |
var deviceName = "InternetButton"; // set this to the name of your device | |
// Login and retrive the device | |
var getDevice = spark.login({ | |
username: process.env.PARTICLE_USERNAME, | |
password: process.env.PARTICLE_PASSWORD | |
}).then(function() { | |
return spark.listDevices(); | |
}).then(function(devices) { | |
var device = _.findWhere(devices, {name: deviceName}); | |
if (device) { | |
return device; | |
} else { | |
throw new Error('Device ' + deviceName + ' not found. Avaliable devices: ' + _.pluck(devices, 'name').join(', ')); | |
} | |
}); | |
// app.all supports GET, POST, etc. | |
app.all('/device/:command/:value?', function(req, res) { | |
getDevice.then(function(device) { | |
device.callFunction(req.params.command, req.params.value, function(err, data) { | |
if (err) { | |
console.error(err); | |
return res.status(500).send(err.message || err); | |
} | |
res.json(data); | |
}) | |
}).catch(function(err) { | |
console.error('Error getting device: ', err); | |
res.status(500).send(err.message || err); | |
}); | |
}); | |
app.listen(process.env.PORT || 3000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment