Making code cross platform

Hello,

I’m working with both Gen2 and multiple Gen3 devices. I would like to make my code to work across both platforms, but was wondering what the best way to do this would be. Any suggestions for “best practices”?

One thing I was thinking of was to make use of PLATFORM_IDs. Perhaps do something like the below. I have yet to try this and this is on my “TODO” list, but I would just like to start a conversation + get some ideas while I clear my backlog or at least be told “Yeah your going in the right direction” and I’ll figure it out.

Relevant Docs

What I am thinking of…

#ifdef PLATFORM_BORON
     // Boron code goes here (e.g. Cellular.setActiveSIM(), Cellular.setCredentials(), RGB.onChange() etc...)
#elif PLATFORM_ARGON
     // Maybe some WIFI settings here...
#elif PLATFORM_ELECTRON_PRODUCTION
     // Electron code goes here(e.g. cellular_credentials_set(), RGB.mirrorTO() etc...)
#endif

Found something useful: https://docs.particle.io/reference/device-os/firmware/argon/#antenna-selection

I guess its #if (PLATFORM_ID == PLATFORM_XXX) rather than the #ifdef in the OP, but the idea is the same.

There are also other “flags” the rather focus on available features instead of platform
e.g.

#if Wiring_WiFi 
// WiFi specific stuff
#elif Wiring_Cellular
// Cellular specific stuff
#else
// or
#define HAL_PLATFORM_WIFI (1)
#define HAL_PLATFORM_CELLULAR (1) 
#define HAL_PLATFORM_MESH (1)

I also use this to abstract away WiFi or Cellular specifics

#if Wiring_WiFi 
  #define RADIO WiFi
#elif Wiring_Cellular
  #define RADIO Cellular
#else
...
  // somewhere in code
  RADIO.connect();
  waitUntil(RADIO.ready);

Here you can find some of the defined platforms and features


2 Likes

@ScruffR thanks for the suggestion.

This is a good one. So instead of being platform specific I could check for feature or hardware flags. I could then use a combination of these flags to perhaps make a wrapper to abstract the specifics (and call something generic my main function (i.e. just like your RADIO example).

I’ll do this in my next refactor, I’ll probably start with the most common place which is the void setup(), this always has device/feature specific calls!

1 Like

Yes, checking for the feature is always better than checking for the platform.

For example, the Boron SoM has a different PLATFORM_ID than the Boron, but if you check for Wiring_Cellular instead of the PLATFORM_ID your code would probably work without modification.