There are multiple ways to solve this, there is not one single way that is the best
. If you’re satisfied with the way you’ve solved it, keep with it. You can look on these other examples to see other ways of solving the same issue.
If you want to simplify and down size in the amount of lines to get this working you can look at AppDaemon and this script for the same end result AppDaemon motion detectionlights version 1.1
Or if you prefer wholly inside of HASS you can look at Turn on lights on and keep them on when motion detection
/R