From 5e94f480b244f3c53cf7806d41c014b80ea39131 Mon Sep 17 00:00:00 2001 From: Pim van den Berg Date: Sun, 25 Oct 2020 13:54:43 +0100 Subject: [PATCH] feat(itho-wpu): cli arguments to run master/slave only + set slave timeout --master-only allows to only run the I2C master functionality. --slave-only allows to only run the I2C slave functionality. The I2C slave functionality via the "set_callback" mechanism (--type callback) just executes the pigpio "event_callback()" function and waits for 2 seconds for a response. The amount of seconds can now be configured via --slave-timeout. --- itho-wpu.py | 33 ++++++++++++++++++++------------- 1 file changed, 20 insertions(+), 13 deletions(-) diff --git a/itho-wpu.py b/itho-wpu.py index 14134cc..e06e7e5 100755 --- a/itho-wpu.py +++ b/itho-wpu.py @@ -34,6 +34,10 @@ def parse_args(): parser.add_argument('--loglevel', nargs='?', choices=["debug", "info", "warning", "error", "critical"], help="Loglevel") + parser.add_argument('--master-only', action='store_true', help="Only run I2C master") + parser.add_argument('--slave-only', action='store_true', help="Only run I2C slave") + parser.add_argument('--slave-timeout', nargs='?', type=int, default=2, + help="Slave timeout in seconds.") args = parser.parse_args() return args @@ -47,11 +51,12 @@ class I2CSlave(): logger.error("not pi.connected") return - def set_callback(self, q): + def set_callback(self, q, timeout): logger.debug("set_callback()") e = self.pi.event_callback(pigpio.EVENT_BSC, self.callback) self.pi.bsc_i2c(self.address) - time.sleep(2) + logger.debug(f"Waiting {timeout}s for activity") + time.sleep(timeout) e.cancel() self.pi.bsc_i2c(0) # Disable BSC peripheral self.pi.stop() @@ -117,18 +122,20 @@ if __name__ == "__main__": q = queue.Queue() - slave = I2CSlave(address=0x40) - if args.type == 'callback': - slave_thread = threading.Thread(target=slave.set_callback, args=[q]) - elif args.type == 'wait': - slave_thread = threading.Thread(target=slave.wait, args=[q]) - slave_thread.start() + if not args.master_only: + slave = I2CSlave(address=0x40) + if args.type == 'callback': + slave_thread = threading.Thread(target=slave.set_callback, args=[q, args.slave_timeout]) + elif args.type == 'wait': + slave_thread = threading.Thread(target=slave.wait, args=[q]) + slave_thread.start() - master = I2CMaster(address=0x41, bus=1) - if args.action: - master.execute_action(args.action) - master.close() + if not args.slave_only: + master = I2CMaster(address=0x41, bus=1) + if args.action: + master.execute_action(args.action) + master.close() - if args.type == 'wait': + if args.type == 'wait' and not args.master_only: result = q.get() logger.info(f"Response: {result}")