Improved watering sequence

I have been attempting to improve the watering experience to make more resilient hence the focus on the UTM connection improvement and I now offer up my coding methods for comment.

My sequence looks like this



The coding style here (LAUNCHER / SEQ / SUB comes from here)

The code for ‘Water all’ is now a SUB sequence of the launcher about. The Launcher sets up the watering head doing checks to make sure it worked to prevent a water drill being sent to water plants

My code replaced this one line

    points = api({method = "GET", url = "/api/points"})

and make it check until it gets a good read - or failed after 3 minutes.


local watering_time = variable("Watering Time (Seconds)")
start_time = os.time() * 1000

-- New code is below
local theNumberOfAllowableNetworkTries = 9
local theSecondsDelayBetweenRetries = 20
local failedToGetPoints = 1
local points

while( theNumberOfAllowableNetworkTries > 0 )
do
    theNumberOfAllowableNetworkTries = theNumberOfAllowableNetworkTries -1
    points = api({method = "GET", url = "/api/points"})

    if points then
        toast("Plant list obtained", "info")
        theNumberOfAllowableNetworkTries = 0
        failedToGetPoints = 0
    else
        toast("Error - Unable to obtain list of plants (Retrying)", "warn")
        wait (theSecondsDelayBetweenRetries * 1000)
        theNumberOfAllowableNetworkTries = theNumberOfAllowableNetworkTries -1
    end
end

if (failedToGetPoints == 1) then
    toast("Fatal Error - Unable to obtain list of plants (EXITING)", "error")
    return
end

-- end of new code



local plants = {}

for k, v in pairs(points) do
    if v.pointer_type == "Plant" then
        table.insert(plants, {name = v.name, x = v.x, y = v.y})
    end
end

table.sort(plants, function(l, r)
    -- "close enough" approximation.
    if math.abs(l.x - r.x) < 150 then
        return l.y < r.y
    else
        return l.x < r.x
    end
end)

count = 0
total = #plants
job = "Watering all " .. total .. " plants"

send_message(
    "info",
    "Watering all " .. total .. " plants for " .. watering_time .. " seconds each",
    "toast")

for k, v in pairs(plants) do
    coordinates = "(" .. v.x .. ", " .. v.y .. ")"
    set_job_progress(job, {
        percent = 100 * (count) / total,
        status = "Moving to " .. (v.name or "plant") .. " at " .. coordinates,
        time = start_time
    })
    move_absolute(v.x, v.y, 0)
    set_job_progress(job, {
        percent = 100 * (count + 0.5) / total,
        status = "Watering " .. (v.name or "plant") .. " for " .. watering_time .. " seconds",
        time = start_time
    })
    write_pin(8, "digital", 1)
    wait(watering_time * 1000)
    write_pin(8, "digital", 0)
    count = count + 1
end

set_job_progress(job, {
    percent = 100,
    status = "Complete",
    time = start_time
})

Comments anyone?