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()
예제 #2
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)
예제 #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)
예제 #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)
예제 #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)
예제 #6
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()
예제 #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)
예제 #8
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)
예제 #9
0
파일: plc.py 프로젝트: thebagmaster/plc.py
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()
예제 #10
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()
예제 #11
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()
예제 #12
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()
예제 #13
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
예제 #14
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
예제 #15
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()
예제 #16
0
        # 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'])
        if _resp[0][1] == 0:
            # Set the speed
            print("Speed: ", spd, c.write_tag(('ST_Speed', spd, 'REAL')))
            print("Direction:", c.write_tag('Direction_Mode', 2, 'INT'))
            # Toggle the relative start requested
            rel_deg = float(raw_input("Move by __ Relative degree?: "))
            #print(c.write_tag('Rel_Deg', rel_deg, 'REAL'))
            print(c.write_tag('Rel_Deg', rel_deg, 'REAL'))
            print(c.write_tag('R_Start_Req', 1, 'BOOL'))
            print("New Angle: ", c.read_tag(['FB_Position']))
            #print(c.write_tag('R_Start_Req', 0, 'BOOL'))
            #print("Stop  Motion", c.write_tag('Stop_Motion', 1, 'BOOL'))
            #print("Stop  Motion", c.write_tag('Stop_Motion', 0, 'BOOL'))
            #print("Direction:", c.write_tag('Direction_Mode', 1, 'INT'))
            # Set Direction
            # 2-clockwise,  1-counterclockwise,   3-shortestpath to a position
            #print("Direction:", c.write_tag('Direction_Mode', 2, 'INT'))
            #print(c.write_tag('Rel_Deg', 34, 'DINT'))
            #time.sleep(20)

    # close the connection
    c.close()
    print("Closed the connection")
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)
예제 #18
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
예제 #19
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()
예제 #20
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()