Building a smart ‘anything’ with salesforce

This blog post is an expanded version of a talk I gave at the July 2018 London Salesforce Developer meetup with slides available here

I am sure by now we’ve all heard of the ‘internet of things’ and maybe someone us even have some ‘smart devices’ in our homes or offices. Maybe you’ve heard of Salesforce IoT. This post will show you the things you need to build a smart ‘anything’ on salesforce.

Before we go too much further, we need to understand event driven architecture, which is the underpinnings of many IoT (and general) integrations. What I mean by event driven architecture is this; Rather than a standard point to point (one system connects directly to another to exchange data) or middleware (there is software in the middle of the systems to manage the exchange of data) integration, event driven integrations rely on three things. These are publishers, subscribers and the event bus. Simply put, systems or devices publish or subscribe to messages to send and receive data, and the event bus manages this. A major advantage of this approach is that systems or devices are decoupled from one another, so if things need to change or a system needs replacing entirely, the other systems are not effected by this change.

Now that we understand event driven architecture (hopefully, here is a good trailhead for more info), on to our smart ‘anything’, in this case its a smart powerstrip. I chose this example because it is easy to demonstrate and relate to, as many people have smart devices in their homes or businesses. The concepts here are not limited to domestic use, this could just as easily be applied to a smart refrigerator, projector, water tank, conveyor belt, etc. Lets work out how we are going to make our smart power strip. We will need some hardware in the form of relays, sensors and microcontrollers (more on this in a minute) and we will need an event bus, so say hello to platform events (and MQTT), we will also need some automation and a user interface, so enter Salesforce IoT and Lightning respectively.

Lets start with the hardware, inside of this fetching white box we have the following items

  1. A modified two gang powerpoint (modified so that each outlet can be controlled individually)
  2. Two cheap 5v relay boards from amazon
  3. A current sensor (ACS712A, 5 amp version)
  4. An Arduino nano
  5. An NodeMCU 1.0 ESP8266 Dev Board
  6. A 240VAC to 5VDC power supply (aka. sacrificial phone charger)

The hardware is a tad more complex than necessary because I used what I had on hand to build this device. The relay boards and the current sensor both are designed to operate on 5v, where as the ESP8266 is a 3.3v device. So I am essentially using the Arduino nano to control all of the sensors and relays, and the ESP8266 is acting as a glorified serial to wifi converter. If I were to build this again I would do away with the Arduino Nano, as the ESP8266 does have everything needed to interface with sensors and relays directly.

The Arduino Nano’s code is simple, every 5 seconds it prints the current draw (in watts) to the serial port, It also listens for some JSON from the ESP8266 to tell it which pin and what value to set it to, to turn the relays on or off. You can check this code out on my github here

The ESP8266’s code is a bit more complex, it acts as an interface between the Arduino Nano and the outside world, so on an emulated serial port it listens for the current draw information and sends it via MQTT and Platform Events in to salesforce. It also listens for a Platform Event telling it which device to turn on or off. You can check out the code for it here.

So now we need a way for our hardware to talk to our event bus, while it is possible for it to talk directly to salesforce, as I discovered this isn’t a great idea (more on that later). I built a very quick and dirty ‘proxy’ between Platform Events and MQTT (MQTT is another Event Driven protocol, very similar to platform events but designed for low power applications). This proxy is written in NodeJS and runs on heroku, it simply takes a Platform Event and sends publishes it to MQTT, and it listens for MQTT events from the smart power strip and publishes them as a Platform Event. The code for this is available here.

Now comes the fun part, Salesforce! The first part is of course, platform events. For this to work, we have three platform events defined

  1. Smart Meter Reading – This event is published to from the device and contains the current power consumption in watts
  2. Smart Meter Event – This event is published to from Salesforce IoT and contains the type of chatter alert to generate
  3. Smart Device Event – This event is published from Lightning and subscribed to by the device to turn sockets on and off

We also have some standard salesforce objects defined these are;

  1. Smart Home – A collection of devices under one roof
  2. Smart Device – The smart device itself, child of ‘Smart Home’
  3. Smart Device Pin – An individual pin (relay in this case) on the smart device, child of ‘Smart Device’

These objects are used to store basic information such as Device ID, Pin Number and current state. We could also hang reporting from these objects to measure changes in state over time, such as power consumption on a daily/weekly/monthly basis or how often devices are on or off.

When the device is powered on, every 5 seconds, a ‘Smart Meter Reading’ event is generated from the hardware, this is subscribed to in salesforce in two ways; The first being Salesforce IoT, which in itself creates another platform event (‘Smart Meter Event’) if power usage goes over a certain level

The IoT orchestration itself fires another platform event, which is subscribed to via an apex trigger. When an event is received the apex trigger creates an appropriate chatter post to warn the user that their usage is high

The second way is directly in a lightning component, this component displays a gauge (built using gauge.js) of the current power usage to the user. It is only subscribed when the page is open, not all of the time. There is a good trailhead about how to use platform events in lightning here and the code for my lightning components is available here

From this user interface, we can generate ‘Smart Device Events’ that are sent off to the device to tell it what to turn on or off, these are generated via an Apex controller that also lists ‘Smart Device Pins’ that are related to a given ‘Smart Home’

And thats it, now of course this is just a basic example, but as you can see, its not too difficult to control physical devices from salesforce!


…and now for no reason: Emoji’s in your Wi-Fi name!

A while ago, I came across someone using emoji as a Wi-Fi network name (SSID), I tried to do the same on my wifi router (I wanted the delightful smiling poo emoji 💩) but my router, sadly wouldn’t let me.

I saw it again the other day, and I thought I’d have another try, after all this was years ago and I have a much newer router, and newer version of DD-WRT running on it.

But, I was rudely told that what I was trying to do was illegal.

Not to be deterred, I thought I’d try changing it via SSH… but that was not to be either.

Inserting the emoji returned “p)” which was not accepted, I did also try the unicode char for it “U+1F4A9” but that didn’t work either.

Turning to google, I wondered if anyone had done this successfully before, but all I could find was this article, This was done on the same model of wireless router as I own, but using the stock firmware.

But it did give me a good idea… So taking the same approach as in the article, but skipping straight to the server-side method, I used chrome dev tools to inspect the request;

So that is all well and good, but I need to replicate the request with new parameters, so turning to postman

Fingers crossed, I hit send on the request… and low and behold!


So far I’ve not had any issues with modern-ish devices finding/connecting to it, however I did leave the 2.4ghz radio of my wireless router alone, so that older devices can use it if need be.





SchemaPuker v0.3 Released!

After far too long between, I’ve finally had a chance to release a new version of SchemaPuker

This release contains the following changes;

  • Objects are now shown with both their label and API name in the select list, entering objects in the text box is still done by API name only as before.
  • An issue with some custom object relationships not being drawn has now been resolved
  • Error handling has been further enhanced

It is live now at:, so please give it a go!

As always, if you have any suggestions, comments, bugs or need help you can send me a tweet, leave a comment, or send me a message!


Why I love/hate custom metadata types: Introducing Meta Dataloader

A semi-recent feature of salesforce is Custom Metadata Types. The are like custom settings, but better in many ways.

One of these is very important…  they are deployable! Just like any other piece of metadata (fields, objects, classes, etc) Anyone who has ever dealt with custom settings before, knows what a gigantic pain in the ass it is to keep environments in sync.

However, they have some limitations… While they can be accessed from within apex classes, unlike custom settings they cannot be modified programmatically (well, they can but its not that easy).

Also, unlike custom settings, there is no easy way to populate them in bulk (e.g via workbench, dataloader, etc). Salesforce do give you an option, but it kind of sucks (it involves deploying code to your org, etc, etc)

Faced with having to load ~200 custom metadata type records, and not wanting add an app to my org when I didn’t have to. I decided to write a tool instead.

Presenting: Meta Dataloader!

This is a similar tool to SchemaPuker (infact, i reused a LOT of the code from it) that performs one specific task, it can take a CSV and create custom metadata type records from it.

Once you’ve logged in, you simply choose the Metadata type you wish to load records in to, and if you want to upsert or delete records.


You then need to upload a csv of the values you wish to load, with the headings matching the field API names (similar to workbench)


Click submit, and the records will be upserted or deleted


The tool is pretty basic, but it solves a problem. It took me ~3 hours to put together, so it may have issues.

If you find it useful, let me know, and likewise let me know if you find any bugs.

The code for this is available on my github


SchemaPuker: How it came to be

If you haven’t seen my post about SchemaPuker, check it out here.

The story begins last year, when a colleague of mine David Everitt built a handy tool for generating ERDs. It was essentially a visualforce page / controller that allowed you to choose objects and then it would output some text in the format of a PostgreSQL Schema file that you could then import in to Lucidchart.

PostgreSQL schema files are relatively easy to generate (as they are essentially plain text) and Lucidchart was the diagramming tool of choice where we worked, so this all made sense.

I saw this, and thought it was a brilliant idea. ERDs are something that are very often part of design documents, proposals, etc. Even if you are building new functionality, often you are using some, or all of the existing data model, so having a way to get this out of salesforce easily was very helpful.

You can read more about David’s tool at his blog, SlightlyTechnical, including how to try it yourself.

However, a visualforce page / apex class has its limitations.

  • If you were doing a discovery, perhaps you don’t have credentials to organisation you need to chart, or if you do perhaps you don’t have a sandbox, or permission to install anything in one
  • If you do have credentials and a sandbox, you then need to add the visualforce page and controller in to the org
  • It would just output the results into the page itself, making it harder to import into your charting tool

So I decided I would make a new version of the tool, plus it was a good excuse to play with the salesforce metadata API, which I hadn’t had a lot of exposure to at the time.

I decided I would throw together a Java application to do this, I had written plenty of little console based apps in the past, but had never done anything with a GUI, so this was yet another learning opportunity. I built the app using swing, the WSC, utilising the metadata API and the SOAP API to handle authentication.

The application worked fine and had all the same functionality as its visualforce counterpart, with the added bonus that it would generate a text file, rather than display the output. After that, I got busy with life and forgot about it all.

This year, after giving my blog a bit of a refresh and thinking about what I could write about, when I remembered the tool. I dug out the source code, looked at it, cringed and thought about how I could make this thing better.

The obvious solution here was a cloud based app. Something that required no installation or setup, and was easy to use. Given that I already had a my previous iteration written in Java (and Java is the language I am most comfortable with) heroku seemed like the best fit for hosting this.

Life got in the way again, and it wasn’t till after a trip to surfforce (see my writeup here) and a discussion with Dave Carroll from salesforce that I thought about it again.

Dave was telling me about the work he had done on the cli, and the plans to extend the tool. I told him about my at-the-time named ‘Salesforce ERD Tool’ I was planning to move to heroku. He suggested (quite rightly) that that was a rather boring name, and came up with the idea of calling it ‘SchemaPuker’, and the name was born.

After surfforce I decided I would tackle this. I had never written a java web-app, nor had I used a web framework or deployed anything to heroku before. So with yet another great learning opportunity I set about learning how to do this.

I chose Spring MVC as my framework, mostly due to the huge amount of documentation for it, its uncanny similarity to visualforce and Spring Boot, which made testing the app locally *really* easy, and allowed for no xml config files.

I decided I was going to use the salesforce lightning design system in for the UI of my application, it looks nice and there is an excellent guide available for it.

Next, was taking a look at authorisation. My previous tool used the SOAP API for authorisation, however this was not going to be suitable here. Using OAuth2 made much more sense (so much so that I made a post about it here).


Once I had authorisation sorted out, I was able to reuse most of the core of my original application, and once I had the UI tidied up, I had a minimum viable product. I do have some ideas for enhancements for the next version, such as graphical output, stored groups of objects and a better interface for choosing objects.


Maintenance Mode Package Installation Guide

For more information about this, see this post.



Install the package in the org you wish to try it in (can be a sandbox)
Ensure the package is installed for admins only

Screen Shot 2016-08-08 at 11.54.17

Once installed, go to the ‘Maintenance Config’ tab by clicking the ‘+’ button on the tab bar and click the ‘Perform Initial Setup’ button. You only need to click this once.

Screen Shot 2016-08-03 at 12.44.22

Screen Shot 2016-08-08 at 11.56.42

Once this has completed successfully, you will see the below;

Screen Shot 2016-08-08 at 13.31.00

Next, go to Setup > Develop > Sites

If you have a site already, you can skip this step next two steps

Screen Shot 2016-08-08 at 11.59.19

Enter a domain name you wish to use (remember, you cannot modify this once its been set) and press ‘Check Availability’ Once you have chosen a domain that is avaiable, accept the terms and conditions and press ‘Register My Domain’

Screen Shot 2016-08-08 at 12.01.33

Now, click ‘New’ and configure the site as follows;

Screen Shot 2016-08-08 at 12.02.28

Site Label: Maintenance Site

Active Site Home Page: SFDCMaintLoginSidebar

Default Web Address: maint

Clickjack Protection Level: allow framing by any page

Screen Shot 2016-08-08 at 12.23.57

Accept the defaults for the rest of the fields

If you have an existing site, under ‘Site Visualforce Pages’ click ‘Edit’

Screen Shot 2016-08-08 at 12.06.46

and then add the ‘SFDCMaintLoginSidebar’ page to the ‘Enabled Visualforce Pages’ section

Screen Shot 2016-08-08 at 12.06.59

Ensure you have activated your site when you are finished.

Once you have done this, Setup > Administer > Domain Management > My Domain

Under the ‘Authentication Configuration’ Heading, click ‘Edit’

Screen Shot 2016-08-08 at 12.18.06

Populate the ‘Right Frame URL’ with the URL of your site and press save.

Screen Shot 2016-08-08 at 12.14.25

Once you have completed these steps, logout of salesforce to check your changes have worked.

Make sure you login using your domain (not

Screen Shot 2016-08-08 at 12.25.12 (2)

Once logged in, go to Setup > Develop > Custom Metadata Types

Select ‘Manage Records’ next to ‘Salesforce Maintenance Exempt User’

Screen Shot 2016-08-08 at 13.36.51

Create a new record, and populate the details of the user you want to exclude from Maintenance freezes (e.g DevOps, System Admin)

Screen Shot 2016-08-08 at 13.37.22Once complete, go to the ‘Maintenance Configuration’ tab and press ‘Enable Maintenance Mode’

Screen Shot 2016-08-09 at 13.57.46

Any users who are not exempt will be frozen, and you will a different login page

Screen Shot 2016-08-09 at 13.58.26 (2)



Siri, turn on the light (Part 1)


As you may or may not know, Apple has a technology called HomeKit. Put simply, it allows you to control devices (lights, heating, etc) from your iPhone, and it integrates with Siri.

Several companies make HomeKit enabled devices (e.g Phillips Hue) that you can easily install to take advantage of this… but what is the fun of that?

Luckily, there exists a very good HomeKit Java library, so armed with that, an ESP8266 I set out to see if I could make my own HomeKit enabled devices.

The rough plan was, have the ESP8266 handle the hardware side of things (e.g actually turn things on and off, via a relay) and built a Java application that acts as a HomeKit Bridge.

The first version of the application I built was very basic, it essentially used the example code provided with the library, but one thing I quickly learnt is that HomeKit is like a database, rather than an actual application. You need an app to add entries into the database in order to use it.

Elgato Eve is one such app (which is designed to work with their devices) or there is Home that is designed to work with any HomeKit device (commercial or otherwise). Another option is Apple’s own ‘example code’ called HomeKit Catalog, if you have a Mac with Xcode installed, you can install this on your device (see here for instructions)

I went with HomeKit Catalog, so with that installed and running I was able to test my application. Initially, it worked but would not maintain pairing if the Java application was stopped and re-started, to spite me persisting the data that was required for this. I solved that issue (a method returning weather a device has been paired was not implemented correctly) and was able to move onto the next problem…

How to communicate with the ESP8266 (and actually turn things on and off!) I decided to go with the MQTT protocol for this, its a lightweight and fairly secure publish/subscribe protocol that is often used in low bandwidth/low power applications. The ESP8266 is a very powerful piece of kit, so by using this I have plenty of headroom for other things.

MQTT uses a client/server architecture, meaning I would need a MQTT Broker (server) running, and both my Java application and my ESP8266 would be clients, with the ESP8266 listening for publications from the Java application in order to know when to turn the attached relay on and off. Eclipse make a very good MQTT client library (and application) called Paho that I used in my project. For my MQTT Broker I used Moquette (which I could integrate in to my Java application at a later date)

Next, I had to program the ESP8266. I have done a lot of tinkering in the past with Arduinos, and since you can now program an ESP8266 with the Arduino IDE, I used that. The sketch is fairly simple, it just listens to a topic (A, or B) and then for a value of 1 or 0 (on or off) and sets a GPIO pin high or low, triggering a relay.

So after adding the Paho library to my Java application, I had a means to communicate easily between the Java application and the ESP8266, so time to put it all together and try it out.

And it worked! The Java application is running on my MacBook, so the next step is to get this running on my raspberry pi (and perhaps integrate control of the GPIO pins) as well as support for devices other than simple switches.

I am also working on a design for a ESP8266 relay board that I will talk about in more detail in a future post.

If you want to try this for yourself, the code is available on my github, click here for the Java application and here for the ESP8266 sketch.

A word of warning: working with mains electricity (in this case 240v) is dangerous! Do not attempt this unless you know what you are doing, regardless I take no responsibility for your actions and any damage caused by them.

Australia Day 2015: Slip ‘n Slide + Salesforce

NOTE: This is a previously unpublished post from 2015

When you think of Australia day what would normally come to mind? Celebrating with mates? A BBQ and (often too many) beers? All of these things are pretty standard when it comes to celebrating Australia’s national holiday… but one thing that probably doesn’t come to mind is Salesforce.

For those of you outside of Australia, Australia Day is a national holiday celebrating the foundation of Australia. Like most things here, it’s a pretty relaxed affair. A newer tradition is to listen to the Triple J Hottest 100, a crowd sourced music countdown on Australia’s national alternative radio station. Something else a lot of Aussies do, is setup a backyard slip-n-slide.

So, what does this have to do with Salesforce, you ask. Well… every year a couple of my mates who are electrical engineers host an Australia day party… and being engineers, they couldn’t just settle for any old backyard slip-n-slide… No, their slip-n-slide had a full timing system, leaderboards and a drag racing style Christmas tree! The previous iterations of the slide lacked analytics and a way to track who performed each ride… enter Salesforce.

This year I jumped in on the project and using Salesforce, provided a way to track each person’s runs, display all run-times easily and allow for data from other sources (e.g. the currently playing song on the Triple J Hottest 100) to merge with our data.

Every time a person wanted to use the slide, they’d scan their unique barcode, wait for the traffic light  to go green, and then do their run. The christmas tree would not go green until the course was clear. A series of 6 sensors, placed along the slide run would report data back to a microcontroller (in this case, a teensy 3.0). This data was calculated into times and pushed into Salesforce by a processing sketch. The processing sketch also handled scanning of barcodes and control of the Christmas tree.

Each run down the slide was recorded inside Salesforce, including sector times, total time and speed, with each run being related to the current rider’s contract record as well as the currently playing song on Triple J.

So how did we achieve this? Each time a person scanned their barcode the data was recorded by the processing sketch, and once a run had been completed the barcode number, along with all of the timing data, was pushed in to Salesforce via the processing sketch. As processing is derived from java, It was easy to write a Salesforce connector using existing libraries leveraging the salesforce REST API. This connector created a slide run record in a custom object from this data each time a run was completed.

Upon creation of this record a trigger would fire that called a custom web service class. This web service made a callout to retrieve an XML file that Triple J updated each time a song is played. The class retrieves the file, parses it and stores the currently playing song information against the record.

To tie this all together, a custom app appropriately called ‘Straya Day was created, which consisted of the object tabs and several visualforce tabs to serve as leader boards. This resulted in three main visualforce pages;

  • Last 10 Runs – Displays the last 10 runs down the slide, with the last run in a larger font at the top of the page, as well as the currently playing track on Triple J
  • Top 10 Runs – Displays two tables, the 10 fastest runs by ET and the 10 fastest runs by total time. Also displays the last run and currently playing track in large font at the top of the page.
  • Top 10 by Gender – Displays two tables, 10 fastest runs by girls sorted by total time, and 10 fastest runs by guys sorted by total time. Also displays the last run and currently playing track in large font at the top of the page.

The ‘Straya Day app was then displayed on a laptop, with the page set to refresh every 10 seconds, so that when a rider had completed their run, they could view their time and the currently playing song on the laptop.

Now for some photos.

IMG_20150126_115745 IMG_20150126_115707

The slip and slide itself, running down the side of the house and round into a
catchment area at the end. You can see the yellow timing beams beside the slide.

IMG_20150126_124327 IMG_20150126_125915

The VisualForce page and people checking their recent runs.
IMG_20150126_115907 IMG_20150126_132200

The big mess-o-wires (teensy3, etc) collecting data from the sensors and reporting back to the processing sketch.

If you are keen to get started on something like this yourself? I have placed some example code for the processing sketch, as well as the JJJ fetch web service on my github.