I’ve just finally started to take advantage of creating handlers myself. I’ve managed to convert most of my frequently repetitive things to subroutines just fine, but I’m having trouble with this one. It’s about sending commands to smart lights hub API using JSON.
I manage to get the preset handler to create a command string correctly, and (in isolation from that handler), successfully send commands to my lights using the following hue handler.
But if I try to run these two in a row, the script fails because “TestPreset” that I’m trying to have the handler use as a named variable for the preset, “has not been defined”.
I can see how it isn’t defined, but I can’t figure out how to have the handler also define it.
So hard to explain, hope I’m making some sense.
-----------------------------------------------------
# Hue preset making handler
-----------------------------------------------------
on huePreset(Preset, state, trans, hue, ct, bri, sat)
set Preset to the quoted form of ("{\"on\": " & state & ", \"transitiontime\": " & trans & ", \"hue\": " & hue & ", \"ct\": " & ct & ", \"bri\": " & bri & ", \"sat\": " & sat & "}")
end huePreset
-----------------------------------------------------
# Hue send command handler
-----------------------------------------------------
on hue(setting, destination)
do shell script "curl --request PUT --data " & setting & " " & destination
delay 0.1
end hue
huePreset("TestPreset", true, "30", "20000", "", "254", "254") ---This creates the preset's name to be used as a variable in the next phase, and then the values to be passed onto the actual command string
hue(TestPreset, DestinationAddress) ---This takes the newly created setting called TestPreset and sends it to DestinationAddress
Without the handler, I used to create such presets this way:
set TestPreset to the quoted form of "{\"on\": true, \"transitiontime\": 30, \"hue\": 20000, \"ct\": , \"bri\": 254, \"sat\": 254}"
But it’s messy when you have plenty of them, they extend to the next row and the values are pretty annoying to edit.
The variables that you can enter into the command, by the way, are simply all the possible variables that can be sent; In reality, some are exclusive to specific lamp models only or I might not necessarily want to change every possible value in a single command, so the possibility to leave some values empty is intentional. In this case value ct is empty just to test that it’s still getting accepted.