LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

Return a Python Class Instance

I'm not sure if this is possible, but I'm trying to get the Python node in LV21 to return an instance of a Python class from one of my functions in a Python module. These functions are fairly rudimentary, as I'm still testing things out.

 

 

import serial

def serial_open(port_name, baud_rate, timeout=10):
    port = serial.Serial()
    port.port = rf'\\.\{port_name}'
    port.baudrate = baud_rate
    port.timeout = timeout
    port.open()
    return port

 

 

As you can see, my 'serial_open()' function is returning an instance of 'serial.Serial()'. This instance will end up being passed to other functions in my module (see below). I'm just not sure how to get the LV Python node to return a class instance...

 

 

def serial_close(port):
    if isinstance(port, serial.Serial):
        try:
            port.close()
            return 0
        except OSerror:
            return 1


def serial_read(port, buffer_size=1)
    if isinstance(port, serial.Serial) and port.is_open:
        return port.read(buffer_size)


def serial_write(port, data)
    if isinstance(port, serial.Serial) and port.is_open:
        return port.write(data)

 

 

Ideally, I'd like to be able to use it in a manner similar to a refnum that will be passed around to / from the various functions. Any help is appreciated!

 

FWIW, this code is all working fine when called directly within Python...just struggling with the LabView half.

 

And yes, I have tried VISA and the built-in serial functions - they (for one reason or another) aren't working with the hardware we're using which is a MicroGate "SyncLink" GT4 PCI serial adapter. If somebody has a better idea for interfacing with these cards directly in LabVIEW, I'm all ears!

 

Thanks in advance!

 

Edit: typo

0 Kudos
Message 1 of 3
(1,259 Views)

Update to say that I forgot to mention I'm using Python 3.7.2.

0 Kudos
Message 2 of 3
(1,229 Views)

Use python global instead.

import serial

port = None

def serial_open(port_name, baud_rate, timeout=10):
    global port
    port = serial.Serial()
    port.port = rf'\\.\{port_name}'
    port.baudrate = baud_rate
    port.timeout = timeout
    port.open()

def serial_read(buffer_size=1)
    global port
    if port is None:
        raise Exception("port not opened")

    if isinstance(port, serial.Serial) and port.is_open:
        return port.read(buffer_size)

 

0 Kudos
Message 3 of 3
(1,118 Views)