Monday, April 1, 2019

Trailhead Electric Imp plus plus

After completing the the Trailhead Electric Imp project I was left wanting an excuse to access a number of other features of the imp001 hardware. Namely the accelerometer and pressure sensor. Yet there didn't seem many opportunities for a static fridge to fully utilize them.

While I was experimenting with this back in May 2018 the #BeABuilder challenge happened and I got sidetracked using the hardware for that instead. Somewhere in that process I never got around to hitting publish on this blog post, so here we are a year or so latter with a better late than never post.

Firstly I expanded the data model in Salesforce so I'd have fields to receive the additional data. This included the acceleration and pressure readings.

Out of interest I tried getting the IoT Orchestration Traffic into a Lightning component. I didn't have much luck at the time and it didn't really liked to be iframed in.

Hunting through the Salesforce Labs I found the salesforce-iot-toolkit. This provided some great visualizations via platform events as the data came in from the fridge. It directly monitored the platform events to drive the graphs. I found I needed to use the source based version rather than the app exchange version, which was missing a number of features.

Dramatic reenactment of sensor usage

Modified Agent Nut Source

A few points of interest:

  1. My source was the version before they added proper refresh token support to handle expired sessions. So you probably don't want my version of getStoredCredentials()
  2. Added #require statements to access additional sensors.
  3. Dropped the READING_INTERVAL_SEC down to 1 second to improve the accelerometer data.
  4. Retrieved the X,Y, and Z axis acceleration values.
  5. Retrieved the pressure sensor and additional temperature reading from that sensor as well.
  6. Set the RGB color based on the current orientation indicated by the acceleration.
  7. The LIS2DH12 sensor needed a non-default I2C address of 0x32.

Modified Salesforce Platform Event Trigger Code

Nothing fancy here. Just collect the additional properties the map them to the new custom fields.

trigger SmartFridgeReadingReceived on Smart_Fridge_Reading__e (after insert) {
    List records = new List(); 
    for (Smart_Fridge_Reading__e event : Trigger.New) {
        SmartFridge__c record = new SmartFridge__c();
        record.deviceId__c = event.deviceId__c;
        record.temperature__c = event.temperature__c;
        record.humidity__c = event.humidity__c;
        record.door__c = event.door__c;
        record.ts__c = event.ts__c;
        record.accX__c = event.accX__c;
        record.accY__c = event.accY__c;
        record.accZ__c = event.accZ__c;
        record.pressure__c = event.pressure__c;
        record.temp2__c = event.temp2__c;
        records.add(record); }
    insert records;
}