Targeting Gateway or Node with a single sketch

So for one of my first tests to play with my new Mesh devices, I used an Argon and a Xenon kit. I basically built the test hardware project for the Xenon – a light sensor connected to pin A0, used Mesh.publish() to send its values to the mesh, then had the Argon relay those to the cloud with Particle.publish().

But I didn’t want to have to manage two separate sets of code. So I used feature detection and conditional compilation to write a single program that deploys different code (node/gateway) depending on which device you are targeting.

https://go.particle.io/shared_apps/5c0356b4e7a087848a0009cb

The key logic is:

/**
 * If you are using a Xenon with the Ethernet FeatherWing, change this
 * value to '1' instead of '0' to use the device as a gateway instead
 * of a leaf node.
 */
#define HAVE_ETHERNET 0

/**
 * If you want to force an Argon or Boron to be a leaf instead of a
 * gateway, set this value to '1' instead of '0'.
 * 
 * NOTE: FORCE_LEAFNODE will override HAVE_ETHERNET, so it doesn't make
 * sense to turn them both on.
 */
#define FORCE_LEAFNODE 0
 
/**
 * Define GATEWAY and LEAF, then conditinally compile our code, depending
 * on which device we are currently targeting.
 */
#define GATEWAY ( Wiring_Mesh && (Wiring_WiFi || Wiring_Cellular || HAVE_ETHERNET) && ! FORCE_LEAFNODE)
#define LEAF ( Wiring_Mesh && ( FORCE_LEAFNODE || ! (Wiring_WiFi || Wiring_Cellular || HAVE_ETHERNET) ) )

Then you can just use #if LEAF and #if GATEWAY to target code to either type of device.

5 Likes

Thank you for sharing! I’m sure others will find this post useful :slight_smile: