Skip to content

Instantly share code, notes, and snippets.

@ReidCarlberg
Last active December 27, 2015 20:49
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ReidCarlberg/7386924 to your computer and use it in GitHub Desktop.
Save ReidCarlberg/7386924 to your computer and use it in GitHub Desktop.
/*
Requires npm installs for
* nforce (handles salesforce API)
* faye (handles streaming API -- there's an old version in nforce, but install a new one)
* serialport (this handles serial communication and will do a little compiling on your machine)
Configure Salesforce as follows
* Start with a standard developer org -- http://developer.force.com/join
* Install the package for the simple Streaming API demo here
https://github.com/ReidCarlberg/LAB-Streaming-API-Demo
(Link in the read me.)
* Configure a new connected app in your developer org.
Setup (top) > Create (side) > Apps > Connected Apps (scroll down) > New
* Check "Enable Oauth Settings"
* Add all permissions
* Use "http://localhost:3000/oauth/_callback" as your callback URL
* You'll be using the Oauth2 web server flow
https://help.salesforce.com/apex/HTViewHelpDoc?id=remoteaccess_oauth_web_server_flow.htm&language=en
* You need your personal security code.
Setup > My Personal Information > Reset My Security Code
* Use your passwork in the field below as PASSWORDsecurityCode (concatenated, no space)
* For bi-directional communication, this package has the Device, Device Reading and Device Message objects.
https://login.salesforce.com/packaging/installPackage.apexp?p0=04tE00000001XSP
Configure this app
* Ensure your oauth settings are correct at the bottom
* Client ID, Secret, Username, Password and Callback URL.
* Note that your secret, username and password should be set as environment variables, not encapsulated in code.
Raspberry Pi notes
* Node is not part of the Wheeze Distro. You can install it using these instructions.
http://www.raspberrypi.org/phpBB3/viewtopic.php?f=66&t=54817
* The Pi has a single serial port that is in use by default. You need to disable it following these instructions
http://www.hobbytronics.co.uk/raspberry-pi-serial-port
* The Pi comes with a UK keyboard layout that will be confusing. You can update it following these instructions
http://raspberrypi.stackexchange.com/questions/10060/raspbian-keyboard-layout
Testing
* Note that new Oauth connected app id's take up to 10 minutes to become usable.
You will get authentication errors until then.
Versions
* 11/11/13 - Updated to check for existence of an outbound message before inserting one into the array.
*/
var SerialPort = require("serialport");
var AckCounter = 0;
var serialPort = new SerialPort.SerialPort("/dev/ttyAMA0", {
baudrate: 9600,
parser: SerialPort.parsers.readline('\r\n')
}, false); // this is the openImmediately flag [default is true]
var nforce = require('nforce');
var http = require('http'),
faye = require('faye');
var client;
var outboundMessages = [];
function handleStreamingAPI(_oauth, _serialPort) {
client = new faye.Client(_oauth.instance_url + '/cometd/28.0');
client.setHeader("Authorization", "OAuth " + _oauth.access_token);
var subscription = client.subscribe('/topic/LAB_OutboundSample', function(message) {
//V1 was JSON
//var simpleMessage = { "addr": message.sobject.Device_Address__c, "msg" : message.sobject.Message__c };
//var simpleMessageString = JSON.stringify(simpleMessage);
var simpleMessageString = "^" + message.sobject.Device_Address__c + ":" + message.sobject.Message__c;
console.log(simpleMessageString + "\n");
if (outboundMessages.indexOf(simpleMessageString) < 0) {
outboundMessages.push(simpleMessageString);
}
});
console.log("Streaming API Connected...");
}
function handleSerialPort(_oauth) {
serialPort.open(function() {
serialPort.on('data', function(data) {
var myData;
try {
myData = JSON.parse(data);
} catch (e) {
console.log("JSON Parse failed " + e);
console.log("==============");
console.log(data);
console.log("==============");
}
if (myData) {
org.apexRest({uri:'DeviceReport', method: 'POST', body: myData}, _oauth, function(err,resp){
if(!err) {
console.log(resp);
}else{
console.log(err);
}
});
}
});
});
}
function processOutboundMessages() {
console.log(outboundMessages);
if (outboundMessages && outboundMessages.length > 0) {
var targetOutboundMessage = outboundMessages[0];
outboundMessages.splice(0,1);
serialPort.write(targetOutboundMessage + "\n", function(err, results) {
if (err) {
console.log(err);
}
});
} else {
//console.log("no messages");
}
setTimeout(function(){processOutboundMessages();},1000);
}
var sfuser = "reid@labs.551";
var sfpass = "PASSWORDsecuritycode";
var query = 'SELECT Id, FirstName, LastName, Email FROM Lead LIMIT 10';
var org = nforce.createConnection({
clientId: '3MVG9y6x0357Hlefg7ne7tiUmhOZad6PLdNH8ljsB0UbY9OTJcx2Qp.c2xUVzXxBCV0xBjuFXYp0Ro4uS1mWV',
clientSecret: '1909279409156583445',
redirectUri: 'http://localhost:3000/oauth/_callback'
});
org.authenticate({ username: sfuser, password: sfpass}, function(err, oauth) {
if(err) {
console.error('unable to authenticate to sfdc');
console.log(err);
process.exit(code=0);
} else {
console.log("authenticated");
console.log("oauth");
console.log(oauth);
handleStreamingAPI(oauth, serialPort);
handleSerialPort(oauth);
processOutboundMessages();
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment