adamczykpiotr / php-canbus

Extension for PHP to interface efficiently with a Controller Area Network (CAN bus) 2.0A / 2.0B
7 stars 5 forks source link

Read Timeout? #3

Open yachtwave opened 2 months ago

yachtwave commented 2 months ago

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!

adamczykpiotr commented 2 months ago

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!

adamczykpiotr commented 1 month ago

@yachtwave Did it solve your problem?

yachtwave commented 1 month ago

Hi, Piotr. I haven't had a chance to test it, but you can consider this resolved. I greatly appreciate it - john

--

Capt. John O'Keefe FOUNDER, YACHTWAVE USCG 100 GT MASTER

www.yachtwave.com | @. @.>

935 N Beneva Rd, Ste 609, Sarasota, FL 34232 https://maps.google.com/?q=935+N+Beneva+Rd,+Ste+609+PMB+2056,+Sarasota,+FL+34232

On Mon, May 13, 2024 at 3:20 AM Piotr Adamczyk @.***> wrote:

@yachtwave https://github.com/yachtwave Did it solve your problem?

— Reply to this email directly, view it on GitHub https://github.com/adamczykpiotr/php-canbus/issues/3#issuecomment-2106831964, or unsubscribe https://github.com/notifications/unsubscribe-auth/A7OOXAFBTKKUJ3M6W5BSUSLZCBSVBAVCNFSM6AAAAABHGGFWVWVHI2DSMVQWIX3LMV43OSLTON2WKQ3PNVWWK3TUHMZDCMBWHAZTCOJWGQ . You are receiving this because you were mentioned.Message ID: @.***>