1

I have written this class that connects to a relay board and allows me to send the commands to turn off and on the different relays upon it.

class relay_board:
    def __init__(self, com_port):
        self.com_port = com_port
        self.ser = serial.Serial(self.com_port, 9600, timeout=2)

        self.shorttime = 0.01

    def send_command(self, bank, ports):
        self.bank = bank
        self.ports = ports

        message = bank+ports

        self.ser.write(message)
        time.sleep(0.01)

And I am calling it like this,

relay_one = relay_board.relay_board('COM3')

relay_one.send_command(b'\x42', b'\x00')
relay_one.send_command(b'\x43', b'\x3F')

Does the class destroy the self.ser when the program is finished or do I have to add a __del__ or a def close_serial() function to close the serial connection at the end?

john-hen
  • 4,410
  • 2
  • 23
  • 40

1 Answers1

2

The Serial object has a __del__ method which does what you want, so you don't need to write it.

That being said, you shouldn't rely on __del__ being called. For the same reason that you shouldn't leave files opened, you shouldn't rely on the garbage collector to close things for you. In fact, during interpreter shutdown, there is no reason to garbage collect your objects since the OS will reclaim this memory anyway, so implementations other than CPython don't really bother. The reason to do it is these objects that hold handles to OS resources which may not get closed when the program closes.

So, to be sure that the handle gets released properly, you should close() the serial port yourself, and not wait for interpreter shutdown to do it for you.

Danya02
  • 1,006
  • 1
  • 9
  • 24
  • Thanks for this explanation, it makes a lot more sense now. I have actually moved the serial initialisation out if the init function and placed it in the get command function. I also run it using ```with as``` so it should close properly I think. I am also running the close() at the end just to be double sure. – ProgramMasher May 17 '21 at 12:12
  • So you're keeping the port closed while you're not sending commands? I'm not sure how exactly buffering in serial ports works, but if the target device sends anything back and you aren't reading it then it could fill up the device-to-computer buffers which can get the device softlocked as it waits for you to read all the data it's sent you. I've ran into this problem with an Arduino once, but I can't remember the specifics. – Danya02 May 17 '21 at 12:39
  • Yep, I am keeping it closed, it is okay for the device I am using at the moment as it is unable to send anything over serial. It is a relay board that only accepts commands so not an issue here. It is a valid point that I will keep an eye out for in the future though. – ProgramMasher May 18 '21 at 13:23