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 __init__(self, plc='clx', ip='0.0.0.0'):
     if plc == 'clx':
         self.driver = ClxDriver()
     if plc == 'slc':
         self.driver = SlcDriver()
     self.ip = ip
     self.open()
Пример #3
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()
Пример #4
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)
Пример #5
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)
Пример #6
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)
Пример #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)
Пример #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)
Пример #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
Пример #10
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
Пример #11
0
def main():
global c
c = ClxDriver()
update()

def update():
    global c
    try:
        if c.open('192.168.1.95'):
        #print(c.read_tag(['SimulatedDT_Remaining'])[0][1])
            f_array = c.read_array("line1.FaultCode", 1500)
            t_array = c.read_array("line1.TimeStamp", 1500)
            d_array = c.read_array("line1.Duration", 1500)
            p_array = c.read_array("line1.ProductCount", 1500)
            c.close()
            
            
            conn = pyodbc.connect(r'Driver={SQL Server};Server=nth-server-12\SQLEXPRESS;Database=nth;Trusted_Connection=yes;')
            conn.autocommit = True
            cursor = conn.cursor()
            cursor.executemany(
                "BEGIN TRY INSERT INTO line1 VALUES (?, ?, ?, ?) END TRY BEGIN CATCH END CATCH",
                zip(zip(*t_array)[1],zip(*f_array)[1],zip(*d_array)[1],zip(*p_array)[1]))
            
            cursor.close()
            conn.close()
            global cycles
            cycles+=1
            print(cycles)
    except:
        pass
    threading.Timer(10, update).start()
    return

if __name__ == '__main__':
    main()
Пример #12
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())
Пример #13
0
 def __init__(self):
     super().__init__()
     self.cnxn = ClxDriver()
Пример #14
0
# some global variables for the PLC Thread
plc_ip_address = '192.168.1.5'
# accuracy desired in degree
accuracy_desired = 0.1
#table precision, set it to a value lower than accuracy_desired
table_precision = 0.01
message_json = None
command = None

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

# initialize the communication driver
# this is a global variable that will only be used from the second thread.
c = ClxDriver()

# used to track the last index reached in the table motion vector
curr_index = -1


def reset():
    '''
        This is called by one of the motion options in the PLC thread.
        :. It must already by opened when the function is called.
    '''
    #print("Driver Reset: ", c.write_tag(
    #    'Drive_1_Command.RESET', 1, 'BOOL'))
    #print("Driver Reset: ", c.write_tag(
    #    'Drive_1_Command.RESET', 0, 'BOOL'))
    # Stop automatic motion
Пример #15
0
 def __init__(self):
     # initialize a thread safe queue
     # load queue with a single plc obj
     self.plc = ClxDriver()
     self.mutex = Lock()
Пример #16
0
                        1] = Avg_Sum[Avg_Count]  # Shift each one up a spot
            Avg_Sum[0] = Angle  # Store value in array
            Avg = round(
                np.average(Avg_Sum,
                           axis=None,
                           weights=Avg_Sum_WT,
                           returned=False))
            print("Avg: {}".format(Avg))
            # Check and see if face exceeded limits to reduce noise and jitter
            if (
                ((TX_Prev - Avg_Threshold) < Avg < (TX_Prev + Avg_Threshold))
            ):  # If the new location is not within the range dont update robot.
                print("Not a big enough change")
            else:
                TX_Angle = Angle
                print("TX_Angle")
                print(TX_Angle)
                SD_Huber_Tag_Handle_20190116.PI_PLC(int(TX_Angle))
                TX_Prev = TX_Angle  # Previous angle sent

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break


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

    main()