Exemplo n.º 1
0
def read_plc(plc_ip, tag_name):
    plc = ClxDriver()
    if plc.open(plc_ip):
        tag_value = plc.read_tag(tag_name)[0]
        plc.close()
        return tag_value
    else:
        print("Unable to open: ", plc_ip)
Exemplo n.º 2
0
def read_plc(ipaddress: str, tag_name: str):
    result = None
    c = ClxDriver()
    try:
        c.open(ipaddress)
        is_open = True
    except:
        is_open = False
        return False

    return c.read_tag(tag_name)
Exemplo n.º 3
0
def enip_read(plc_ip, tag_name):
    """Read a plc tag and print the rx data

    """

    plc = ClxDriver()
    if plc.open(plc_ip):
        print(plc.read_tag(tag_name))
        plc.close()
    else:
        print("Unable to open", plc_ip)
Exemplo n.º 4
0
def enip_write(plc_ip, tag_name, value, tag_type):
    """Write a plc tag and print the resutl

    :value: TODO
    :tag_type: TODO
    """

    plc = ClxDriver()
    if plc.open(plc_ip):
        print(plc.write_tag(tag_name, value, tag_type))
        plc.close()
    else:
        print("Unable to open", plc_ip)
Exemplo n.º 5
0
def write_plc(plc_ip, tag_name, value, tag_type):
    plc = ClxDriver()
    if plc.open(plc_ip):
        if plc.write_tag(tag_name, value, tag_type):
            print("Success")
            print("Target: " + plc_ip)
            print("Tag Name: " + tag_name)
            print("Value: " + str(value))
            print("Tag Type: " + tag_type)
        else:
            print("Failed to write to " + plc_ip)
        plc.close()
    else:
        print("Unable to open: ", plc_ip)
Exemplo n.º 6
0
def test_plc_write(plc_ip, tag_name, value, tag_type):
    """Write a plc tag and print a BOOL status code.

    :plc_ip: TODO
    :tag_name: TODO
    :value: TODO
    :tag_type: TODO

    """
    plc = ClxDriver()
    if plc.open(plc_ip):
        print(plc.write_tag(tag_name, value, tag_type))
        plc.close()
    else:
        print("Unable to open", plc_ip)
Exemplo n.º 7
0
def test_plc_read_val(plc_ip, tag_name):
    """Read a plc tag and print the rx data

    :plc_ip:
    :tag_name:
    """

    plc = ClxDriver()
    if plc.open(plc_ip):
        tagg = plc.read_tag(tag_name)
        plc.close()
        return (tagg)
        
    else:
        print("Unable to open", plc_ip)
Exemplo n.º 8
0
    def reset(self):
        c = PLCDriver()
        if c.open(plc_ip):
            pos_tag = 'nerfgun_position_fire'
            motor_tag = 'trigger_motor_on'
            fire_tag = 'trigger_bullet_fire'

            c.write_tag((pos_tag, 1, 'BOOL'))
            c.write_tag((motor_tag, 0, 'BOOL'))
            c.write_tag((fire_tag, 0, 'BOOL'))

            print('Resetting Position')

            self.triggerBtn.setText(" Drop Gun ")
            self.motorBtn.setText(" Start Motor ")
            self.triggerBtn.setText(" Fire Bullets ")

        c.close()
Exemplo n.º 9
0
def write_tag(addr, tag, val, plc_type="CLX"):
    """Write a tag value to the PLC."""
    direct = plc_type == "Micro800"
    clx = ClxDriver()
    if clx.open(addr, direct_connection=direct):
        try:
            prevval = clx.read_tag(tag)
            if direct:
                time.sleep(1)
            write_result = clx.write_tag(tag, val, prevval[1])
            return write_result
        except Exception:
            print("Error during writeTag({}, {}, {})".format(addr, tag, val))
            err = clx.get_status()
            clx.close()
            print(err)
            return False
        clx.close()
    return False
Exemplo n.º 10
0
def main(argv):
    ip = ''
    read_register = ''
    write_register = ''
    values = ''
    number = 0
    try:
        opts, args = getopt.getopt(argv,"hi:r:n:w:v:")
    except getopt.GetoptError:
        print 'plc.py -i <ip> -r <read register> -w <write register> -n <num to read> -v <value1 value2>'
        sys.exit(2)
    for opt, arg in opts:
        if opt in ("-h","--help"):
            print 'plc.py -i <ip> -r <read register> -w <write register> -n <num to read> -v <value1,value2>'
            sys.exit()
        elif opt in ("-i","--ip"):
            ip = arg
        elif opt in ("-r", "--read"):
            read_register = arg
        elif opt in ("-n", "--number"):
            number = arg
        elif opt in ("-w", "--write"):
            write_register = arg
        elif opt in ("-v", "--value"):
            values = arg
    #c = SlcDriver()
    c = ClxDriver()
    if c.open(ip):
        if(write_register and values):
            c.write_tag(write_register, map(int, values.split()))
        if(read_register):
            vals = c.read_tag([read_register])
            if(isinstance(vals, list)):
                vals=map(str, vals)
                print " ".join(vals)
            else:
                print vals
        # print c.write_tag('N7:0', [-30, 32767, -32767])
        # print c.write_tag('N7:0', 21)
        # print c.read_tag('N7:0', 10)
        # c.write_tag('B3/3955', 1)
        # print c.read_tag('B3/3955')
        # c.write_tag('N7:0/2', 1)
        # print c.read_tag('N7:0/2')
        c.close()
Exemplo n.º 11
0
    def trigger(self):
        c = PLCDriver()
        if c.open(plc_ip):
            tag = 'trigger_bullet_fire'
            r_tag = c.read_tag([str(tag)])
            value = int(r_tag[0][1])

            if (value == 0):
                w_tag = c.write_tag((tag, 1, 'BOOL'))
                self.triggerBtn.setText(" Stop Firing ")
                print('Firing On')

            elif (value == 1):
                w_tag = c.write_tag((tag, 0, 'BOOL'))
                self.triggerBtn.setText(" Fire Bullets ")
                print('Firing Off')
            else:
                print('Error!')
        c.close()
Exemplo n.º 12
0
    def motor(self):
        c = PLCDriver()
        if c.open(plc_ip):
            tag = 'trigger_motor_on'
            r_tag = c.read_tag([str(tag)])
            value = int(r_tag[0][1])

            if (value == 0):
                w_tag = c.write_tag((tag, 1, 'BOOL'))
                self.motorBtn.setText(" Stop Motor ")
                print('Motor On')

            elif (value == 1):
                w_tag = c.write_tag((tag, 0, 'BOOL'))
                self.motorBtn.setText(" Start Motor ")
                print('Motor Off')
            else:
                print('Error!')
        c.close()
Exemplo n.º 13
0
    def position_gun(self):
        c = PLCDriver()
        if c.open(plc_ip):
            tag = 'nerfgun_position_fire'
            r_tag = c.read_tag([str(tag)])
            value = int(r_tag[0][1])

            if (value == 0):
                w_tag = c.write_tag((tag, 1, 'BOOL'))
                self.positionBtn.setText(" Drop Gun ")

                print('Moving Up')
            elif (value == 1):
                w_tag = c.write_tag((tag, 0, 'BOOL'))
                self.positionBtn.setText(" Hide Gun ")

                print('Moving Down')
            else:
                print('Error!')
        c.close()
Exemplo n.º 14
0
def read_tag(addr, tag, plc_type="CLX"):
    """Read a tag from the PLC."""
    direct = plc_type == "Micro800"
    addr = str(addr)
    c = ClxDriver()
    try:
        if c.open(addr, direct_connection=direct):
            try:
                if type(tag) == type([]):
                    read_values = []
                    for t in tag:
                        read_values.append(c.read_tag(t))
                    return read_values
                else:
                    return c.read_tag(tag)
                return v
            except DataError as e:
                c.close()
                time.sleep(TAG_DATAERROR_SLEEPTIME)
                print("Data Error during readTag({}, {}, plc_type='{}'): {}".
                      format(addr, tag, plc_type, e))
        else:
            raise DataError("no data")

    except CommError:
        # err = c.get_status()
        c.close()
        print("Could not connect during readTag({}, {})".format(addr, tag))
        # print err
    except AttributeError as e:
        c.close()
        print("AttributeError during readTag({}, {}): \n{}".format(
            addr, tag, e))
    c.close()
Exemplo n.º 15
0
        mylog.write(response.read() + '\n')
        print(response.read())
    except Exception as e:
        mylog.write("Failed to contact Web App" + '/n')
        mylog.write(e + '/n')
        mylog.flush()


# Main function

if __name__ == '__main__':
    runloop = 1
    var_init()
    mylog.write('Session information from ' + str(datetime.datetime.now()) +
                '\n')
    c = ClxDriver()
    mylog.write(str(c['port']) + '\n')
    print c['port']
    mylog.write(str(c.__version__) + '\n')
    print c.__version__
    print tag1
    mylog.flush()
    # attempt to open connection to PLC
    if c.open(plcip):
        while runloop == 1:
            try:
                # Read value of tag. Only using a single tag currently, future enhancements to enable multiple
                myMachineStop = str(c.read_tag(tag1))

                # Data is returned as comma seperated and in paranthesis. Removing formatting to isolate just values
                myMachineStop = myMachineStop.replace("(", "")
Exemplo n.º 16
0
 def __init__(self):
     # initialize a thread safe queue
     # load queue with a single plc obj
     self.plc = ClxDriver()
     self.mutex = Lock()
Exemplo n.º 17
0
class EIPFunctions:
    def __init__(self):
        # initialize a thread safe queue
        # load queue with a single plc obj
        self.plc = ClxDriver()
        self.mutex = Lock()

    def is_connected(self):
        with self.mutex:
            return self.plc.is_connected()

    def connect_plc(self, ip):
        with self.mutex:
            self.plc.open(ip)
            return self.plc.is_connected()

    def disconnect_plc(self):
        with self.mutex:
            if self.plc.is_connected():
                self.plc.close()

    def read_tag(self, tag_name):
        with self.mutex:
            return self.plc.read_tag(tag_name)[0]

    def write_tag(self, tag_name, tag_value, tag_type):
        """
        :param tag_name: tag name, or an array of tuple containing (tag name, value, data type)
        :param tag_value: the value to write or none if tag is an array of tuple or a tuple
        :param tag_type: the type of the tag to write or none if tag is an array of tuple or a tuple
        :return: None is returned in case of error otherwise the tag list is returned
        The type accepted are:
            - BOOL
            - SINT
            - INT'
            - DINT
            - REAL
            - LINT
            - BYTE
            - WORD
            - DWORD
            - LWORD
        """
        with self.mutex:
            return self.plc.write_tag(tag_name, tag_value, tag_type)

    def read_tag_string(self, tag_name):
        with self.mutex:
            return self.plc.read_string(tag_name)

    def write_tag_string(self, tag_name, tag_value):
        with self.mutex:
            return self.plc.write_string(tag_name, tag_value)

    def read_tag_array(self, tag_name, count):
        with self.mutex:
            return self.plc.read_array(tag_name, count)

    def write_tag_array(self, tag_name, tag_array, tag_type):
        with self.mutex:
            self.plc.write_array(tag_name, tag_array, tag_type)

        # always return true; pycomm is not telling us if we succeed or not
        return True
Exemplo n.º 18
0
# Fires when 'longgun' appears in message
def parse_msg(message,fp):
    t_end = time.time() + 60 * .02
    t_end2 = time.time() + 60 * .058

    if "longgun" in message:
        motor_state(t_end)
        fire_bullets(t_end2)
        hide_gun()
        while "longgun" in message:
            message = fp.readline()


if __name__ == '__main__':

    c = ClxDriver()

    print('PLC Port Number: ' + str(c['port']))
    print('Driver Version: ' + str( c.__version__))

    # Path for AK47 Detection Program
    filepath = "/home/nvidia/Documents/yolov2/capturedetect"

    # IP address for PLC
    if c.open('192.168.0.203'):

        with open(filepath) as fp:
            while 1:
                line = fp.readline()
                try:
                    print(line.rstrip())
Exemplo n.º 19
0
from pycomm.ab_comm.clx import Driver as ClxDriver
import logging

from time import sleep

if __name__ == '__main__':

    logging.basicConfig(filename="ClxDriver.log",
                        format="%(levelname)-10s %(asctime)s %(message)s",
                        level=logging.DEBUG)
    c = ClxDriver()

    print c['port']
    print c.__version__

    if c.open('172.16.2.161'):
        while 1:
            try:
                print(c.read_tag(['ControlWord']))
                print(c.read_tag(['parts', 'ControlWord', 'Counts']))

                print(c.write_tag('Counts', -26, 'INT'))
                print(c.write_tag(('Counts', 26, 'INT')))
                print(c.write_tag([('Counts', 26, 'INT')]))
                print(
                    c.write_tag([('Counts', -26, 'INT'),
                                 ('ControlWord', -30, 'DINT'),
                                 ('parts', 31, 'DINT')]))
                sleep(1)
            except Exception as e:
                c.close()
Exemplo n.º 20
0
from pycomm.ab_comm.clx import Driver as ClxDriver
import logging

from time import sleep


if __name__ == "__main__":

    logging.basicConfig(
        filename="ClxDriver.log", format="%(levelname)-10s %(asctime)s %(message)s", level=logging.DEBUG
    )
    c = ClxDriver()

    print c["port"]
    print c.__version__

    if c.open("172.16.2.161"):
        while 1:
            try:
                print (c.read_tag(["ControlWord"]))
                print (c.read_tag(["parts", "ControlWord", "Counts"]))

                print (c.write_tag("Counts", -26, "INT"))
                print (c.write_tag(("Counts", 26, "INT")))
                print (c.write_tag([("Counts", 26, "INT")]))
                print (c.write_tag([("Counts", -26, "INT"), ("ControlWord", -30, "DINT"), ("parts", 31, "DINT")]))
                sleep(1)
            except Exception as e:
                err = c.get_status()
                c.close()
                print err
Exemplo n.º 21
0
from pycomm.ab_comm.clx import Driver as ClxDriver
import logging

from time import sleep

if __name__ == '__main__':

    logging.basicConfig(filename="ClxDriver.log",
                        format="%(levelname)-10s %(asctime)s %(message)s",
                        level=logging.DEBUG)
    c = ClxDriver()

    print c['port']
    print c.__version__

    if c.open('192.168.0.167', 3):
        try:
            # r_array = c.read_array("F20_CreamReceoption.Tickets",2)
            # print r_array
            # for tag in r_array:
            #     print (tag)
            # x = c.read_tag(['Python_Teste_01'])
            # print x[0][1]
            # print(c.read_tag(['F20_CreamReceoption']))
            # print(c.read_tag('Python_Teste_03'))
            # print(c.read_tag(['Python_Teste_04']))
            print(c.read_string('F20_CreamReceoption.Tickets[0].StartTime'))

            # print(c.read_tag(['parts', 'ControlWord', 'Counts']))
            # print(c.write_string('Python_Teste_06', 'Flex Automacao'))
            # print(c.write_tag(('TankSelectedToExpedition', 26, 'INT')))
Exemplo n.º 22
0
 def _connect(self):
     # each instance of ClxDriver can open connection to only 1 host
     # subsequent calls to open() are quietly ignored, and close()
     # does not take any args, so one host per block instance for now
     self.cnxn = ClxDriver()
     self.cnxn.open(self.host())
class CLXReadTag(EnrichSignals, Retry, Block):

    host = StringProperty(title='Host Address', order=0)
    tags = Property(title='Tags', order=1)
    version = VersionProperty('0.2.0')

    def __init__(self):
        super().__init__()
        self.cnxn = None

    def before_retry(self, *args, **kwargs):
        self._disconnect()
        self._connect()

    def configure(self, context):
        super().configure(context)
        try:
            self._connect()
        except Exception:
            self.cnxn = None
            msg = 'Unable to connect to {}'.format(self.host())
            self.logger.exception(msg)

    def stop(self):
        super().stop()
        self._disconnect()

    def process_signals(self, signals):
        host = self.host()
        output_signals = []
        if self.cnxn is None:
            try:
                msg = 'Not connected to {}, reconnecting...'.format(host)
                self.logger.warning(msg)
                self._connect()
            except Exception:
                self.cnxn = None
                msg = 'Unable to connect to {}'.format(host)
                self.logger.exception(msg)
                return
        for signal in signals:
            tag = self.tags(signal)
            try:
                value = self.execute_with_retry(self._make_request, tag)
            except Exception:
                value = False
                self.cnxn = None
                msg = 'read_tag failed, host: {}, tag: {}'
                self.logger.exception(msg.format(host, tag))
                continue
            if not isinstance(value[0], tuple):
                # read_tag only includes the tag name in the return value
                # when reading a list of tags, so we include it here
                value = (tag, ) + value
            new_signal_dict = {'host': host, 'value': value}
            new_signal = self.get_output_signal(new_signal_dict, signal)
            output_signals.append(new_signal)

        self.notify_signals(output_signals)

    def _connect(self):
        # each instance of ClxDriver can open connection to only 1 host
        # subsequent calls to open() are quietly ignored, and close()
        # does not take any args, so one host per block instance for now
        self.cnxn = ClxDriver()
        self.cnxn.open(self.host())

    def _disconnect(self):
        if self.cnxn is not None:
            self.cnxn.close()
            self.cnxn = None

    def _make_request(self, tag):
        return self.cnxn.read_tag(tag)
def PI_PLC(Head_Angle_Current):
    PLC = ClxDriver()

    print("Opening Connection To PLC...")
    if PLC.open('192.168.1.150'):
        print("*********************************")
        PLC_Known_Head_Angle, _ = PLC.read_tag(
            "R_PI_User_Head_Angle"
        )  # Read the current head angle the PLC knows of
        print("PLC_Known_Head_Angle: " + str(PLC_Known_Head_Angle)
              )  # Print the current head angle the PLC knows of
        print("Head_Angle_Current: " + str(Head_Angle_Current)
              )  # Print the head angle passed into this argument
        PLC.write_tag('R_PI_User_Head_Angle', Head_Angle_Current,
                      'INT')  # Tell the PLC the new angle
        PLC.write_tag(
            'R_PI_Comm_Check', random.randint(-25, 25), 'INT'
        )  # Send a random value to the PLC to make sure data is received
        PLC_Known_Head_Angle, _ = PLC.read_tag(
            "R_PI_User_Head_Angle")  # Read the new angle
        print("NEW PLC_Known_Head_Angle: " + str(PLC_Known_Head_Angle)
              )  # Print the current head angle the PLC knows of
        # Make sure the PLC Read the new angle
        if Head_Angle_Current != PLC_Known_Head_Angle:
            print("FAULT: PI -> PLC TRANSMISSION FAILED!!!")

        print("Closing Connection...")
        print("********************************* \n")
        PLC.close()

    PLC.close()
Exemplo n.º 25
0
from pycomm.ab_comm.clx import Driver as ClxDriver
import logging

from time import sleep

if __name__ == '__main__':

    logging.basicConfig(
        filename="ClxDriver.log",
        format= "%(levelname)s %(asctime)s",
        # format="%(levelname)s %(asctime)s %(message)s %(filename)s",
        level=logging.DEBUG
    )
    c = ClxDriver()

    print (c['port'])
    print (c.__version__)


    if c.open('192.168.0.203'):
        while 1:
            try:
                print(c.read_tag(['TESTTAG']))

                print(c.write_tag('TESTTAG', 30, 'DINT'))
            
                sleep(1)
            except Exception as e:
                c.close()
                print (e)
                pass
Exemplo n.º 26
0
def write_plc(ipaddress: str, tag_name: str, data_type: str, tag_value):
    result = None

    c = ClxDriver()
    try:
        c.open(ipaddress)
        is_open = True
    except:
        is_open = False
        return False
    if is_open:

        # Verify tag value matches data type.#
        
        if(data_type == "DINT"):
            try:
                result = int(tag_value)
            except:
                c.close()
                return False
        elif(data_type == "REAL"):
            try:
                result = float(tag_value)
            except:
                c.close()
                return False
        else:
            c.close()
            return False

        # write value to tag #
        if result != None:
            c.write_tag(tag_name, result, data_type)
            c.close()
            return True

        c.close()
        return False

    else:
        print("Could not interface with PLC at this IP Address.")
        return False
Exemplo n.º 27
0
    # Set Speeds
    print("Speed: ", 50, c.write_tag(('jog_ST_Speed', 50, 'REAL')))
    print("Speed: ", 50, c.write_tag(('ST_Speed', 50, 'REAL')))
    print("Speed: ", 50, c.write_tag(('time_ST_Speed', 50, 'REAL')))
    #if home is 1 set to 0
    _resp = c.read_tag(['Set_Home'])
    if _resp[0][1] == 1:
        print("Setting Home: ", c.write_tag(('Set_Home', 0, 'BOOL')))
    print("Gear Ratio:", c.write_tag('Gear_Ratio', 0.9793333, 'REAL'))


if __name__ == '__main__':
    logging.basicConfig(filename="ClxDriver.log",
                        format="%(levelname)-10s %(asctime)s %(message)s",
                        level=logging.DEBUG)
    c = ClxDriver()

    print("connecting to driver...", )
    if c.open('192.168.1.5'):
        print("success!", )
        print("Reseting")
        reset()
        # Get position
        print("Angle: ", c.read_tag(['FB_Position']))
        # Set to home
        #print("Setting Home: ", c.write_tag(('Set_Home', 1, 'BOOL')))
        #print("Setting Home: ", c.write_tag(('Set_Home', 0, 'BOOL')))
        # Confirm position
        print("New Angle: ", c.read_tag(['FB_Position']))
        # Fault Active
        _resp = c.read_tag(['Fault_Active'])
Exemplo n.º 28
0
    # Set Direction to Clockwise
    # 1-clockwise,  2-counterclockwise,   3-shortestpath to a position
    print("Direction:", c.write_tag('Direction_Mode', 2, 'INT'))
    # Set Speeds
    print("Speed: ", 50, c.write_tag(('jog_ST_Speed', 35, 'REAL')))
    print("Speed: ", 50, c.write_tag(('ST_Speed', 50, 'REAL')))
    print("Speed: ", 50, c.write_tag(('time_ST_Speed', 50, 'REAL')))
    print("Gear Ratio:", c.write_tag('Gear_Ratio', 0.9793333, 'REAL'))


if __name__ == '__main__':
    logging.basicConfig(filename="ClxDriver.log",
                        format="%(levelname)-10s %(asctime)s %(message)s",
                        level=logging.DEBUG)
    c = ClxDriver()

    print("connecting to driver...", )
    if c.open('192.168.1.5'):
        print("success!", )
        print("Reseting")
        reset()
        # Get position
        print("Angle: ", c.read_tag(['FB_Position']))
        # Fault Active
        _resp = c.read_tag(['Fault_Active'])
        if _resp[0][1] == 0:
            # # Set the speed
            # valid_resps = [1, 2, 3]
            # usr_input = int(raw_input("What direction?: "))
            # while usr_input not in valid_resps:
Exemplo n.º 29
0
 def __init__(self):
     super().__init__()
     self.cnxn = ClxDriver()
Exemplo n.º 30
0
from pycomm.ab_comm.clx import Driver as ClxDriver


if __name__ == '__main__':

    c = ClxDriver(True, 'ClxDriver.log')

    if c.open('172.16.2.161'):

        print(c.read_tag(['ControlWord']))
        print(c.read_tag(['parts', 'ControlWord', 'Counts']))

        print(c.write_tag('Counts', -26, 'INT'))
        print(c.write_tag(('Counts', 26, 'INT')))
        print(c.write_tag([('Counts', 26, 'INT')]))
        print(c.write_tag([('Counts', -26, 'INT'), ('ControlWord', -30, 'DINT'), ('parts', 31, 'DINT')]))

        # To read an array
        r_array = c.read_array("TotalCount", 1750)
        for tag in r_array:
            print (tag)

        # reset tha array to all 0
        w_array = []
        for i in xrange(1750):
            w_array.append(0)
        c.write_array("TotalCount", "SINT", w_array)

        c.close()
Exemplo n.º 31
0
class CLXWriteTag(EnrichSignals, Retry, Block):

    host = StringProperty(title='Host Address')
    tags = Property(title='Tags')
    version = VersionProperty('0.1.2')

    def __init__(self):
        super().__init__()
        self.cnxn = ClxDriver()

    def before_retry(self, *args, **kwargs):
        self._disconnect()
        self._connect()

    def configure(self, context):
        super().configure(context)
        try:
            self._connect()
        except Exception:
            self.cnxn = None
            msg = 'Unable to connect to {}'.format(self.host())
            self.logger.exception(msg)

    def stop(self):
        super().stop()
        self._disconnect()

    def process_signals(self, signals):
        host = self.host()
        output_signals = []
        if self.cnxn is None:
            try:
                msg = 'Not connected to {}, reconnecting...'.format(host)
                self.logger.warning(msg)
                self._connect()
            except Exception:
                self.cnxn = None
                msg = 'Unable to connect to {}'.format(host)
                self.logger.exception(msg)
                return
        for signal in signals:
            tag_list = self.tags(signal)
            self._validate_tags(tag_list)
            try:
                response = self.execute_with_retry(self._make_request,
                                                   tag_list)
            except Exception:
                response = False
                self.cnxn = None
                msg = 'write_tag failed, host: {}, tags: {}'
                self.logger.exception(msg.format(host, tag_list))
                continue
            new_signal_dict = self._parse_response(response)
            new_signal_dict['host'] = host
            new_signal = self.get_output_signal(new_signal_dict, signal)
            output_signals.append(new_signal)
        self.notify_signals(output_signals)

    def _abort(self):
        raise TypeError(
            'Tags to write must be given as a tuple of (name, value, type)')

    def _connect(self):
        # each instance of ClxDriver can open connection to only 1 host
        # subsequent calls to open() are quietly ignored, and close()
        # does not take any args, so one host per block instance for now
        self.cnxn = ClxDriver()
        self.cnxn.open(self.host())

    def _disconnect(self):
        if self.cnxn is not None:
            self.cnxn.close()
            self.cnxn = None

    def _make_request(self, tag_list):
        return self.cnxn.write_tag(tag_list)

    def _parse_response(self, response):
        if isinstance(response, list):
            # when writing multiple tags write_tag returns a list of
            # tuples (name, value, type, "GOOD"|"BAD")
            success = []
            for resp in response:
                success.append(resp[3] == "GOOD")
        else:
            success = response
        return {'success': success}

    def _validate_tags(self, tag_list):
        if isinstance(tag_list, list):
            for tag in tag_list:
                if not isinstance(tag, tuple):
                    self._abort()
        else:
            if not isinstance(tag_list, tuple):
                self._abort()
Exemplo n.º 32
0
    # disable alrt
    print("Disable Relative: ", c.write_tag('Alt_Start_Req', 0, 'BOOL'))
    # Set Direction to Clockwise
    # 2-counter-clockwise,  1-clockwise,   3-shortestpath to a position
    print("Direction:", c.write_tag('Direction_Mode', 2, 'INT'))
    # Set Speeds
    print("Speed: ", 50, c.write_tag(('jog_ST_Speed', 50, 'REAL')))
    print("Speed: ", 50, c.write_tag(('ST_Speed', 50, 'REAL')))
    print("Speed: ", 50, c.write_tag(('time_ST_Speed', 50, 'REAL')))


if __name__ == '__main__':
    logging.basicConfig(filename="ClxDriver.log",
                        format="%(levelname)-10s %(asctime)s %(message)s",
                        level=logging.DEBUG)
    c = ClxDriver()

    print("connecting to driver...", )
    if c.open('192.168.1.5'):
        reset()
        # Get position

        while True:
            start_time = datetime.now()
            position = (c.read_tag(['FB_Position']))
            position_angle = position[0][1]

            stop_time = datetime.now()

            print("angle = ", position_angle, (stop_time - start_time))