If you’re struggling, @JDRoberts ’ FAQ is worth a look:
Edited to add - this is a device handler rather than a smartapp, just in case you’re trying to create a smartapp with the code.