Esempio n. 1
0
def door_active(door):

    # Check verify_trailers table for active route
    routes = "SELECT route FROM wcs.verify_trailers WHERE door_id=" + str(door)
    cursor.execute(routes)
    result = cursor.fetchall()
    routes = []
    if len(result) > 0:
        for r in result:
            routes.append(r[0])
        #print(routes)

        doorActive = False
        for route in routes:
            #print("")
            #print(route)

            pre_verify = "SELECT pre_verify FROM wcs.verify_trailers WHERE route=" + str(
                route)
            cursor.execute(pre_verify)
            result = cursor.fetchone()
            pre_verify = result[0]
            #print(pre_verify)

            status = "SELECT status FROM wcs.verify_trailers WHERE route=" + str(
                route)
            cursor.execute(status)
            result = cursor.fetchone()
            status = result[0]
            #print(status)

            if pre_verify == 1 and status != "Shipped":
                doorActive = True
                break
            else:
                doorActive = False
    else:
        doorActive = False

    #print(doorActive)
    if doorActive == True:
        with PLC() as comm:
            comm.IPAddress = plcIP
            comm.Write("wxsDoor" + str(door) + "Control", 1)

    elif doorActive != True:
        with PLC() as comm:
            comm.IPAddress = plcIP
            comm.Write("wxsDoor" + str(door) + "Control", 0)

    ret = comm.Read("wxsDoor" + str(door) + "Control", datatype=INT)
    #print(ret.Value)
    comm.Close()

    if doorActive == True:
        return "Door " + str(door) + " is Active"
    elif doorActive != True:
        return "Door " + str(door) + " is Inactive"
Esempio n. 2
0
def discoverDevices():
    try:
        lbDevices.delete(0, 'end')

        commDD = PLC()

        devices = commDD.Discover()

        if str(devices) == 'None [] Success':
            lbDevices.insert(1, 'No Devices Discovered')
        else:
            i = 0
            for device in devices.Value:
                lbDevices.insert(i * 12 + 1, 'IP Address: ' + device.IPAddress)
                lbDevices.insert(i * 12 + 2, 'Product Name: ' + device.ProductName)
                lbDevices.insert(i * 12 + 3, 'Product Code: ' + str(device.ProductCode))
                lbDevices.insert(i * 12 + 4, 'Vendor: ' + device.Vendor)
                lbDevices.insert(i * 12 + 5, 'Vendor ID: ' + str(device.VendorID))
                lbDevices.insert(i * 12 + 6, 'Device Type: ' + str(device.DeviceType))
                lbDevices.insert(i * 12 + 7, 'Device ID: ' + str(device.DeviceID))
                lbDevices.insert(i * 12 + 8, 'Revision: ' +  device.Revision)
                lbDevices.insert(i * 12 + 9, 'Serial: ' + str(int(device.SerialNumber, 0)))
                lbDevices.insert(i * 12 + 10, 'State: ' + str(device.State))
                lbDevices.insert(i * 12 + 11, 'Status: ' + str(device.Status))
                lbDevices.insert(i * 12 + 12, '----------------------------------')
                i += 1

            for device in devices.Value:
                if device.DeviceID == 14:
                    lbDevices.insert(i * 12 + 1, 'Modules at ' + device.IPAddress)

                    '''
                    Query each slot for a module
                    '''
                    with PLC() as c:
                        c.IPAddress = device.IPAddress

                        for j in range(17):
                            x = c.GetModuleProperties(j)
                            lbDevices.insert(i * 12 + 2 + j, 'Slot ' + str(j) + ' ' + x.Value.ProductName + ' rev: ' + x.Value.Revision)

                    c.Close()
                    c = None

                    i += 1

        commDD.Close()
        commDD = None
    except Exception as e:
        if not commDD is None:
            commDD.Close()
            commDD = None

        if app_closing:
            pass
        else:
            print(str(e))
Esempio n. 3
0
def get_production(tag_prefix):

    with PLC() as comm:
        comm.IPAddress = '192.168.1.2'
        comm.ProcessorSlot = 2

        hourly = []
        totals = []
        for shift in range(3):
            shift_counts = []
            for hour in range(8):
                tag_name = tag_prefix + 'Shift_' + \
                    str(shift+1) + '_Hour_' + str(hour+1) + '_Total'
                # print(tag_name)
                ret = comm.Read(tag_name)
                # print(ret.TagName, ret.Value, ret.Status)
                if ret.Status == 'Success':
                    shift_counts.append(ret.Value)
                else:
                    shift_counts.append('Error')

            hourly.append(shift_counts)

            tag_name = tag_prefix + 'Shift_' + str(shift + 1) + '_Total'
            ret = comm.Read(tag_name)
            # print(ret.TagName, ret.Value, ret.Status)
            if ret.Status == 'Success':
                totals.append(ret.Value)
            else:
                totals.append('Error')
    return (hourly, totals)
Esempio n. 4
0
def main():
    '''
    Create our window and comm driver
    '''
    global root
    global comm
    global ProductionCount

    # create a comm driver
    comm = PLC()
    comm.IPAddress = ipAddress

    # create a tkinter window
    root = Tk()
    root.config(background='black')
    root.title = 'Production Count'
    root.geometry('800x600')

    # bind the "q" key to quit
    root.bind('q', lambda event: root.destroy())

    # create a labe to display our variable
    ProductionCount = Label(root,
                            text='n',
                            fg='white',
                            bg='black',
                            font='Helvetica 350 bold')
    ProductionCount.place(anchor=CENTER, relx=0.5, rely=0.5)

    # call our updater and show our window
    root.after(1000, UpdateValue)
    root.mainloop()
    comm.Close()
Esempio n. 5
0
def Scan(host):
    plc_ip = host
    with PLC() as comm:
        comm.IPAddress = plc_ip
        prop = comm.GetModuleProperties(0)
        if prop.Value.ProductName:
            PLC_id_file.write("AB" + " | " + plc_ip + " | " + prop.Value.Vendor + " " + prop.Value.ProductName + '\n')
        print prop.Value.ProductName, prop.Value.Revision
Esempio n. 6
0
def Emergency():
    comm = PLC()
    comm.IPAddress = '169.254.215.82'
    comm.Write('EmergencyPB', False)
    time.sleep(.250)
    comm.Write('EmergencyPB', True)
    comm.Close()
    return
Esempio n. 7
0
def SeqResume():
    comm = PLC()
    comm.IPAddress = '169.254.215.82'
    comm.Write('SEQResume', False)
    time.sleep(.3)
    comm.Write('SEQResume', True)
    comm.Close()
    return
Esempio n. 8
0
def PauseSEQ():
    comm = PLC()
    comm.IPAddress = '169.254.215.82'
    comm.Write('SEQPause', True)
    time.sleep(.25)
    comm.Write('SEQPause', False)
    comm.Close()
    return
Esempio n. 9
0
def StartSEQ():
    comm = PLC()
    comm.IPAddress = '169.254.215.82'
    comm.Write('StartSeq', True)
    time.sleep(.3)
    comm.Write('StartSeq', False)
    comm.Close()
    return
Esempio n. 10
0
def MasterOn():
    comm = PLC()
    comm.IPAddress = '169.254.215.82'
    comm.Write('MasterStart', True)
    time.sleep(.25)
    comm.Write('MasterStart', False)
    comm.Close()
    return
Esempio n. 11
0
def comm_check():
    global comm
    global updateRunning
    global connected
    global connectionInProgress

    try:
        connectionInProgress = True
        ip = selectedIPAddress.get()
        port = int(selectedProcessorSlot.get())

        if (not connected or comm.IPAddress != ip or comm.ProcessorSlot != port or changePLC.get() == 1):
            if not comm is None:
                comm.Close()
                comm = None

            comm = PLC()
            comm.IPAddress = ip

            if checkVarMicro800.get() == 0:
                comm.ProcessorSlot = port
                comm.Micro800 = False
            else:
                comm.Micro800 = True

            plcTime = comm.GetPLCTime()

            lbConnectionMessage.delete(0, 'end')
            lbErrorMessage.delete(0, 'end')

            if plcTime.Value is None:
                if btnStop['state'] == 'disabled':
                    btnStart['state'] = 'disabled'
                    btnStart['bg'] = 'lightgrey'
                lbConnectionMessage.insert(1, ' Not Connected')
                lbErrorMessage.insert(1, ' ' + plcTime.Status)
                connected = False
                root.after(5000, start_connection)
            else:
                lbConnectionMessage.insert(1, ' Connected')
                if not updateRunning:
                    updateRunning = True

                connected = True
                connectionInProgress = False

                if btnStop['state'] == 'disabled':
                    btnStart['state'] = 'normal'
                    btnStart['bg'] = 'lightgreen'
                else:
                    start_update()

        changePLC.set(0)
    except Exception as e:
        if app_closing:
            pass
        else:
            print(str(e))
Esempio n. 12
0
def WriteSEQCount():
    comm = PLC()
    comm.IPAddress = '169.254.215.82'
    seqcount = entry1.get()
    seqcount = int(seqcount)
    comm.Write('SEQCount', seqcount)
    time.sleep(.22)
    comm.Close()
    return
Esempio n. 13
0
def get_tag_list(ip, slot=0):
    from pylogix import PLC

    with PLC() as comm:
        comm.IPAddress = ip
        comm.ProcessorSlot = slot
        tags = comm.GetTagList()

    for t in tags.Value:
        print(t.TagName, t.DataType)
    def run(self):
        self.running = True
        with PLC() as plc:
            plc.IPAddress = global_parameters['PLC_IP']
            current_time = self.time_Q.get()
            counter = 0

            while True:
                if self.stopped:
                    return

                if current_time < time.time() and current_time > 0:
                    if counter == 0:
                        s = time.time()
                        print("Sending instructions to PLC...")
                    counter += 1
                    if not self.instruction_Q.empty():
                        instruction = self.instruction_Q.get()
                        to_send = np.around(instruction, 2)

                        ### PLC write instruction ###
                        print(instruction)
                        # plc.Write("<tag0>", value=instruction[0])
                        # plc.Write("<tag1>", value=instruction[1])
                        # plc.Write("<tag2>", value=instruction[2])
                        # plc.Write("<tag3>", value=instruction[3])
                        # plc.Write("<tag4>", value=instruction[4])
                        # plc.Write("<tag5>", value=instruction[5])
                        # plc.Write("<tag6>", value=instruction[6])
                        # plc.Write("<tag7>", value=instruction[7])
                        #############################

                        current_time = self.time_Q.get()
                    else:
                        print("ERROR: Instruction size mismatch.")

                elif current_time == 0 and counter != 0:

                    # Send a stop order to stop all motion
                    # plc.Write("<tag0>", value=instruction[0])
                    # plc.Write("<tag1>", value=instruction[1])
                    # plc.Write("<tag2>", value=instruction[2])
                    # plc.Write("<tag3>", value=instruction[3])
                    # plc.Write("<tag4>", value=instruction[4])
                    # plc.Write("<tag5>", value=instruction[5])
                    # plc.Write("<tag6>", value=instruction[6])
                    # plc.Write("<tag7>", value=instruction[7])

                    counter = 0
                    print("Instruction completed. \nExecution time:",
                          round(time.time() - s, 2), "s\n")
                    current_time = self.time_Q.get(
                    )  # get is a locking function so it stays here until the next instruction comes in
                    self.instruction_Q.get()  # Clears out the 0 instruction
Esempio n. 15
0
def audit_rack(plc):
    '''
    Query each slot for a module
    '''
    with PLC() as c:
        c.IPAddress = plc.IPAddress
        f.write('%s - %s\n' % (plc.IPAddress, plc.ProductName))
        for i in range(17):
            x = c.GetModuleProperties(i)
            f.write('\tSlot %d:%s  rev:%s\n' % (i, x.ProductName, x.Revision))
        f.write('')
Esempio n. 16
0
def comm_check():
    global comm

    ip = selectedIPAddress.get()
    port = int(selectedProcessorSlot.get())

    if (comm.IPAddress != ip or comm.ProcessorSlot != port):
        comm.Close()
        comm = None
        comm = PLC()
        comm.IPAddress = ip
        comm.ProcessorSlot = port
Esempio n. 17
0
def poll_ribbon_switch(door):
    with PLC() as comm:
        comm.IPAddress = plcIP
        ret = comm.Read("wxsDoor" + str(door) + "RibbonSwitch", datatype=BOOL)
        switch = ret.Value

        if switch == True:

            delete = modal.delete(door)

            if delete == "Done":
                comm.Write("wxsDoor" + str(door) + "RibbonSwitch", False)
Esempio n. 18
0
def loop(taglist, ip, slot=0, minimum_cycle=.5):
    with PLC() as comm:
        comm.IPAddress = ip
        comm.ProcessorSlot = slot

        for entry in taglist:

            # get current timestamp
            now = time.time()

            frequency = entry['frequency']

            # make sure we are not polling too fast
            if frequency < minimum_cycle:
                frequency = minimum_cycle

            # handle first pass through
            if entry['nextread'] == 0:
                entry['nextread'] = now

            if entry['nextread'] > now:
                continue  # too soon move on

            entry['lastread'] = now

            if entry['type'] == 'counter':
                with PLC() as comm:
                    comm.IPAddress = ip
                    comm.ProcessorSlot = slot
                    read_counter(entry, comm)

            if entry['type'] == 'value':
                with PLC() as comm:
                    comm.IPAddress = ip
                    comm.ProcessorSlot = slot
                    read_value(entry, comm)

            # set the next read timestamp
            entry['nextread'] += frequency
Esempio n. 19
0
def get_rabbit_bypass(prefix):
    """ Gets a red rabbit's bypass status. Return 0, 1 and datetime, or -1)"""
    with PLC() as comm:
        comm.IPAddress = '192.168.1.2'
        comm.ProcessorSlot = 2
        res = comm.Read(prefix + '.Bypassed')
        if res.Status == 'Success':
            if res.Value:
                return res.Value, get_date_time(prefix + '.Date_Time')
            else:
                return res.Value, None
        else:
            return -1, None
Esempio n. 20
0
def get_all_tags(ipAddress, slot):
    tags = []

    comm = PLC(ipAddress, slot)
    ret = comm.GetTagList()
    comm.Close()

    if ret.Value is None:
        return jsonify(ret.Status)

    for tag in ret.Value:
        tags.append({"tagName": tag.TagName, "dataType": tag.DataType})

    return jsonify({'tags': tags})
Esempio n. 21
0
def get_date_time(tag_prefix):
    """ Returns a datetime object from a collection of tags """
    with PLC() as comm:
        comm.IPAddress = '192.168.1.2'
        comm.ProcessorSlot = 3

        tag_list = [
            tag_prefix + '.Year', tag_prefix + '.Month', tag_prefix + '.Day',
            tag_prefix + '.Hour', tag_prefix + '.Min', tag_prefix + '.Sec'
        ]

        x = list(map(test_response, comm.Read(tag_list)))
        if -1 not in x:
            return datetime(*x)
Esempio n. 22
0
def rockwells():
    with PLC() as comm:
        # 设备扫描
        deviceip = []
        devicename = []
        devices = comm.Discover()
        for device in devices.Value:
            deviceip.append(device.IPAddress)
            devicename.append(device.ProductName + ' ' + device.IPAddress)
        global rockwell_device_list
        rockwell_device_list = dict(zip(devicename, deviceip))  # 创建设备字典 写入全局变量
        scanresult = "扫描到" + str(len(rockwell_device_list)) + "台设备"
        print(scanresult)
        flash(scanresult, "scanresult")  #扫描完成flash提示
        return redirect("rockwellscan")
Esempio n. 23
0
def readString(tag):
    with PLC() as comm:
        comm.IPAddress = '10.4.42.135'
        comm.ProcessorSlot = 3
        length = comm.Read('{}.LEN'.format(tag))
        if not (length.Status == 'Success'):
            return length
        if not length.Value:
            return None

        ret = comm.Read(tag + '.DATA', length.Value)
        if ret.Status == 'Success':
            return ''.join(chr(i) for i in ret.Value)
        else:
            return ret
Esempio n. 24
0
def read_pylogix_counter(counter_entry):
    with PLC() as comm:
        comm.IPAddress = counter_entry['processor_ip']
        comm.ProcessorSlot = counter_entry['processor_slot']

        tag = counter_entry['tag']
        part_count = comm.Read(tag)

        if part_count.Status != 'Success':
            logger.error(f'Failed to read: {part_count} : {tag}')
            return -1

        logger.debug(
            f'Read pylogix counter:{part_count}, tag:{counter_entry["tag"]}')

    return part_count.Value
Esempio n. 25
0
def get_devices(ipAddress, slot):
    devices = []

    comm = PLC(ipAddress, slot)
    ret = comm.Discover()
    comm.Close()

    if ret.Value == []:
        return jsonify('No Devices Discovered')

    for device in ret.Value:
        devices.append({
            "productName": device.ProductName,
            "revision": device.Revision
        })

    return jsonify({'devices': devices})
Esempio n. 26
0
def getTags():
    try:
        lbTags.delete(0, 'end')

        commGT = PLC()
        commGT.IPAddress = selectedIPAddress.get()
        if checkVarMicro800.get() == 0:
            commGT.ProcessorSlot = int(selectedProcessorSlot.get())

        tags = commGT.GetTagList()

        if not tags is None:
            if not tags.Value is None:
                # save tags to a file
                if checkVarSaveTags.get() == 1:
                    with open('tags_list.txt', 'w') as f:
                        for t in tags.Value:
                            if t.DataType == '':
                                f.write(t.TagName + '\n')
                            else:
                                f.write(t.TagName + ' (DataType - ' + t.DataType + ')\n')

                for t in tags.Value:
                    j = 1
                    if t.DataType == '':
                        lbTags.insert(j, t.TagName)
                    else:
                        lbTags.insert(j, t.TagName + ' (DataType - ' + t.DataType + ')')
                    j = j + 1
            else:
                lbTags.insert(1, 'No Tags Retrieved')
        else:
            lbTags.insert(1, 'No Tags Retrieved')

        commGT.Close()
        commGT = None
    except Exception as e:
        if not commGT is None:
            commGT.Close()
            commGT = None

        if app_closing:
            pass
        else:
            print(str(e))
Esempio n. 27
0
 def closepop(self):
     global clx
     global ismicro
     global firstrun
     firstrun = True
     if ipset:
         clx = PLC(ip, 2)
         if ismicro:
             App.get_running_app(
             ).root.ids.iplabel.text = 'Connected ' + ip + ' Micro800'
         else:
             App.get_running_app(
             ).root.ids.iplabel.text = 'Connected ' + ip + ' Logix'
         clx.Micro800 = ismicro
         print(ismicro)
         Clock.schedule_interval(update, 0.25)
     else:
         print('Nop')
Esempio n. 28
0
def rockwell_get_all_vars():  #
    # print("111111111111111")
    with PLC() as comm:
        # print("111111111111")
        ####### 无法连续运行重复获取变量表? 连续点击不进入循环 直接下载附件?? 如果要刷新变量表需要再次“开始连接”##############
        print(rockwellip)
        if rockwellip == '':
            print("请先选择设备IP地址")
        else:
            print(rockwellip)
            comm.IPAddress = rockwellip  #全局变量
            # comm.IPAddress="192.168.100.200"
            print("2222222222")
            try:
                tags = comm.GetTagList()  #输出是Response结构体类型需要解析
                comm.Close()
            except Exception as e:
                print(e)
                #缺一个return ,读取错误的错误处理
            else:
                tagname = []
                tagtype = []
                head = ["TagName", "TagType"]
                for t in tags.Value:
                    tagname.append(t.TagName)
                    tagtype.append(t.DataType)
                taglist = pd.DataFrame({
                    'tagname': tagname,
                    'tagtype': tagtype
                })  #采用Pandas格式化
                # print(taglist)
                tt = datetime.datetime.now().strftime(
                    '%Y-%m-%d %H-%M-%S')  #时间标识符
                filepath = ("D:/Taglist " + tt + ".xlsx")
                print(filepath)
                ## 变量表文件暂存以备发送和自动读取
                taglist.to_excel(filepath,
                                 encoding='utf-8',
                                 index=False,
                                 header=head)  #写入excel
                ## 变量表文件下载
                return send_file(
                    filepath,
                    as_attachment=True)  #向前端发送文件 下载 比send_from_directory简化
Esempio n. 29
0
def discoverDevices():
    lbDevices.delete(0, 'end')

    devices = comm.Discover()

    if str(devices) == 'None [] Success':
        lbDevices.insert(1, 'No Devices Discovered')
    else:
        i = 0
        for device in devices.Value:
            lbDevices.insert(i * 12 + 1, 'IP Address: ' + device.IPAddress)
            lbDevices.insert(i * 12 + 2, 'Product Name: ' + device.ProductName)
            lbDevices.insert(i * 12 + 3,
                             'Product Code: ' + str(device.ProductCode))
            lbDevices.insert(i * 12 + 4, 'Vendor: ' + device.Vendor)
            lbDevices.insert(i * 12 + 5, 'Vendor ID: ' + str(device.VendorID))
            lbDevices.insert(i * 12 + 6,
                             'Device Type: ' + str(device.DeviceType))
            lbDevices.insert(i * 12 + 7, 'Device ID: ' + str(device.DeviceID))
            lbDevices.insert(i * 12 + 8, 'Revision: ' + device.Revision)
            lbDevices.insert(i * 12 + 9, 'Serial: ' + device.SerialNumber)
            lbDevices.insert(i * 12 + 10, 'State: ' + str(device.State))
            lbDevices.insert(i * 12 + 11, 'Status: ' + str(device.Status))
            lbDevices.insert(i * 12 + 12, '----------------------------------')
            i += 1

        for device in devices.Value:
            if device.DeviceID == 14:
                lbDevices.insert(i * 12 + 1, "Modules at " + device.IPAddress)
                '''
                Query each slot for a module
                '''
                with PLC() as c:
                    c.IPAddress = device.IPAddress

                    for j in range(17):
                        x = c.GetModuleProperties(j)
                        lbDevices.insert(
                            i * 12 + 2 + j, "Slot " + str(j) + " " +
                            x.Value.ProductName + " rev: " + x.Value.Revision)
                i += 1
Esempio n. 30
0
def timeTestforReadWrite():
    '''
    testing the time to read and write to the PLC
    '''
    from pylogix import PLC
    import time
    DiamondElements = PLC('192.168.1.10')  #AB PLC IP Address

    count = 0
    targetCycleCount = 1000

    startTime = time.time()
    """
    read the bool, write its opposite value, read it again.
    """
    while True:

        returnedValue = DiamondElements.Read('IO_NEEDED_HERE')

        print('Currently read value of ' + returnedValue.TagName + ': ' +
              str(returnedValue.Value))

        if returnedValue.Value == True:
            boolToWrite = 0
        else:
            boolToWrite = 1

        DiamondElements.Write('IO_NEEDED_HERE', boolToWrite)

        newReturnedValue = DiamondElements.Read('IO_NEEDED_HERE')

        print('New value after writing: ' + str(newReturnedValue.Value))

        if count >= targetCycleCount:
            break

        count += 1

    EndTime = time.time()
    totalTime = EndTime - startTime
    print(f"{totalTime:.4f} seconds with {targetCycleCount} read/write cycles")