There’s an awesome node in node-red for exactly that. “Get Entities”.
My goodnight routine closes the garage doors, locks the doors, arms the alarm and turns off all the lights. It would take well over a minute because of all the z-wave traffic and I find the HE hub doesn’t handle tons of commands at once very well.
I created groups in HA and used the get entities node to determine which lights (and others) were actually on and send the off commands only to those devices. My goodnight routine is now fully completed in under 10s.
You can see here, instead of 30 some lights being told to turn off, only 3 were on so it only sent the off command to those 3.
Here’s the import code to give you a jumping off point. You’ll need to add a trigger and adjust to your setup.
[{"id":"7d9b910b.9eee2","type":"api-call-service","z":"a8efc4c6.6fe918","name":"Turn Off Lights","server":"94fdcfdf.a00b","version":1,"debugenabled":false,"service_domain":"light","service":"turn_off","entityId":"","data":"{\"entity_id\":\"{{payload}}\"}","dataType":"json","mergecontext":"","output_location":"","output_location_type":"none","mustacheAltTags":false,"x":900,"y":260,"wires":[[]]},{"id":"46e1c983.10f708","type":"join","z":"a8efc4c6.6fe918","name":"","mode":"custom","build":"string","property":"payload","propertyType":"msg","key":"topic","joiner":", ","joinerType":"str","accumulate":false,"timeout":"","count":"","reduceRight":false,"reduceExp":"","reduceInit":"","reduceInitType":"","reduceFixup":"","x":750,"y":260,"wires":[["7d9b910b.9eee2"]]},{"id":"bef4604a.81564","type":"template","z":"a8efc4c6.6fe918","name":"Format Msg","field":"payload","fieldType":"msg","format":"handlebars","syntax":"mustache","template":"{{payload.entity_id}}","output":"str","x":610,"y":260,"wires":[["46e1c983.10f708"]]},{"id":"393e066b.78413a","type":"ha-get-entities","z":"a8efc4c6.6fe918","server":"94fdcfdf.a00b","name":"Which Lights?","rules":[{"property":"entity_id","logic":"in_group","value":"group.goodnight_lights","valueType":"str"},{"property":"state","logic":"is","value":"on","valueType":"str"}],"output_type":"split","output_empty_results":false,"output_location_type":"msg","output_location":"payload","output_results_count":1,"x":400,"y":260,"wires":[["bef4604a.81564"]]},{"id":"94fdcfdf.a00b","type":"server","z":"","name":"Home Assistant","addon":true}]