routes.py 34.1 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873
from flask import jsonify,render_template
from app.api import bp
from config import Config
from pyecharts.charts import Bar,Line
from pyecharts.options.global_options import ThemeType
import pyecharts.options as opts
import pymongo
import pandas as pd
import pytz
import time
import json
from datetime import datetime,timedelta
import urllib.request
import operator
import re
import threading
import logging

agv_error = {}
is_start = True
bar_data = {}


def iso2timestamp(datestamp, format='%Y-%m-%d %H:%M:%S',timespec='seconds'):
    """
    ISO8601时间转换为时间戳

    :param datestring:iso时间字符串 2019-03-25T16:00:00.000Z,2019-03-25T16:00:00.000111Z
    :param format:%Y-%m-%dT%H:%M:%S.%fZ;其中%f 表示毫秒或者微秒
    :param timespec:返回时间戳最小单位 seconds 秒,milliseconds 毫秒,microseconds 微秒
    :return:时间戳 默认单位秒
    """
    datestring = datestamp.strftime("%Y-%m-%d %H:%M:%S")
    tz = pytz.timezone('Asia/Shanghai')
    utc_time = datetime.strptime(datestring, format)  # 将字符串读取为 时间 class datetime.datetime
    t = utc_time.replace(tzinfo=pytz.utc).astimezone(tz)
    last_time=t.strftime("%Y-%m-%d %H:%M:%S")
    # print (last_time)
    return last_time

def local2utc(local_st):
    """本地时间转UTC时间(-8: 00)"""
    time_struct = time.mktime(local_st.timetuple())
    utc_st = datetime.utcfromtimestamp(time_struct)
    return utc_st


def conn_mongo_datalog(start,end):
    mongo_client = pymongo.MongoClient(host='10.85.162.124', port=27017)
    # current_dbname=Config.DB_NAME
    # db = mongo_client[current_dbname]
    db = mongo_client['qisda']
    db.authenticate("admin", "123")
    cach = db.dataLog
    start_date = local2utc(start)
    end_date = local2utc(end)
    # start_date = datetime(2020,8,25,8,00,00)
    # end_date = datetime(2020,8,31,8,00,00)
    data=list(cach.find({"updateDate": {"$gte": start_date, "$lt": end_date}}))
    mongo_client.close()
    df = pd.DataFrame(data)
    return (df)

def process_datalog_hour(start,end):
    # now = datetime.now()
    # start=datetime.now() - timedelta(hours=24)
    # start = datetime(start.year, start.month, start.day, start.hour, start.minute, start.second)
    # end = datetime.now() + timedelta(hours=12)
    # end = datetime(end.year, end.month, end.day, end.hour, end.minute, end.second)
    df = conn_mongo_datalog(start,end)
    if not df.empty and 'posName' in df:
        df['updateDate'] = df['updateDate'].apply(iso2timestamp)
        temp_df_in = df[(df['type'] == 1) & (df['status'] != 'CANCEL') & (df['status'] != 'WAIT') & (df['posName'].notnull())]
        df_in = temp_df_in[['updateDate', 'status']]
        datalog_hour_in = df_in['updateDate'].groupby(df_in['updateDate'].map(lambda x: x[5:13])).count()
        hour_list_in = datalog_hour_in.index.to_list()
        count_list_in = datalog_hour_in.values.tolist()
        hour_list_in,count_list_in = check_hour_zero(start,end,hour_list_in,count_list_in)
        # check_hour_zero(start, now, hour_list_in, count_list_in)
        temp_df_out = df[(df['type'] == 2) & (df['status'] != 'CANCEL') & (df['status'] != 'WAIT') & (df['posName'].notnull())]
        df_out = temp_df_out[['updateDate', 'status']]
        datalog_hour_out = df_out['updateDate'].groupby(df_out['updateDate'].map(lambda x: x[5:13])).count()
        hour_list_out = datalog_hour_out.index.to_list()
        count_list_out = datalog_hour_out.values.tolist()
        hour_list_out, count_list_out = check_hour_zero(start, end, hour_list_out, count_list_out)
    else:
        hour_list_in = []
        count_list_in = []
        hour_list_out = []
        count_list_out = []
        hour_list_in,count_list_in = check_hour_zero(start,end,hour_list_in,count_list_in)
        hour_list_out,count_list_out = check_hour_zero(start,end,hour_list_out,count_list_out)
    data_dict = {
                'hour_list_in':hour_list_in,
                'count_list_in':count_list_in,
                'hour_list_out':hour_list_out,
                'count_list_out':count_list_out
    }
    return data_dict

def get_days_before_today(n=0):
    '''''
    date format = "YYYY-MM-DD HH:MM:SS"
    '''
    now = datetime.now()
    if(n<0):
        return datetime(now.year, now.month, now.day, now.hour, now.minute, now.second)
    else:
        n_days_before = now - timedelta(days=n)
        return datetime(n_days_before.year, n_days_before.month, n_days_before.day)

def process_datalog_day(n=5):#默认取前10天(含当天)
    day_count_list_in = []
    day_count_list_out = []
    while n >=0:
        start = get_days_before_today(n)
        start = datetime(start.year,start.month,start.day,8,0,0)
        # start = datetime(2020, 11, 27, 8, 0, 0)
        end = start + timedelta(days=1)
        df = conn_mongo_datalog(start, end)
        if not df.empty and 'posName' in df:
            # df['updateDate'] = df['updateDate'].apply(iso2timestamp)
            temp_df_in = df[(df['type'] == 1) & (df['status'] != 'CANCEL') & (df['status'] != 'WAIT') & (df['posName'].notnull())]
            temp_df_out = df[(df['type'] == 2) & (df['status'] != 'CANCEL') & (df['status'] != 'WAIT') & (df['posName'].notnull())]
            current_num_in = temp_df_in.shape[0]
            current_num_out = temp_df_out.shape[0]
            day_count_list_in.append(current_num_in)
            day_count_list_out.append(current_num_out)
        else:
            day_count_list_in.append(0)
            day_count_list_out.append(0)
        n -= 1
    add_start = end
    add_end = end + timedelta(days=1)
    df = conn_mongo_datalog(add_start, add_end)
    if not df.empty and 'posName' in df:
        # df['updateDate'] = df['updateDate'].apply(iso2timestamp)
        temp_df_in = df[(df['type'] == 1) & (df['status'] != 'CANCEL') & (df['status'] != 'WAIT') & (df['posName'].notnull())]
        temp_df_out = df[(df['type'] == 2) & (df['status'] != 'CANCEL') & (df['status'] != 'WAIT') & (df['posName'].notnull())]
        current_num_in = temp_df_in.shape[0]
        current_num_out = temp_df_out.shape[0]
        day_count_list_in.append(current_num_in)
        day_count_list_out.append(current_num_out)
    else:
        day_count_list_in.append(0)
        day_count_list_out.append(0)
    return (day_count_list_in,day_count_list_out)


def conn_mongo_outinfo(start,end):
    mongo_client = pymongo.MongoClient(host='10.85.162.124', port=27017)
    # current_dbname = Config.DB_NAME
    # db = mongo_client[current_dbname]
    db = mongo_client['qisda']
    db.authenticate("admin", "123")
    cach = db.outInfo
    start_date = local2utc(start)
    end_date = local2utc(end)
    # start_date = datetime(2020,8,25,8,00,00)
    # end_date = datetime(2020,8,31,8,00,00)
    data = list(cach.find({"taskNeedOutDate": {"$gte": start_date, "$lt": end_date}}))
    mongo_client.close()
    df = pd.DataFrame(data)
    return (df)

def process_outinfo_hour(start,end):
    # start = datetime.now() - timedelta(hours=24)
    # start = datetime(start.year, start.month, start.day, start.hour, start.minute, start.second)
    # end = datetime.now() + timedelta(hours=12)
    # end = datetime(end.year, end.month, end.day, end.hour, end.minute, end.second)
    df = conn_mongo_outinfo(start,end)
    if not df.empty:
        df['taskNeedOutDate'] = df['taskNeedOutDate'].apply(iso2timestamp)
        df_need = df[['taskNeedOutDate', 'totalBindNum']]
        outinfo_hour = df_need['totalBindNum'].groupby(df_need['taskNeedOutDate'].map(lambda x: x[5:13]))
        sum_outinfo_hour = outinfo_hour.sum()
        outhour_list = sum_outinfo_hour.index.to_list()
        outcounthour_list = sum_outinfo_hour.values.tolist()
        outhour_list, outcounthour_list = check_hour_zero(start, end, outhour_list, outcounthour_list)
    else:
        outhour_list = []
        outcounthour_list = []
    return (outhour_list, outcounthour_list)

def process_outinfo_day(n=5):#默认取前6天(含当天)
    first_start = get_days_before_today(n)
    outcount_list = []
    while n >=0:
        start = get_days_before_today(n)
        start = datetime(start.year,start.month,start.day,8,0,0)
        end = start + timedelta(days=1)
        df = conn_mongo_outinfo(start, end)
        if not df.empty:
            df['taskNeedOutDate'] = df['taskNeedOutDate'].apply(iso2timestamp)
            if 'totalBindNum' not in df.columns.to_list():
                current_num = 0
            else:
                current_num = df['totalBindNum'].sum()
            outcount_list.append(current_num)
        else:
            outcount_list.append(0)
        n -= 1
    # 处理向后一天数据
    add_start = end
    add_end = end + timedelta(days=1)
    df = conn_mongo_outinfo(add_start, add_end)
    if not df.empty:
        df['taskNeedOutDate'] = df['taskNeedOutDate'].apply(iso2timestamp)
        if 'totalBindNum' not in df.columns.to_list():
            current_num = 0
        else:
            current_num = df['totalBindNum'].sum()
        outcount_list.append(current_num)
    else:
        outcount_list.append(0)
        # outday_list.append(add_start)
    date = pd.date_range(first_start, add_start)
    outday_list = [datetime.strftime(x, '%F') for x in date]
    return (outday_list,outcount_list)


def check_hour_zero(start,end,hour_list,count_list):
    print ("24小时原始数据,时间{},数量{}".format(hour_list,count_list))
    date_hour_list = []
    for i in range(24):
        date_hour = (end - timedelta(hours=(i))).strftime('%m-%d %H')
        date_hour_list.append(date_hour)
    date_hour_list = list(reversed(date_hour_list))
    if len(hour_list) == len(date_hour_list):
        return (hour_list,count_list)
    else:
        l = len(date_hour_list)
        new_l = [0]*l
        for index,value in enumerate(date_hour_list):
            for index1,value1 in enumerate(hour_list):
                if value == value1:
                    new_l[index] = count_list[index1]
        # print (date_hour_list,new_l)
        print("24小时补全数据,时间{},数量{}".format(date_hour_list, new_l))
        return (date_hour_list,new_l)

def get_hour_date():
    hour_now = datetime.now()
    if hour_now.hour >= 8:
        b_start = hour_now-timedelta(days=1)
        b_start = datetime(b_start.year, b_start.month, b_start.day, 8, 0, 0)
        b_end = datetime(hour_now.year, hour_now.month, hour_now.day, 7, 59, 59)
        c_start = datetime(hour_now.year, hour_now.month, hour_now.day, 8, 0, 0)
        c_end = hour_now+timedelta(days=1)
        c_end = datetime(c_end.year, c_end.month, c_end.day, 7, 59, 59)
        print (b_start,b_end,c_start,c_end)
    else:
        b_start = hour_now-timedelta(days=2)
        b_start_before = hour_now-timedelta(days=1)
        b_start = datetime(b_start.year, b_start.month, b_start.day, 8, 0, 0)
        b_end = datetime(b_start_before.year, b_start_before.month, b_start_before.day, 7, 59, 59)
        c_start = datetime(b_start_before.year, b_start_before.month, b_start_before.day, 8, 0, 0)
        c_end = datetime(hour_now.year, hour_now.month, hour_now.day, 7, 59, 59)
        print (b_start,b_end,c_start,c_end)
    return b_start,b_end,c_start,c_end


def cach_data():
    global bar_data
    b_start_hour,b_end_hour,c_start_hour,c_end_hour = get_hour_date()
    print("*******************outinfo**7天数据准备中*********************")
    outday_list,outcount_list=process_outinfo_day()
    print("outinfo**7天数据{}{}".format(outday_list,outcount_list))
    outcount_list1 = [int(x) for x in outcount_list]
    print("*******************outinfo**前24h数据准备中*********************")
    outhour_list, outcounthour_list = process_outinfo_hour(b_start_hour,b_end_hour)
    print("*******************outinfo**后24h数据准备中*********************")
    c_outhour_list, c_outcounthour_list = process_outinfo_hour(c_start_hour,c_end_hour)
    print ("前24小时需求总数量{}".format(sum(outcounthour_list)))
    print ("后24小时需求总数量{}".format(sum(c_outcounthour_list)))
    print("*******************datalog**7天数据准备中*********************")
    day_count_list_in,day_count_list_out = process_datalog_day()
    print("datalog**7天数据出库--{},入库--{}".format(day_count_list_out, day_count_list_in))
    print("*******************datalog**前24h数据准备中*********************")
    log_data=process_datalog_hour(b_start_hour,b_end_hour)
    hour_list_in = log_data.get('hour_list_in')
    count_list_in = log_data.get('count_list_in')
    print ("前24小时入库总数量{}".format(sum(count_list_in)))
    hour_list_out = log_data.get('hour_list_out')
    count_list_out = log_data.get('count_list_out')
    print("前24小时出库总数量{}".format(sum(count_list_out)))
    print("*******************datalog**后24h数据准备中*********************")
    log_data=process_datalog_hour(c_start_hour,c_end_hour)
    c_hour_list_in = log_data.get('hour_list_in')
    c_count_list_in = log_data.get('count_list_in')
    print ("后24小时入库总数量{}".format(sum(c_count_list_in)))
    c_hour_list_out = log_data.get('hour_list_out')
    c_count_list_out = log_data.get('count_list_out')
    print("后24小时出库总数量{}".format(sum(c_count_list_out)))
    y_total = [i + j for i, j in zip(day_count_list_in, day_count_list_out)]
    bar = (
        Bar(init_opts=opts.InitOpts(bg_color='rgba(255,255,255,0.7)',
                                    theme=ThemeType.LIGHT
                                    )
            )
            .add_xaxis(hour_list_in)
            .add_yaxis("需求数量", outcounthour_list, stack="outinfo")
            .add_yaxis("实际出库数量", count_list_out,stack="datalog")
            .add_yaxis("实际入库数量", count_list_in, stack="datalog")
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False, font_size=14),markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(y=500, name="达标线=500")],linestyle_opts=opts.LineStyleOpts(width = 3,color = 'red',)))
            .set_global_opts(xaxis_opts=opts.AxisOpts(name='时间/小时',axislabel_opts=opts.LabelOpts(rotate=-60)),
                             yaxis_opts=opts.AxisOpts(name='单位:盘',max_=600,split_number=6))
    )
    barc = (
        Bar(init_opts=opts.InitOpts(bg_color='rgba(255,255,255,0.7)',
                                    theme=ThemeType.LIGHT
                                    )
            )
            .add_xaxis(c_hour_list_in)
            .add_yaxis("需求数量", c_outcounthour_list, stack="outinfo")
            .add_yaxis("实际出库数量", c_count_list_out,stack="datalog")
            .add_yaxis("实际入库数量", c_count_list_in, stack="datalog")
            .set_series_opts(label_opts=opts.LabelOpts(is_show=False, font_size=14),markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(y=500, name="达标线=500")],linestyle_opts=opts.LineStyleOpts(width = 3,color = 'red',)))
            .set_global_opts(xaxis_opts=opts.AxisOpts(name='时间/小时',axislabel_opts=opts.LabelOpts(rotate=-60)),
                             yaxis_opts=opts.AxisOpts(name='单位:盘',max_=600,split_number=6))
    )
    bar1 = (
        Bar(init_opts=opts.InitOpts(bg_color='rgba(255,255,255,0.7)',
                                    theme=ThemeType.LIGHT
                                )
        )
            .add_xaxis(outday_list)
            .add_yaxis("需求数量", outcount_list1, stack="outinfo_day")
            .add_yaxis("实际出库数量", day_count_list_out, stack="datalog_day",)
            .add_yaxis("实际入库数量", day_count_list_in, stack="datalog_day")
            .set_series_opts(label_opts=opts.LabelOpts(is_show=True,position='inside', font_size=12),markline_opts=opts.MarkLineOpts(data=[opts.MarkLineItem(y=12000, name="达标线=12000")],linestyle_opts=opts.LineStyleOpts(width = 3,color = 'red',)))
            .set_global_opts(xaxis_opts=opts.AxisOpts(name='时间/天',axislabel_opts=opts.LabelOpts(rotate=-40)),
                             yaxis_opts=opts.AxisOpts(name='单位:盘',max_=13000,split_number=13),
                             )
    )
    line = (
        Line()
            .add_xaxis(outday_list)
            .add_yaxis(
            "总数量",
            y_total,
            # color="#675bba",
            label_opts=opts.LabelOpts(is_show=True),
        )
    )
    bar1.overlap(line)
    # hourdata=bar.dump_options(),
    # daydata = bar1.dump_options()
    bar_data['hourdata'] = bar
    bar_data['chourdata'] = barc
    bar_data['daydata'] = bar1
    try:
        qty = []
        # day_count_list_in, day_count_list_out = process_datalog_day()
        # outday_list, outcount_list = process_outinfo_day()
        # outcount_list1 = [int(x) for x in outcount_list]
        n = len(outday_list)
        for i in range(n):
            qty_dict = {
                'Date': outday_list[i],
                'qty_in': day_count_list_in[i],
                'qty_out': day_count_list_out[i],
                'qty_need': outcount_list1[i],
            }
            qty.append(qty_dict)
        upload_qty(qty)
        print("出入库数据上传成功")
    except Exception as e:
        print("数据上传失败:{}".format(e))

def open_url(url):
    try:
        resp = urllib.request.urlopen(url,timeout=0.5)
        ele_json = json.loads(resp.read())
        return ele_json
    except Exception as e:
        print("出现异常:" + str(e))

def add_outinfo(equip_info,origin_equip,sign):
    equips = []
    if sign == 'agv':
        for equip in equip_info:
            equips.append(equip['name'])
        c = [x for x in equips if x in origin_equip]
        add_equip = [y for y in (equips + origin_equip) if y not in c]
        for add in add_equip:
            number = int(re.findall(r"\d+", add)[0])
            add_dict = {
                'name':add,
                'des':'运转正常',
                'state':'正常',
                'number':number
            }
            equip_info.append(add_dict)
    elif sign == 'line':
        origins = [origin for origin in origin_equip.keys()]
        for equip in equip_info:
            origins.remove(equip['name'])
        for line in origins:
            number = int(re.findall(r"\d+", line)[0])
            add_dict = {
                    'name':line,
                    'des':'状态正常',
                    'state':'正常',
                    'number':number
                }
            equip_info.append(add_dict)
        # for equip in equip_info:
        #     equips.append(equip['name'])
        # c = [x for x in equips if x in origin_equip]
        # add_equip = [y for y in (equips + origin_equip) if y not in c]
        # for add in add_equip:
        #     number = int(re.findall(r"\d+", add)[0])
        #     if add in ['4D-7线','4D-13线','4D-14线','4D-15线']:
        #         add_dict = {
        #             'name': add,
        #             'des': '--',
        #             'state': '--',
        #             'number': number
        #         }
        #     else:
        #         add_dict = {
        #             'name':add,
        #             'des':'状态正常',
        #             'state':'正常',
        #             'number':number
        #         }
        #     equip_info.append(add_dict)
    elif sign == 'box':
        for equip in equip_info:
            equips.append(equip['name'])
        c = [x for x in equips if x in origin_equip]
        add_equip = [y for y in (equips + origin_equip) if y not in c]
        for add in add_equip:
            number = int(re.findall(r"\d+", add)[0])
            add_dict = {
                'name':add,
                'des':'未获取到状态',
                'state':'异常',
                'number':number
            }
            equip_info.append(add_dict)
    return equip_info

def process_agv_error(info):
    alarm_agv = []
    global agv_error
    for agv in info:
        if agv['state'] == '异常':
            if agv['name'] in agv_error.keys():
                agv_error[agv['name']]['des'] = agv['des']
                agv_error[agv['name']]['updatetime'] = datetime.utcnow()
            else:
                current_dict = {}
                current_dict['name'] = agv['name']
                current_dict['des'] = agv['des']
                current_dict['starttime'] = datetime.utcnow()
                current_dict['updatetime'] = datetime.utcnow()
                agv_error[agv['name']] = current_dict
        else:
            if agv['name'] in agv_error.keys():
                current_name = agv['name']
                if (datetime.utcnow() - agv_error[current_name]['updatetime']).seconds > 10:
                    if '分钟' in agv_error[current_name]['des']:
                        total_time = re.findall(r"(\d+.\d+)分钟",agv_error[current_name]['des'])
                        total_time = str(total_time[0]) + '分钟'
                    elif '秒' in agv_error[current_name]['des']:
                        total_time = re.findall(r"(\d+.\d+)秒", agv_error[current_name]['des'])
                        total_time = str(total_time[0]) + '秒'
                    else:
                        total_time = '未定义时间'
                    alarm_dict = {
                        'name':agv_error[current_name]['name'],
                        'des':agv_error[current_name]['des'],
                        'starttime':agv_error[current_name]['starttime'],
                        'updatetime':datetime.utcnow(),
                        'endtime':datetime.utcnow(),
                        'totaltime':total_time
                    }
                    alarm_agv.append(alarm_dict)
                    del agv_error[current_name]
    logging.info('agv erroring:{},ready upload:{}'.format(agv_error, alarm_agv))
    return alarm_agv

def put_agv_error(alarm_agv):
    if alarm_agv:
        mongo_client = pymongo.MongoClient(host='10.85.162.124', port=27017)
        db = mongo_client['qisda']
        db.authenticate("admin", "123")
        cach = db.alarmagv
        cach.insert(alarm_agv)
        mongo_client.close()
        print ("agv错误信息写入成功")

def autoagvinfo():
    url = Config.URL
    ele_json = open_url(url)
    info_agvs = []
    info_agv = {}
    info_agv_error = {}
    for info in ele_json:
        if (info['name'])[-2:] == '号车':
            if info['type'] == 0:
                state = '异常'
                des = info['msgValue']
            else:
                if info['msgValue'] == 'Standby':
                    state = '正常'
                    des = '待机位'
                elif info['msgValue'] == 'AutoCharge':
                    state = '充电中'
                    des = '充电'
                else:
                    state = '正常'
                    des = info['msgValue']
            number = int(re.findall(r"\d+", info['name'])[0])
            # print (number)
            c_dict = {
                'name':info['name'],
                'des':des,
                'state':state,
                'number':number}
            if state == '异常':
                info_agv_error[info['name']] = c_dict
            else:
                info_agv[info['name']] = c_dict
    if info_agv_error:
        for key, value in info_agv_error.items():
            if key in info_agv.keys():
                del info_agv[key]
                info_agvs.append(value)
        for key,value in info_agv.items():
            info_agvs.append(value)
    return info_agvs


def upload_qty(qty):
    mongo_client = pymongo.MongoClient(host='10.85.162.124', port=27017)
    db = mongo_client['qisda']
    db.authenticate("admin", "123")
    for line in qty:
        date = line['Date']
        cach = db.stockqty
        data = cach.find_one({"Date":date})
        if data:
            cach.update({"Date": date}, {'$set': {"qty_in": line['qty_in'],"qty_out":line['qty_out'],"qty_need":line['qty_need']}})
        else:
            cach.insert(line)
    mongo_client.close()

#def download_stockqty():


@bp.route('/getagvinfo',methods=['POST'])
def getagvinfo():
    url = Config.URL
    ele_json = open_url(url)
    current_agv = Config.CONFIG_AGV
    info_agv = []
    agv_name = []
    for info in ele_json:
        if (info['name'])[-2:] == '号车':
            if info['type'] == 0:
                des = info['msgValue']
                if info['msgValue'] == '停用':
                    state = '停用'
                elif info['msgValue'] == '离线':
                    state = '离线'
                else:
                    state = '异常'
            else:
                if info['msgValue'] == 'Standby':
                    state = '正常'
                    des = '待机位'
                elif info['msgValue'] == 'AutoCharge':
                    state = '充电中'
                    des = '充电'
                else:
                    state = '正常'
                    des = info['msgValue']
            number = int(re.findall(r"\d+", info['name'])[0])
            # print (number)
            c_dict = {
                'name':info['name'],
                'des':des,
                'state':state,
                'number':number}
            info_agv.append(c_dict)
    sign = 'agv'
    info_agv = add_outinfo(info_agv,current_agv,sign)
    info_agv = sorted(info_agv, key=operator.itemgetter('number'))
    return json.dumps(info_agv)

@bp.route('/get4cinfo',methods=['POST'])
def get4cinfo():
    url = Config.URL
    ele_json = open_url(url)
    current_4c = Config.CONFIG_4C
    info_4c = []
    for info in ele_json:
        if info['msgKey'][8:9] == 'C' and 'Feed' not in info['name']:
            if info['type'] == 0:
                if info['name'] in ['4C-15线','4C-14线','4C-10线','4C-2线']:
                    state = '--'
                else:
                    state = '异常'
            else:
                state = '正常'
            number = int(re.findall(r"\d+", info['name'])[1])
            if info['name'] in ['4C-15线', '4C-14线', '4C-10线','4C-2线']:
                des = '--'
            else:
                des=info['msgValue']
            c_dict = {
                'name': info['name'],
                'des': des,
                'state': state,
                'number':number}
            info_4c.append(c_dict)
        else:
            pass
    # info_4c = json.dumps(info_4c)
    sign = 'line'
    info_4c = add_outinfo(info_4c, current_4c,sign)
    info_4c = sorted(info_4c, key=operator.itemgetter('number'))
    return json.dumps(info_4c)

@bp.route('/get4dinfo',methods=['POST'])
def get4dinfo():
    url = Config.URL
    ele_json = open_url(url)
    current_4d = Config.CONFIG_4D
    current_3d = Config.CONFIG_3D
    info_4d = []
    for info in ele_json:
        # if info['msgKey'][8:9] == 'S' and 'Feed' not in info['name']:
        # if 'lineAgv.S' in info['msgKey']:
        # if (info['name'])[-2:] == '号车':
        if info['name'] in current_3d.keys():
            if info['type'] == 0:
                state = '异常'
            else:
                state = '正常'
            number = int(re.findall(r"\d+", info['name'])[0])
            des=info['msgValue']
            c_dict = {
                'name': info['name'],
                'des': des,
                'state': state,
                'number':number}
            info_4d.append(c_dict)
        else:
            pass
    # info_4d = json.dumps(info_4d)
    sign = 'line'
    info_4d = add_outinfo(info_4d, current_3d,sign)
    info_4d = sorted(info_4d, key=operator.itemgetter('number'))
    return json.dumps(info_4d)

@bp.route('/getboxinfo',methods=['POST'])
def getboxinfo():
    url = Config.BOX_URL
    ele_json = open_url(url)
    current_box = Config.CONFIG_BOX
    current_box_status = Config.CONFIG_BOX_STATUS
    ratio_dict = get_boxratio()
    info_box = []
    for info in ele_json:
        if info['cid'][0:7] == 'line-ac':
            if info['status'] == 1:
                status = info['boxStatus']['1']['status']
                if status in [2,3,4,5]:
                    state = '异常'
                else:
                    state = '正常'
                # des = current_box_status[status] + '温度' + info['boxStatus']['1']['temperature'] + '℃' + '湿度' + info['boxStatus']['1']['humidity']
                des = current_box_status[status]
            elif info['status'] == 999:
                des = '离线'
                state = '异常'
            number = int(re.findall(r"\d+", info['cid'])[0])
            c_dict = {
                'name': info['cid'],
                'des': des,
                'state': state,
                'number':number}
            info_box.append(c_dict)
        else:
            pass
    # info_4d = json.dumps(info_4d)
    sign = 'box'
    info_box = add_outinfo(info_box, current_box,sign)
    info_box = sorted(info_box, key=operator.itemgetter('number'))
    box_trans = Config.CONFIG_BOX_TRANS
    # info_boxs = [info_box[i:i + 2] for i in range(0, len(info_box), 2)]
    # temp_list = []
    # for index,value in enumerate(info_boxs):
    #     str1 = '云料仓' + str(index+1) + '-' +'1'
    #     str2 = '云料仓' + str(index+1) + '-' +'2'
    #     temp_list.append(str1)
    #     temp_list.append(str2)
    # for index,s in enumerate(info_box):
    #     info_box[index]['name'] = temp_list[index]
    #     info_box[index]['ratio'] = ratio_list[index]
    json_data = []
    for s in info_box:
        ratio = ratio_dict.get(s['name'],0)
        trans_name = box_trans.get(s['name'],'')
        json_dict = {
                'name': trans_name,
                'des': s['des'],
                'state': s['state'],
                'number':s['number'],
                'ratio':ratio
        }
        json_data.append(json_dict)
    return json.dumps(json_data)

@bp.route('/drawchartday')
def drawchartday():
    global bar_data
    if bar_data:
        daydata = bar_data.get('daydata','')
        return daydata.dump_options_with_quotes()

@bp.route('/drawcharthour')
def drawcharthour():
    global bar_data
    if bar_data:
        hourdata = bar_data.get('hourdata','')
        return hourdata.dump_options_with_quotes()

@bp.route('/drawcharthourc')
def drawcharthourc():
    global bar_data
    if bar_data:
        chourdata = bar_data.get('chourdata','')
        return chourdata.dump_options_with_quotes()

def get_boxratio():
    url = Config.BOX_RATIO_URL
    ele_json = open_url(url)
    # ratio_list = []
    ratio_dict = {}
    for info in ele_json:
        usecount = 0
        totalcount = 0
        for nummap in info['usageMap'].values():
            usecount += int(nummap['usedCount'])
            totalcount += int(nummap['totalCount'])
        current_ratio = usecount/totalcount
        if current_ratio > 1:
            current_ratio = 1
        current_ratio = ('%.2f%%' % (current_ratio * 100))
        # number = int(re.findall(r"\d+", info['cid'])[0])
        # name = info['cid']
        ratio_dict[info['cid']] = current_ratio
        # ratio_dict = {
        #             'ratio':current_ratio,
        #             'number':info['cid']
        # }
        # ratio_list.append(ratio_dict)
    # ratio_list = sorted(ratio_list, key=operator.itemgetter('number'))
    # out_list = []
    # for m in ratio_list:
    #     out_list.append(m['ratio'])
    return ratio_dict

def conn_mongo_alarminfo(start,end):
    mongo_client = pymongo.MongoClient(host='10.85.162.124', port=27017)
    db = mongo_client['qisda']
    db.authenticate("admin", "123")
    cach = db.alarmInfo
    start_date = local2utc(start)
    end_date = local2utc(end)
    data = list(cach.find({"createDate": {"$gte": start_date, "$lt": end_date}}))
    mongo_client.close()
    return (data)

def check_type(date,data):
    count1 = count2 = count3 = count4 = count5 = 0
    info_list = [x['alarmMsg'] for x in data]
    for line in info_list:
        if '未扫到条码' in line or '未找到有效条码' in line:
            count1 += 1
        elif '入库判定NG' in line or '找到多个有效条码' in line or '已在' in line or '操作未完成' in line:
            count2 += 1
        elif '对应数量<=0' in line or '收料接口处理异常' in line:
            count3 += 1
        elif '无法收料' in line:
            count4 += 1
        elif '未找到可用的' in line or '已满' in line:
            count5 += 1
        else:
            pass
    mongo_client = pymongo.MongoClient(host='10.85.162.124', port=27017)
    db = mongo_client['qisda']
    db.authenticate("admin", "123")
    cach = db.collectNg
    data = cach.find_one({"Date": date})
    if data:
        cach.update({"Date": date},{'$set': {"codetype": count1, "operation": count2, "api": count3,"DN": count4,"stock": count5,'updateDate':datetime.utcnow()}})
    else:
        ks = {'Date':date,"codetype": count1, "operation": count2, "api": count3,"DN": count4,"stock": count5,'createDate':datetime.utcnow(),'updateDate':datetime.utcnow()}
        cach.insert(ks)
    logging.info('ng统计消息上传成功')
    mongo_client.close()



def serverpost():
    global is_start
    while is_start:
        try:
            info_agv = autoagvinfo()
            error_info = process_agv_error(info_agv)
            put_agv_error(error_info)
            logging.info('agv error info collecting')
        except Exception as e:
            logging.info('agv error info collecting failed:{}'.format(e))
        finally:
            time.sleep(2)

def upload_nginfo():
     global  is_start
     while is_start:
         try:
             now = datetime.now()
             start = datetime(now.year,now.month,now.day,0,0,0)
             end = datetime(now.year,now.month,now.day,23,59,59)
             date=now.strftime("%Y-%m-%d")
             data = conn_mongo_alarminfo(start,end)
             check_type(date,data)
         except Exception as e:
             logging.info('NG info collecting failed:{}'.format(e))
         finally:
             time.sleep(60*60)




def servermongo():
    global is_start
    while is_start:
        try:
            cach_data()
        except Exception as e:
            logging.info('获取图表数据失败:{}'.format(e))
        finally:
            time.sleep(300)

@bp.route('/')
@bp.route('/index')
def index():
    return render_template("index.html")

@bp.route('/state')
def state():
    return render_template("state.html")

@bp.route('/dataload')
def dataload():
    return render_template("download.html")


threads = []
threads.append(threading.Thread(target=serverpost))
threads.append(threading.Thread(target=upload_nginfo))
threads.append(threading.Thread(target=servermongo))
for t in threads:
    t.start()
print ("启动成功")