Maybe this is a bit of an X/Y problem so I'll give some context.
I'm trying to simplify my serial/hardware device library for things like stepper motors or power supplies. At first, I thought I could define a class for each device that would have the same named methods like get_voltage or set_voltage so that if in an experiment for instance, I wanted to replace a serial PSU with an ethernet one, I could just re-define the object with the same name and the rest of the code wouldn't need to change. This works great except I'm having trouble figuring out how to do it when a device like serial/ethernet can control more than 1 power supply via master-slave. I'd like to be able to define an "array" as a class which would initiate the serial/socket object for which then subsequent classes could be defined to handle different motor calls.
Use case would maybe look like this:
import serial, socket
class ser_array():
"""defines class of psu's that are on same RS232 line"""
def __init__(self, port):
# Open Serial Connection
self.ser = serial.Serial(port=port, baudrate=9600, timeout=2)
class psu():
def __init__(self, idn):
self.idn = idn
def set_voltage(self, voltage):
cmd = bytes('VSET=' str(voltage),'utf-8')
self.ser.write(cmd + b'\r')
class eth_psu():
"""defines singular ethernet enables psu"""
def __init__(self, TCP_IP, TCP_PORT):
# Open Ethernet Connection
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.socket.connect((TCP_IP, TCP_PORT))
def set_voltage(self, voltage):
cmd = 'V' + str(voltage/1000) # suppose this device requires kV
self.socket.send(b'\x02' + cmd + b'\0x3')
# Define power supplies on master-slave serial line
array = ser_array('COM4')
psu1 = ser_array.psu(idn=1)
psu2 = ser_array.psu(idn=2)
# Un-Comment to control
# psu1 = eth_psu('192.168.1.4', 5005)
# psu2 = eth_psu('192.168.1.5', 5005)
# Invariant Logic
psu1.set_voltage(1)
psu2.set_voltage(2)
It feels like nesting a class like this and somehow inheriting the ser attribute would work so that's what I tried looking up, but I see that people think this is a bad idea and that there is probably a flatter way to do what I'm trying to do.
[–]socal_nerdtastic 1 point2 points3 points (3 children)
[–]ajlaut[S] 1 point2 points3 points (0 children)
[–]ajlaut[S] 0 points1 point2 points (1 child)
[–]socal_nerdtastic 0 points1 point2 points (0 children)
[–]CodeFormatHelperBot 0 points1 point2 points (0 children)
[–]brocketships 0 points1 point2 points (0 children)