Exemplo n.º 1
0
def parse_ups_response(response):
    if (len(response) <= 1):
        print("not value but " + response)
        print("length is " + str(len(response)))
        return ""
    print("could be response len is " + str(len(response)))
    message_length, next_pos = _DecodeVarint32(response, 0)
    print(next_pos)
    amazoncmd = UA_pb2.UPSResponses()
    amazoncmd.ParseFromString(response[next_pos:next_pos + message_length])
    print("Req: ")
    print(amazoncmd.__str__())

    # print ("could be response len is "+str(len(response)))
    # message_length, next_pos = _DecodeVarint32(response, 0)
    # print(next_pos)
    # ups_res = UA_pb2.UPSResponses()
    # ups_res.ParseFromString(response[next_pos : next_pos + message_length])
    # print("Req: ")
    # print(ups_res.__str__())

    # n=0
    # next_pos, pos = 0, 0
    # res = UA_pb2.UPSResponses()
    # while n<len(response):
    #     msg_len, new_pos = _DecodeVarint32(response, n)
    #     n = new_pos
    #     msg_buf = response[n:n+msg_len]
    #     print("msg length ",msg_len)
    #     print("raw data is ",response)
    #     n += msg_len
    #     res.ParseFromString(msg_buf)
    # print ("parse result "+res.__str__())
    return amazoncmd
Exemplo n.º 2
0
def listen_ups(ups_socket, world_socket, db, world_acks, world_seqs, ups_acks,
               ups_seqs, email_socket, email_sender):
    print("=============== Start to listen UPS ===========\n")
    while True:
        try:
            response = my_recv(ups_socket)
        except Exception as e:
            print("---------------- UPS Recv Failure -------------\n")
            break

        if response is not None:
            command = UA_pb2.UtoACommand()
            command.ParseFromString(response)
            print("---------------- Receive from UPS -------------\n")
            print(command)
            print("-----------------------------------------------\n")
            for _ in command.ack:
                ups_acks.add(_)

            for user in command.usrVlid:
                # avoid repeated handle
                ack_back_ups(ups_socket, user.seqNum)
                if user.seqNum in ups_seqs:
                    continue
                ups_seqs.add(user.seqNum)
                ua_validated(db, world_socket, user, ups_acks, world_acks,
                             email_socket, email_sender)

            for to_load in command.loadReq:
                # avoid repeated handle
                ack_back_ups(ups_socket, to_load.seqNum)
                if to_load.seqNum in ups_seqs:
                    continue
                ups_seqs.add(to_load.seqNum)
                threading.Thread(target=world_load,
                                 args=(db, world_socket, to_load.warehouseId,
                                       to_load.truckId, to_load.shipId,
                                       world_acks)).start()
                sid_plain_list = ()
                for sid in to_load.shipId:
                    sid_plain_list += (sid, )
                update_truck_id(db, to_load.truckId, sid_plain_list)

            for delivered in command.delivery:
                # avoid repeated handle
                ack_back_ups(ups_socket, delivered.seqNum)
                if delivered.seqNum in ups_seqs:
                    continue
                ups_seqs.add(delivered.seqNum)
                update_pkg_status(db, 8, delivered.shipId)
                receiver = q_email_by_sid(db, delivered.shipId)
                pkg_status = 'DELIVERED.'
                send_email(receiver, delivered.shipId, pkg_status,
                           email_socket, email_sender)

            if command.disconnection:
                world_disconnect(world_socket)
                email_socket.quit()
                break
Exemplo n.º 3
0
def ua_connect(ups_socket):
    response = my_recv(ups_socket)
    command = UA_pb2.UtoACommand()
    command.ParseFromString(response)
    for conn in command.connection:
        ack_back_ups(ups_socket, conn.seqNum)
        print(conn)
        recv_world_id = conn.worldId
        return recv_world_id
Exemplo n.º 4
0
def au_deliver(db, ups_socket, loaded, ups_acks):
    ship_list = [loaded.shipid]
    # shipinfo
    for sid in ship_list:
        deliver = UA_pb2.AtoUCommand()
        seqnum = next(gen)
        deliver.loadReq.add(seqNum=seqnum, shipId=ship_list, truckId=q_pkg_id(db, sid)[1])   
        send_ups(ups_socket, deliver, seqnum, ups_acks)
        update_pkg_status(db, 7, sid)
Exemplo n.º 5
0
def parse_response(response):
    if (len(response) <= 1):
        print("not value but " + response)
        print("length is " + str(len(response)))
        return ""
    print("could be response len is " + str(len(response)))
    n = 0
    next_pos, pos = 0, 0
    res = UA_pb2.AmazonCommands()
    while n < len(response):
        msg_len, new_pos = _DecodeVarint32(response, n)
        n = new_pos
        msg_buf = response[n:n + msg_len]
        n += msg_len
        res.ParseFromString(msg_buf)
    print("parse result " + res.__str__())
    return res
Exemplo n.º 6
0
def django_receiver(socket):
    print("Enter Django Receiver")
    while True:
        conn, addr = socket.accept()
        data = conn.recv(1024)
        if len(data) <= 1:
            continue
        print("server receive django data ", data)
        msg = json.loads(data.decode())
        # for key,value in msg.items():
        # 	print (key, value)
        #   logger.info(key, value)

        #Contruct Amazon purchase command
        command_msg = amazon_pb2.ACommands()
        command_msg.disconnect = False
        buy = command_msg.buy.add()
        buy.whnum = msg.get('whnum')
        product = buy.things.add()
        product.id = msg.get('pid')
        product.description = msg.get('description')
        product.count = int(msg.get('count'))
        # product = Product(msg.get('pid'), msg.get('description'), int(msg.get('count')))

        #Contruct UPS Message
        ups_command = UA_pb2.AmazonCommands()
        product = ups_command.req_ship.package.things.add()
        product.id = msg.get('pid')
        product.description = msg.get('description')
        product.count = int(msg.get('count'))
        ups_command.req_ship.package.whnum = msg.get('whnum')
        ups_command.req_ship.package.shipid = msg.get('shipid')
        ups_command.req_ship.x = msg.get('address_x')
        ups_command.req_ship.y = msg.get('address_y')
        ups_command.req_ship.upsAccount = '123'

        print("django_sender msg construct finish")
        mutex_ups.acquire()
        ups_queue.put(ups_command)
        mutex_ups.release()

        mutex_django.acquire()
        msg_queue.put(command_msg)
        mutex_django.release()
Exemplo n.º 7
0
def au_pickup(db, ups_socket, shipId, ups_acks):
    seqnum = next(gen)
    au_command = UA_pb2.AtoUCommand()  
    # find wh/x/y/buystr from db
    pickup = au_command.pikReq.add()
    pkg = q_pkg_id(db, shipId)
    print(pkg)
    pickup.seqNum = seqnum
    pickup.warehouseId = pkg[8]
    newship = pickup.shipment.add()
    newship.shipId = shipId
    if pkg[6] is not None:
        newship.UPSaccount = pkg[6]
    # parse purchase_list
    buy = getListfromStr(pkg[4])
    for item in buy:
        newship.products.add(description = item['description'], count = item['count'])
    newship.destination_x = pkg[2]
    newship.destination_y = pkg[3]
    # send to ups
    send_ups(ups_socket, au_command, seqnum, ups_acks)
Exemplo n.º 8
0
def amazon_receiver(amazon_socket):
    print("Enter amazon Receiver")
    global amazon_conn
    amazon_conn, addr = amazon_socket.accept()
    while True:

        data = amazon_conn.recv(2048)

        if len(data) <= 1:
            continue
        print("receive amazon data " + data.__str__())
        # response = UA_pb2.AmazonCommands()
        # response.ParseFromString(data)
        response = parse_response(data)
        UPS_response = UA_pb2.UPSResponses()
        print("UPS receive amazon data" + data.__str__())
        if response.HasField('req_ship'):
            ship_req = response.req_ship
            x = ship_req.x
            y = ship_req.y
            ups_account = ship_req.upsAccount
            package = ship_req.package
            whnum = package.whnum
            ship_id = package.shipid
            print("address is " + str(x) + " " + str(y))
            print("ups_Account is " + ups_account)
            print("pick up at warehouse " + str(whnum))
            for p in package.things:
                print("package has item " + p.description + " with count " +
                      str(p.count))

            UPS_response.resp_truck.truckid = 1
            UPS_response.resp_truck.whnum = whnum
            UPS_response.resp_truck.shipid = ship_id
            mutex.acquire(1)
            msg_queue.put(UPS_response)
            mutex.release()
        if response.HasField('req_deliver_truckid'):
            print("Sending Truck" + str(response.req_deliver_truckid) +
                  " to deliver")
Exemplo n.º 9
0
def au_validate(ups_socket, ups_acks, ups_acc, sid):
    seqnum = next(gen)
    val_user = UA_pb2.AtoUCommand()
    val_user.usrVlid.add(seqNum=seqnum, UPSaccount=ups_acc, shipId=sid)
    send_ups(ups_socket, val_user, seqnum, ups_acks)
Exemplo n.º 10
0
def ack_back_ups(ups_socket, seqnum):
    ack_command = UA_pb2.AtoUCommand()
    ack_command.ack.append(seqnum)
    print("---------------- ACK back to UPS --------------")
    my_send(ups_socket, ack_command)
Exemplo n.º 11
0
def Recv_Responses(recv_msg,
                   msg_queue,
                   ups_queue,
                   mutex_django,
                   mutex_ups,
                   connection=None):
    cur = None
    if connection is not None:
        cur = connection.cursor()
    msg = amazon_pb2.AResponses()
    msg.ParseFromString(recv_msg)
    if (not msg) or (not msg.ListFields()):
        print("\033[33mrecv_response is empty\033[0m")
        return

    # receive arrived msg
    if len(msg.arrived) != 0:
        command_msg = amazon_pb2.ACommands()
        for purchaseMore in msg.arrived:
            print("whnum = ", purchaseMore.whnum)
            pack = command_msg.topack.add()
            pack.whnum = purchaseMore.whnum
            order_id = -1
            for product in purchaseMore.things:
                thing = pack.things.add()
                thing.id = product.id
                thing.description = product.description
                thing.count = product.count
                cur.execute(
                    "SELECT order_id from amazon_web_orders where product_id = %s AND count = %s AND warehouse = %s AND purchased = False",
                    (product.id, product.count, purchaseMore.whnum))
                order_id_list = cur.fetchall()
                if (len(order_id_list) < 1):
                    print("product id ", product.id)
                    print("count ", product.count)
                    print("warehouse ", purchaseMore.whnum)
                    print("length ", len(order_id_list))
                order_id = order_id_list[0]
                cur.execute(
                    "update amazon_web_orders set purchased=TRUE where order_id = %s",
                    order_id)
                connection.commit()
                print("purchase update affect row ", cur.rowcount)

            # not included in arrived msg, get from database
            # cannot locate order_id based on returned data, search in database for corresponding orders
            # SELECT order_id form orders where product_id = a.things[0].id AND count = a.things[0].count AND warehouse = whnum
            print("product: id = ", product.id, " description = ",
                  product.description, " count = ", product.count)
            print("create topack command, shipid= ", order_id[0])
            pack.shipid = order_id[0]  # should change later

        mutex_django.acquire(1)
        msg_queue.put(command_msg)
        mutex_django.release()

    print("Ready List: ", end='')
    for rdy in msg.ready:  #ship ids
        print(rdy, end=', ')

        # set ready bit for ship ids
        cur.execute(
            "update amazon_web_orders set ready=TRUE where order_id = %s",
            (rdy, ))
        connection.commit()
        print("ready update affect row ", cur.rowcount)
        cur.execute(
            "SELECT arrive,warehouse,truck_id from amazon_web_orders where order_id = %s",
            (rdy, ))

        # In result set (cursor), if truck Arrived, create load message and insert into msq_queue
        status_list = cur.fetchall()
        assert (len(status_list) == 1)
        arrive_status = status_list[0][0]
        if arrive_status == False:
            continue
        else:
            command_msg = amazon_pb2.ACommands()
            to_load = command_msg.load.add()
            to_load.whnum = status_list[0][1]
            to_load.truckid = status_list[0][2]
            to_load.shipid = rdy
            print(command_msg.__str__())
            mutex_django.acquire(1)
            msg_queue.put(command_msg)
            mutex_django.release()
    print('')

    print("Loaded List: ")
    for load in msg.loaded:
        print(load, end='')
        # Receive a loaded message, create a to delieve msg into ups queue
        # TODO: update load
        cur.execute(
            "update amazon_web_orders set load=TRUE where order_id = %s",
            (load, ))
        connection.commit()

        # TODO: use shipid to get truckid
        cur.execute(
            "SELECT truck_id from amazon_web_orders where order_id = %s",
            (load, ))
        truck_list = cur.fetchall()
        assert (len(truck_list) == 1)
        ups_command = UA_pb2.AmazonCommands()
        ups_command.req_deliver_truckid = truck_list[0][0]

        mutex_ups.acquire()
        ups_queue.put(ups_command)
        mutex_ups.release()

    if msg.HasField("error"):
        print("\033[31mError: \033[0m", msg.error)

    if msg.HasField("finished"):
        if msg.finished:
            print("\033[32mFinished\033[0m")
        else:
            print("\033[32mNot finish\033[0m")