示例#1
0
def handle_world_response():
    global seq
    global amazon_socket
    global world_socket
    global ack_set
    global setlock
    global worldid

    #receive UResponses from world
    received = receive_msg(world_socket)
    print("[DEBUG] Receive UResponses")
    if len(received) == 0:
        print("Empty message")
        world_socket = get_world_socket()
        connect_to_world_again(10, worldid)
        return

    uresponses = world_ups_pb2.UResponses()
    uresponses.ParseFromString(received)

    if (uresponses.finished == True):
        print("[DEBUG] finished by world")

    for delivery in uresponses.delivered:
        print("[DEBUG] Receive UResponses delivered")
        lock.acquire()
        seqNum = seq
        seq += 1
        lock.release()
        t = threading.Thread(target=handle_deliveryMade,
                             args=(delivery, seqNum))
        t.start()

    for completion in uresponses.completions:
        print("[DEBUG] Receive UResponses finished")
        lock.acquire()
        seqNum = seq
        seq += 1
        lock.release()
        t = threading.Thread(target=handle_finished, args=(completion, seqNum))
        t.start()

    for ack in uresponses.acks:
        print("[DEBUG] World ACK is " + str(ack))
        setlock.acquire()
        ack_set.add(ack)
        print(ack_set)
        setlock.release()

    for error in uresponses.error:
        print("[DEBUG] Receive UResponses error")
        lock.acquire()
        seqNum = seq
        seq += 1
        lock.release()
        t = threading.Thread(target=handle_error_world, args=(error, seqNum))
        t.start()

    for t in uresponses.truckstatus:
        print("[DEBUG] TRUCKSTATUS " + str(t.truck_id) + "  " + t.status)
示例#2
0
def recvMsg(socket, msgType):
    var_int_buff = []
    while True:
        buf = socket.recv(1)
        var_int_buff += buf
        msg_len, new_pos = _DecodeVarint32(var_int_buff, 0)
        if new_pos != 0:
            break
    whole_message = socket.recv(msg_len)

    if msgType == "UConnected":
        msg = wu.UConnected()
        msg.ParseFromString(whole_message)
    elif msgType == "UResponses":
        msg = wu.UResponses()
        msg.ParseFromString(whole_message)
    elif msgType == "AMessages":
        msg = ua.AMessages()
        msg.ParseFromString(whole_message)
    else:
        print("Receive an undefined message.")
        return
    print("------------")
    print("recv:", msg)
    print("------------")

    return msg
示例#3
0
 def handler(self):
     #self.file_handle.write()
     print("Handling response...")
     while True:
         response = world_ups_pb2.UResponses()
         self.recv_data(response)
         self.parse_responses(response)
示例#4
0
文件: tool.py 项目: RAN1025/mini-UPS
def URecv(sock, isUConnect=False):
    all_data = b''
    data = sock.recv(4)
    if not data:
        print('connection to world is closed')
    data_len, new_pos = _DecodeVarint32(data, 0)
    all_data += data[new_pos:]

    data_left = data_len - len(all_data)
    while True:
        data = sock.recv(data_left)
        all_data += data
        data_left -= len(data)

        if data_left <= 0:
            break

    if isUConnect:
        msg = wupb.UConnected()
        msg.ParseFromString(all_data)
        return msg

    msg = wupb.UResponses()
    msg.ParseFromString(all_data)
    return msg
def recv_world_msg(world_id, amazon_fd, world_fd):
    # create a thread pool to handle received messages
    #pool = ThreadPoolExecutor(5)
    while 1:
        # receive a message from Amazon and assign a thread to handle it
        message = world_ups_pb2.UResponses()
        message = recv_from_world(message, world_fd)
        print(message)
        #world_msg = recv_message(world_fd, ups_pb2.UResponses)
        thread1 = threading.Thread(target=ups_world_receiver,
                                   args=(message, world_id, amazon_fd,
                                         world_fd))
        #pool.submit(ups_world_receiver, message, world_id, amazon_fd, world_fd)
        thread1.start()
        thread1.join()
示例#6
0
def parse_ures(msg_str):
    msg = world_ups_pb2.UResponses()
    msg.ParseFromString(msg_str)
    return msg
示例#7
0
def main():

    global glonal_seqnum

    worldID = connect_world_simulator()
    send_worldID_to_Amazon(worldID)
    print("worldID = ", worldID)

    while True:
        # recv sendTruck from amazon - ok
        print("=== waiting for amazon sendtrucks cmd ===")
        data = recv_from_amazon()
        a2ucmds_sendtrucks = amazon_ups_pb2.AtoUCommands()
        a2ucmds_sendtrucks.ParseFromString(data)
        trucks_to_sent = a2ucmds_sendtrucks.sendtrucks
        print("=== received sendtrucks cmd ===")
        print(a2ucmds_sendtrucks)

        # ====== interact with db to choose truck
        print("=== choose truck ===")
        idle_truck_id = 0
        cursor_db.execute(
            "SELECT TRUCK_ID from TRUCK where STATUS='idle' OR STATUS='delivering'"
        )
        rows = cursor_db.fetchall()
        if len(rows) > 0:
            for row in rows:
                print("TRUCK_ID = ", row[0])
            # choose first idle truck
            idle_truck_id = row[0]
            # update TRUCK table
            cursor_db.execute(
                "UPDATE TRUCK set STATUS = 'traveling' where TRUCK_ID = " +
                str(idle_truck_id))
            conn_db.commit()

        # ===== interact with db to update package table
        for each_truck in trucks_to_sent:
            for each_pack in each_truck.packages:
                cursor_db.execute("INSERT INTO PACKAGE (PACKAGE_ID,USER_NAME,DEST_X,DEST_Y,PACK_STATUS, TRUCK_ID) \
                VALUES ("                         +str(each_pack.packageid)+", '"+each_pack.ups_user_name+"', " \
                +str(each_pack.x)+", "+str(each_pack.y)+", 'in warehouse', "+str(idle_truck_id)+" )")
                conn_db.commit()

        # send pickup cmd to world - ok
        ucmds_pickup = world_ups_pb2.UCommands()
        ucmds_pickup.simspeed = 10000
        i = 1
        for one_truck in trucks_to_sent:
            each_pickup = world_ups_pb2.UGoPickup()
            each_pickup.truckid = 1
            each_pickup.whid = one_truck.whs.id
            each_pickup.seqnum = i
            ucmds_pickup.pickups.extend([each_pickup])
            i += 1
        ucmds_pickup_req = ucmds_pickup.SerializeToString()
        print("=== Sent GoPickup to world ===")
        print(ucmds_pickup)
        _EncodeVarint(conn_world.sendall, len(ucmds_pickup_req))
        conn_world.sendall(ucmds_pickup_req)

        # insert cmd in SEQACK table
        cursor_db.execute("INSERT INTO SEQACK (SEQNUM,COMMAND,WORLD_ID) \
            VALUES (" + str(global_seqnum) + ", 'UGoPickup', " + str(worldID) +
                          ")")
        global_seqnum += 1
        conn_db.commit()

        # send trucksent to amazon
        u2aresp_trucksent = amazon_ups_pb2.UtoAResponses()
        for each_trucks_to_sent in trucks_to_sent:
            trksent = amazon_ups_pb2.UTruckSent()
            trksent.truckid = 1
            for each_pack in each_trucks_to_sent.packages:
                trksent.packages.extend([each_pack])
            u2aresp_trucksent.trucksent.extend([trksent])

        print("=== Sent TruckSent to amazon ===")
        print(u2aresp_trucksent)
        u2aresp_trucksent_resp = u2aresp_trucksent.SerializeToString()
        print("trucksent after encoded: ", u2aresp_trucksent_resp)
        _EncodeVarint(conn_amazon.sendall, len(u2aresp_trucksent_resp))
        conn_amazon.sendall(u2aresp_trucksent_resp)

        # recv ufinish from world and ensure truck arrives - ok
        print("=== wait for world truckarrived ===")
        while True:
            data = recv_from_world()
            uresp_truckarrive = world_ups_pb2.UResponses()
            uresp_truckarrive.ParseFromString(data)
            print("=== received truckarrived from world ===")
            print(uresp_truckarrive)

            if uresp_truckarrive.acks:
                resp_acks = uresp_truckarrive.acks
                # delete ack
                for ack in resp_acks:
                    cursor_db.execute("DELETE from SEQACK where SEQNUM=" +
                                      str(ack) + ";")
                    conn_db.commit()
            if uresp_truckarrive.completions:
                break
            else:
                continue
        # send truck arrived to Amazon - ok
        u2aresp_truckarrive = amazon_ups_pb2.UtoAResponses()
        for one_truck in uresp_truckarrive.completions:
            each_arrive = amazon_ups_pb2.UTruckArrived()
            each_arrive.truckid = one_truck.truckid
            u2aresp_truckarrive.arrived.extend([each_arrive])
        u2aresp_truckarrive_resp = u2aresp_truckarrive.SerializeToString()
        print("=== sent truckarrived to amazon ===")
        print(u2aresp_truckarrive)
        _EncodeVarint(conn_amazon.sendall, len(u2aresp_truckarrive_resp))
        conn_amazon.sendall(u2aresp_truckarrive_resp)

        # recv startdelivery from Amazon - ok
        print("=== waiting for startdelivery from amazon ===")
        data = recv_from_amazon()
        a2ucmds_startdelivery = amazon_ups_pb2.AtoUCommands()
        a2ucmds_startdelivery.ParseFromString(data)
        all_deliveries = a2ucmds_startdelivery.startdelivery
        print("=== received startdelivery from amazon ===\n", all_deliveries)

        # db: update status in table package
        for each_delivery in all_deliveries:
            for each_pack in each_delivery.packages:
                cursor_db.execute(
                    "UPDATE PACKAGE set PACK_STATUS = 'out for delivery' where PACKAGE_ID = "
                    + str(each_pack.packageid))
                conn_db.commit()

        # send UGoDeliver to world
        ucmds_godeliver = world_ups_pb2.UCommands()
        ucmds_godeliver.simspeed = 10000
        for each_delivery in all_deliveries:
            delivery = world_ups_pb2.UGoDeliver()
            delivery.truckid = each_delivery.truckid
            for each_package in each_delivery.packages:
                single_package = world_ups_pb2.UDeliveryLocation()
                single_package.packageid = each_package.packageid
                single_package.x = each_package.x
                single_package.y = each_package.y
                delivery.packages.extend([single_package])
                delivery.seqnum = 10
            ucmds_godeliver.deliveries.extend([delivery])

        print("=== sent GoDeliver to world ===")
        print(ucmds_godeliver)
        ucmds_godeliver_req = ucmds_godeliver.SerializeToString()
        _EncodeVarint(conn_world.sendall, len(ucmds_godeliver_req))
        conn_world.sendall(ucmds_godeliver_req)

        # insert cmd in SEQACK table
        cursor_db.execute("INSERT INTO SEQACK (SEQNUM,COMMAND,WORLD_ID) \
        VALUES (" + str(global_seqnum) + ", 'UGoDelivery', " + worldID + ")")
        global_seqnum += 1
        conn_db.commit()

        print("=== wait for world DeliverMade ===")
        while True:
            data = recv_from_world()
            uresp_delivered = world_ups_pb2.UResponses()
            uresp_delivered.ParseFromString(data)
            print("=== received world DeliverMade ===")
            print(uresp_delivered)
            if uresp_delivered.acks:
                resp_acks = uresp_delivered.acks
                # delete ack
                for ack in resp_acks:
                    cursor_db.execute("DELETE from SEQACK where SEQNUM=" +
                                      str(ack) + ";")
                    conn_db.commit()

            if not uresp_delivered.delivered:
                continue
            else:
                all_delivered = uresp_delivered.delivered
                # generate deliveryMade response to amazon
                u2aresp_delivered = amazon_ups_pb2.UtoAResponses()
                for each_delivered in all_delivered:
                    each_delivered_a = amazon_ups_pb2.UDelivered()
                    each_delivered_a.shipid = each_delivered.packageid
                    u2aresp_delivered.delivered.extend([each_delivered_a])

                # send delivery msg to Amazon
                print("=== sent delivered to amazon ===")
                print(u2aresp_delivered)
                u2aresp_delivered_resp = u2aresp_delivered.SerializeToString()
                _EncodeVarint(conn_amazon.sendall, len(u2aresp_delivered_resp))
                conn_amazon.sendall(u2aresp_delivered_resp)

                # if all delivered, then break
                if uresp_delivered.completions:
                    print("contain completions msg, all delivery made")
                break

    conn_world.close()
    print("conn_world closed")