Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Read Timeout? #3

Open
yachtwave opened this issue May 3, 2024 · 3 comments
Open

Read Timeout? #3

yachtwave opened this issue May 3, 2024 · 3 comments

Comments

@yachtwave
Copy link

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
Copy link
Owner

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
Copy link
Owner

@yachtwave Did it solve your problem?

@yachtwave
Copy link
Author

yachtwave commented May 14, 2024 via email

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants