Delete Pybricks Objects or Run Multiple Objects
Searching for a method to switch between gear ratios, motor direction, motor ports, gyro vs non-gyro Drive Base.
Currently you cannot assign the same port to multiple object definitions or create multiple DriveBase objects.
I would like to request a solution to avoid the dreaded "OSError: [Errno 16] EBUSY: Device or resource busy" error when trying to reconfigure a port, motor or drivebase.
Adding the ability to destroy/deconstruct class objects seems the most straight forward and reliable way to ensure everything works.
Note: As far as I can tell, the class __del__ deconstructor is not being called by micropython when I run "del objectvariable" on my own defined classes.
Example Code with Deconstructor
self.hub = PrimeHub()
# Assign Motors and DriveBase
self.leftDrive = (Port.A, Direction.CLOCKWISE, [28, 20])
self.rightDrive = (Port.B, Direction.CLOCKWISE, [28, 20])
self.drive = DriveBase(self.leftDrive, self.rightDrive, wheel_diameter=65, axle_track=120)
# Switch to GyroDriveBase
del self.drive
self.drive = GyroDriveBase(self.leftDrive, self.rightDrive, wheel_diameter=65, axle_track=120)
# Switch to New Motors
del self.leftDrive
del self.rightDrive
del self.drive
self.leftDrive = (Port.E, Direction.CLOCKWISE, [28, 20])
self.rightDrive = (Port.F, Direction.CLOCKWISE, [28, 20])
self.drive = DriveBase(self.leftDrive, self.rightDrive, wheel_diameter=65, axle_track=120)
# Switch to New Gear Ratio and Motor Direction
del self.leftDrive
del self.rightDrive
del self.drive
self.leftDrive = (Port.E, Direction.COUNTERCLOCKWISE, [12, 20])
self.rightDrive = (Port.F, Direction.COUNTERCLOCKWISE, [12, 20])
self.drive = DriveBase(self.leftDrive, self.rightDrive, wheel_diameter=65, axle_track=120)
Alternative Allow multiple motor and drivetrain objects to be created with repeated ports. This would avoid having to delete anything while still allowing full functionality at the cost of memory usage.
Motor.close() was added in https://github.com/pybricks/support/issues/904. I guess it didn't make it into the docs yet. And there isn't a DriveBase.close() yet.
Side note: del x doesn't actually operate on the object that x is associated with - it only removes the association with the name x. del has no relation to __del__. This is a common misconception in Python because the names are the same and reference counting in CPython makes it appear as if the former directly triggers the latter under certain circumstances. MicroPython uses a garbage collector instead of reference counting to manage memory so it doesn't behave the same a CPython.
gyro vs non-gyro Drive Base
There will be a toggle for use_gyro(True) and use_gyro(False) for this.
It's also possible to make multiple drive bases (and implement your own logic to decide when to use which).
To switch motor direction on the fly, perhaps you could negate the speed when needed?