I am trying to create a "synchronised method" that is only ever called by one thread at a time.
Firstly I should say I am a groovy nooby, so please bear with me! I have written a thermostat driver that communicates through telnet. The driver contains 9 methods that get or set the thermostat parameters but those methods all call the same function to actually send the commands through telnet. Each command must complete or timeout before the next one begins. Below is my telnet communication function that needs to run as a single instance, however it doesn't! If I fire of multiple get/set parameter methods then I see mulitple instances of the "samComms" function running concurrently. I should add that I tried importing "groovy.transform.Synchronized" but that threw an error in the hub.
Can anyone help me get this working ?
def synchronized Boolean samComms(command, verify, parameter) {
if (debugLogEnable) log.debug "samComms(): Called"
for(int retries = 0; retries<3; retries++){ // Send command a max of 3 times
if (debugLogEnable) log.debug "samComms: top of retry while, just before sendHubCommand command = $command"
sendHubCommand(new hubitat.device.HubAction(command, hubitat.device.Protocol.TELNET))
sendEvent(name: "parseComms", value: command, descriptionText: "samComms")
pauseExecution(1800) // Wait for reply, most commands execute with 1.5 secs
for(int timeout = 0; timeout<7; timeout++){ //Max timeout is 6 seconds, so check response from parse every second
response = device.currentValue("parseComms", true)
if ( response != command ) {
if("$verify"(response,parameter)) return true // Got a valid response
else break
}
pauseExecution(1000)
}
// Only get here if did not receive a valid response
log.warn "samComms: About to retry command, $command response from SAM was $response"
}
log.error "samComms: Command returned an error or timed out"
sendEvent(name: "parseComms", value: "ERROR", descriptionText: "samComms returned $response")
return false