Read Timeout?
Opened this issue · 3 comments
Anyway, can you get a timeout on the "read"? For example, if the data on the network stops (for whatever reason), the process sits at the "read command" waiting for data. When used as a service with a watchdog, the watchdog needs to be pinged every 30 seconds, which can not happen when the code is stuck at the ->read function. please help!
Hey! I think this can be easily solved by initialising socket as non-blocking $canBus->init(false)
and writing custom wrapper function for read:
function readUntil(CanBus $bus, int $timeout = 500, int $delayMs = 10): ?CanFrame {
$cutOff = microtime(true) + ($timeout / 1000); // Time in the future where we should no longer wait
while(microtime(true) <= $cutOff) {
$frame = $bus->read();
if($frame !== false) {
return $frame;
}
usleep($delayMs); // Sleep some time to reduce CPU busy time
}
return null;
}
Or if you'd like to return CanFrame|false:
function readUntil(CanBus $bus, int $timeout = 500, int $delayMs = 10): CanFrame|bool {
$cutOff = microtime(true) + ($timeout / 1000); // Time in the future where we should no longer wait
$frame = false;
while(microtime(true) <= $cutOff && $frame === false) {
$frame = $bus->read();
if($frame === false) {
usleep($delayMs);
}
}
return $frame;
}
To make it nice an clean in your project, you could extend CanBus class and add new readUntil
method to it or something along those lines. Please let me know if this solves your problem!
@yachtwave Did it solve your problem?