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()
Example #2
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()
Example #3
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()
Example #4
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()
Example #5
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
Example #6
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()
Example #7
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)
Example #8
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)
Example #9
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)
Example #10
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
Example #11
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()
Example #12
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
Example #13
0
    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()
                print e
                pass

        # To read an array
        r_array = c.read_array("TotalCount", 1750)
        for tag in r_array:
Example #14
0
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

        c.close()
Example #15
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()
Example #16
0
        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:
            #     usr_input = int(raw_input("Please enter a valid response: "))
            # print("Speed: ", 100, c.write_tag('jog_ST_Speed', 35, 'REAL'))
            # time.sleep(1)  # second
            print(c.write_tag('Direction_Mode', 2, 'INT'))
            #print(c.write_tag(('J_Start_Req', 0, 'BOOL')))
            time.sleep(1)  # second
            print(c.write_tag(('J_Start_Req', 1, 'BOOL')))
        c.close()
        raw_input("Press any key to stop: ")
        if c.open('192.168.1.5'):
            print("stopping")
            print(c.write_tag(('J_Start_Req', 0, 'BOOL')))
            #print(c.write_tag(('J_Start_Req', 0, 'BOOL')))

            #time.sleep(1) # second
            # print(c.write_tag('Direction_Mode',1, 'INT'))
            #time.sleep(1) # second
            #print(c.write_tag(('J_Start_Req',1, 'BOOL')))
            #time.sleep(5) # second
Example #17
0
 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'])
     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'))
Example #18
0
    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
                pass

        # To read an array
        r_array = c.read_array("TotalCount", 1750)
        for tag in r_array:
            print (tag)
Example #19
0
    )
    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
            spd = float(raw_input("What speed?: "))
            print("Speed: ", spd, c.write_tag(('jog_ST_Speed', spd, 'REAL')))
            time.sleep(1)  # second
            print(c.write_tag('Direction_Mode', 2, 'INT'))
            time.sleep(1)  # second
            #print(c.write_tag(('J_Start_Req', 0, 'BOOL')))
            time.sleep(1)  # second
            print(c.write_tag(('J_Start_Req', 1, 'BOOL')))
            time.sleep(10)  # second
            #print(c.write_tag(('J_Start_Req', 0, 'BOOL')))

            #time.sleep(1) # second
            # print(c.write_tag('Direction_Mode',1, 'INT'))
            #time.sleep(1) # second
            #print(c.write_tag(('J_Start_Req',1, 'BOOL')))
            #time.sleep(5) # second
            #print(c.write_tag(('J_Start_Req',0, 'BOOL')))
Example #20
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()
Example #21
0
    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'])
        print('Fault Active  value issssssssssssssssss ', _resp)
        if _resp[0][1] == 0:
            # Set Direction
            # 2-clockwise,  1-counterclockwise,   3-shortestpath,to,a position
            print("Direction:", c.write_tag('Direction_Mode', 3, 'INT'))
            print("Speed: ", spd, c.write_tag(('ST_Speed', spd, 'REAL')))
            # Ask user for desired angle
            goTo = float(raw_input("What ANGLE do you want?: "))
            print(goTo, type(goTo))
            # Toggle low, then high
            print(c.write_tag('Goto_Deg', goTo, 'REAL'))
            print(c.write_tag('GT_Start_Req', 1, 'BOOL'))
            #print(c.write_tag('Goto_Deg', goTo, 'RE`AL'))
            #print(c.write_tag('Goto_Deg', 50, 'REAL'))
            #time.sleep(2)
            #print("Direction:", c.write_tag('Direction_Mode', 2, 'INT'))
            #for x in range(5):
            #    print(c.write_tag('Goto_Deg', goTo+x, 'REAL'))

        c.close()