def QueryTruck(wSock, aSock, db): print('query truck status, update front end') global SeqNum while True: time.sleep(20) print('truck query start') with db_lock: cur = db.cursor() sql = '''SELECT truckid FROM truck WHERE status = 'delivering';''' cur.execute(sql) row = cur.fetchone() ToWorld = wupb.UCommands() ToWorld_empty = True while row: ToWorld_empty = False msg = ToWorld.queries.add() msg.truckid = row[0] with seq_lock: msg.seqnum = SeqNum SeqNum += 1 Insertusend(db, msg.seqnum, msg.SerializeToString(), 'UQuery') with db_lock: row = cur.fetchone() if not ToWorld_empty: Send(wSock, ToWorld)
def init_world(world_fd, db_cur, db_conn): UConnect = world_ups_pb2.UConnect() UConnect.isAmazon = False #UConnect.worldid = 1 for i in range(1, 3): car1 = UConnect.trucks.add() car1.id = i car1.x = i car1.y = i send_to_world(UConnect, world_fd) UConnected = world_ups_pb2.UConnected() UConnected = recv_from_world(UConnected, world_fd) world_id = UConnected.worldid for i in range(1, 3): db_cur.execute("insert into truck " "(worldid, truckid, packageid, location_x," "location_y, status) values('" + str(world_id) + "', '" + str(i) + "', " + '0' + ", '" + str(i) + "', '" + str(i) + "', '" + 'I' + "')") print(UConnected) db_conn.commit() UComm = world_ups_pb2.UCommands() UComm.simspeed = 50000 send_to_world(UComm, world_fd) return world_id
def return_ack(world_socket, ack): ucommands = world_ups_pb2.UCommands() ucommands.disconnect = False ucommands.acks.append(ack) #send UCommand to world send_msg(world_socket, ucommands.SerializeToString())
def PacketDrop(wSock, aSock, db): print('check seqnum table every 30s, resend all those request/ACK') while True: time.sleep(30) print('start to check ack') with db_lock: cur = db.cursor() sql = 'SELECT * FROM usend' cur.execute(sql) row = cur.fetchone() ToWorld = wupb.UCommands() ToAmazon = uapb.UCommunicate() ToWorld_empty = True ToAmazon_empty = True while row: with db_lock: # TOCHECK: distinguish what type of Msg, add to ToWorld or ToAmazon if row[2] == 'UGoPickup': print('resend UGoPickup') tp = ToWorld.pickups.add() ToWorld_empty = False elif row[2] == 'UGoDeliver': print('resend UGoDeliver') tp = ToWorld.deliveries.add() ToWorld_empty = False elif row[2] == 'UQuery': print('resend UQuery') tp = ToWorld.queries.add() ToWorld_empty = False elif row[2] == 'UOrderPlaced': print('resend UOrderPlaced') tp = ToAmazon.uorderplaced.add() ToAmazon_empty = False elif row[2] == 'UArrivedAtWarehouse': print('resend UArrivedAtwarehouse') tp = ToAmazon.uarrived.add() ToAmazon_empty = False elif row[2] == 'UPackageDelivered': print('resend UPackageDelivered') tp = ToAmazon.udelivered.add() ToAmazon_empty = False tp.ParseFromString(row[1]) row = cur.fetchone() if not ToWorld_empty: Send(wSock, ToWorld) else: print('world empty') if not ToAmazon_empty: Send(aSock, ToAmazon) else: print('amazon empty')
def disconnectWorld(socket, worldid): msgUW = wu.UCommands() msgUW.disconnect = True sendMsg(socket, msgUW) msg = recvMsg(socket, "UResponses") if msg.finished == True: print("Disconnect with World %d!" % worldid) else: print("Disconnection with World %d fails." % worldid) return msg
def loadingfinished_handler(loadingfinished_handle_list, world_id, amazon_fd, world_fd): db_conn = psycopg2.connect( "dbname='postgres' user='******' password='******'" "host='" + db_host + "' port='" + db_port + "'") db_cur = db_conn.cursor() loading_status_update(loadingfinished_handle_list, world_id, amazon_fd, world_fd) UCommands = world_ups_pb2.UCommands() #mutex.acquire() for loadingfinished in loadingfinished_handle_list: go_deliver = UCommands.deliveries.add() go_deliver.truckid = loadingfinished.truckid go_deliver.seqnum = get_seqnum() db_cur.execute("select location_x, location_y from package" " where worldid = '" + str(world_id) + "' and truckid = '" + str(go_deliver.truckid) + "' and status = 'L'") rows = db_cur.fetchall() for row in rows: package = go_deliver.packages.add() package.packageid = loadingfinished.packageid package.x = int(row[0]) package.y = int(row[1]) db_cur.execute("update package set status = 'O' " "where truckid = '" + str(go_deliver.truckid) + "' and worldid = '" + str(world_id) + "' and packageid = '" + str(package.packageid) + "'") db_conn.commit() db_cur.execute("update truck set status = 'O' " " where truckid = '" + str(go_deliver.truckid) + "' and worldid = '" + str(world_id) + "' and packageid = '" + str(package.packageid) + "'") db_conn.commit() #while True: seqnum = get_seqnum() UCommands.acks.append(seqnum) json_msg = pb2json(UCommands) db_cur.execute("""INSERT INTO world_ack (seqnum,message) VALUES(%s,%s);""", (seqnum, json.dumps(json_msg))) db_conn.commit() send_to_world(UCommands, world_fd) # if go_deliver.seqnum in world_ack_list: # break db_conn.commit() return
def orderplaced_handler(orderplaced_handle_list, world_id, amazon_fd, world_fd, truck_list): UCommands = world_ups_pb2.UCommands() UCommu = ups_amazon_pb2.UCommunicate() #mutex.acquire() package_db_handle(orderplaced_handle_list, world_id, amazon_fd, world_fd, truck_list) for i in range(0, len(orderplaced_handle_list)): UGoPickup = UCommands.pickups.add() UGoPickup.truckid = int(truck_list[i]) UGoPickup.whid = orderplaced_handle_list[i].whid UGoPickup.seqnum = get_seqnum() #edited UOrderPlaced = UCommu.uorderplaced.add() UOrderPlaced.packageid = orderplaced_handle_list[i].packageid UOrderPlaced.truckid = int(truck_list[i]) UOrderPlaced.seqnum = get_seqnum() update_truck_orderplaced(UOrderPlaced.packageid, world_id, amazon_fd, world_fd, UOrderPlaced.truckid) tmp2 = """update truck set status = 'E' where truckid = %s and worldid =%s""" db_conn = psycopg2.connect( "dbname='postgres' user='******' password='******'" "host='" + db_host + "' port='" + db_port + "'") db_cur = db_conn.cursor() db_cur.execute(tmp2, (str(UGoPickup.truckid), str(world_id))) db_conn.commit() seqnum1 = get_seqnum() UCommu.acks.append(seqnum1) json_msg = pb2json(UCommu) db_cur.execute( """INSERT INTO amazon_ack (seqnum,message) VALUES(%s,%s);""", (seqnum1, json.dumps(json_msg))) db_conn.commit() send_to_amazon(UCommu, amazon_fd) # if UOrderPlaced.seqnum in amazon_ack_list: # break #while True: seqnum2 = get_seqnum() UCommands.acks.append(seqnum2) json_msg2 = pb2json(UCommands) db_cur.execute("""INSERT INTO world_ack (seqnum,message) VALUES(%s,%s);""", (seqnum2, json.dumps(json_msg2))) db_conn.commit() send_to_world(UCommands, world_fd) # if UGoPickup.seqnum in world_ack_list: # break #mutex.release() return
def th2(self): while not self.th2_quit: if not to_send.empty(): msg = to_send.get() ucmd_msg = world_ups_pb2.UCommands() if isinstance(msg, world_ups_pb2.UCommands): send_msg_str_to_wld(msg.SerializeToString(), self.skt) else: seq = msg.seqnum if isinstance(msg, world_ups_pb2.UGoPickup): pkup = ucmd_msg.pickups.add() pkup.CopyFrom(msg) print("world th2 UGoPickup put on to_send: " + str(ucmd_msg)) elif isinstance(msg, world_ups_pb2.UGoDeliver): deli = ucmd_msg.deliveries.add() deli.CopyFrom(msg) print("world th2 UGoDeliver put on to_send: " + str(ucmd_msg)) th3_new = threading.Thread(target=self.th3, args=(ucmd_msg, seq)) th3_new.start()
def run(self): try: self.connection = psycopg2.connect(user='******', password='******', host='drona.db.elephantsql.com', port='5432', database='mqlyyayc') self.connect_to_world() # create a world self.init_truck_db() # initialize truck table # initialize sim_speed msg = world_ups_pb2.UCommands() msg.simspeed = SIM_SPEED to_send.put(msg) recv_thread = threading.Thread(target=self.th0) read_in_q_thread = threading.Thread(target=self.th1) send_thread = threading.Thread(target=self.th2) recv_thread.start() read_in_q_thread.start() send_thread.start() recv_thread.join() read_in_q_thread.join() send_thread.join() """ send_msg_to_world(connect_to_world_serial(), self.skt) connected_msg_str = self.recv_msg_str_from_world() # world_id = parse_connected_msg(connected_msg_str) # self.out_q.put(world_id) msg = world_ups_pb2.UConnected() msg.ParseFromString(connected_msg_str) print(msg) self.out_q.put(msg) while True: x = 9 """ except (Exception, psycopg2.Error) as error: print("Error while connecting to PostgreSQL", error) finally: if self.connection: self.connection.close()
def send_unack_msg_to_world(worldfd): db_conn = psycopg2.connect( "dbname='postgres' user='******' password = '******'" "host='" + db_host + "' port='" + db_port + "'") db_cur = db_conn.cursor() while True: """ get all message that haven't receive ack """ db_cur.execute("""select message from world_ack""") """send them all again""" msgs_json = db_cur.fetchall() """define json format, restore it back to Message""" for msg_json in msgs_json: """restore it back to Message and send again""" msg = world_ups_pb2.UCommands() msg = json2pb(msg, msg_json, useFieldNumber=False) _EncodeVarint(worldfd.send, len(msg.SerializeToString()), None) worldfd.sendall(msg.SerializeToString()) sleep(60)
def go_pickup(truck_id, warehouse_id, seq): global world_socket global ack_set #Combine Information ucommands = world_ups_pb2.UCommands() ucommands.disconnect = False pickup = ucommands.pickups.add() pickup.truckid = truck_id pickup.whid = warehouse_id pickup.seqnum = seq #send UCommand to world while True: send_msg(world_socket, ucommands.SerializeToString()) print("[DEBUG] Sent UCommand go pick up") time.sleep(4) print(ack_set) if seq in ack_set: print( "[DEBUG] Sent UCommand go pick up, already received by world") break print("[DEBUG] Sent UCommand go pick up, not received by world " + str(seq))
def sendAckToWorld(socketToWorld, seqnum): msgUW = wu.UCommands() #use deep copy,covered instead of appended msgUW.ack[:] = seqnum sendMsg(socketToWorld, msgUW)
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")
def send_ack_to_world(ack, world_fd): #print("sending ack to WORLD") UCommands = world_ups_pb2.UCommands() UCommands.acks.append(ack) send_to_world(UCommands, world_fd)
def go_delivery(truck_id, package_id, seq): global amazon_socket global world_socket global ack_set ucommands = world_ups_pb2.UCommands() ucommands.disconnect = False delivery = ucommands.deliveries.add() delivery.truckid = truck_id print("[DEBUG] THE truck out for delivery is " + str(truck_id)) delivery.seqnum = seq ''' ================================================== TO DO (FINISHED & TESTED): ** Package Status: created ----- in the warehouse ------- out for delivery ----- deliveried ** 1. Change the status of packageid from 2 to 3 2. Find all the packages which status are 3 and truckid is truck_id 3. Get the required information ''' # Connect to ups_package and then change the status of package_id to out for delivery conn = connect_to_database() cur = conn.cursor() cur.execute( "update ups_package set packagestatus='out for delivery' where packageid='" + str(package_id) + "'") # Find all the packages which status are 'out for delivery' and truckid is truck_id cur.execute( "select packageid, destx, desty from ups_package where truckid='" + str(truck_id) + "' and packagestatus='out for delivery'") packages = cur.fetchall() # Change the status of truck from 'arrived at warehouse' to 'delivering' cur.execute( "update ups_truck set truckstatus='delivering' where truckid='" + str(truck_id) + "'") conn.commit() cur.close() conn.close() for package in packages: delivery_location = delivery.packages.add() set_delivery_location(delivery_location, package[0], package[1], package[2]) print("[DEBUG] Finish preparation of UCommand go delivery") #send UCammand to world while True: send_msg(world_socket, ucommands.SerializeToString()) print("[DEBUG] Sent UCommand go delivery") time.sleep(4) if seq in ack_set: print( "[DEBUG] Sent UCommand go delivery, already recceived by world" ) break print("[DEBUG] Sent UCommand go delivery, not recceived by world " + str(seq))
def ProcessURes(msg, wSock, aSock, db): print('Process UResponse...') print(msg) global SeqNum toAmazonEmpty = True toWorldEmpty = True # Prepare UCommand & UCommunicate ToWorld = wupb.UCommands() ToAmazon = uapb.UCommunicate() # check for UFinished print('Looking into UFinished msg') for ufin in msg.completions: toWorldEmpty = False # Add ACK ToWorld.acks.append(ufin.seqnum) # Check ufinished status, notify amazon # first check whether this ufin has been processed before entry = Wrecvseq(db, ufin.seqnum) if entry: continue # record the seqnum from World Insertwrecv(db, ufin.seqnum) if ufin.status == 'ARRIVE WAREHOUSE': toAmazonEmpty = False print('notify amazon') arrive = ToAmazon.uarrived.add() arrive.truckid = ufin.truckid with seq_lock: arrive.seqnum = SeqNum SeqNum += 1 Insertusend(db, arrive.seqnum, arrive.SerializeToString(), 'UArrivedAtWarehouse') Truckstatus(db, ufin.truckid, 'loading') elif ufin.status == 'IDLE': print('dont need notify, notify in delivered') # update truck status in database to idle Truckstatus(db, ufin.truckid, 'idle') # check for UDeliveryMade print('Looking into UDeliveryMade Msg...') for udel in msg.delivered: toWorldEmpty = False toAmazonEmpty = False # Add ACK ToWorld.acks.append(udel.seqnum) # first check whether this udel has been processed before if Checkdelivered(db, udel.packageid): continue # send out notification email SendEmail(db, udel.packageid) # record the seqnum from World Insertwrecv(db, udel.seqnum) # update delivery status for package in db, send to amazon delivered = ToAmazon.udelivered.add() delivered.packageid = udel.packageid Packagestatus(db, udel.packageid, 'delivered') Truckamount(db, udel.truckid, False) # record this MSG in database with seq_lock: delivered.seqnum = SeqNum Insertusend(db, SeqNum, delivered.SerializeToString(), 'UPackageDelivered') SeqNum += 1 # add ack for truckstatus, if any for utruck in msg.truckstatus: toWorldEmpty = False # Add ACK ToWorld.acks.append(utruck.seqnum) UpdatePackagePos(db, utruck.truckid, utruck.x, utruck.y) # Check the acks field, delete those in UPS seqnum table for ACK in msg.acks: Deleteusend(db, ACK) # Send ACK to World & updates to Amazon if not toWorldEmpty: Send(wSock, ToWorld) if not toAmazonEmpty: Send(aSock, ToAmazon)
def ProcessARes(msg, aSock, wSock, conn): print('process aresponse') print(msg) global SeqNum toWorldEmpty = True toAmazonEmpty = True # Check the acks field, delete those in UPS seqnum table for ack in msg.acks: Deleteusend(conn, ack) # Prepare UCommand & UCommunicate ToWorld = wupb.UCommands() ToAmazon = uapb.UCommunicate() # Check for AOrderPlaced for aor in msg.aorderplaced: print('process AOrderPlace') # Select one truck from truck table truck = Findidle(conn) if truck == -1: truck = Findtruck(conn) if truck == -1: print('no truck available, ignore the order') continue # Store in amazon seqnum table exists = Arecvseq(conn, aor.seqnum) if not exists: Insertarecv(conn, aor.seqnum) else: print('process before') continue toWorldEmpty = False toAmazonEmpty = False # Add ACK ToAmazon.acks.append(aor.seqnum) # Add package in package table items = '' amount = 0 for thing in aor.things: if not items: items = thing.name else: items = items + ',' + thing.name amount += thing.count Insertpackage(conn, aor.packageid, aor.x, aor.y, 'created', items, amount, truck, aor.UPSuserid) # Add UGoPickup to ToWorld pick = ToWorld.pickups.add() pick.truckid = truck pick.whid = aor.whid with seq_lock: pick.seqnum = SeqNum SeqNum += 1 # Add UOrderplaced to toAmazon order = ToAmazon.uorderplaced.add() order.packageid = aor.packageid order.truckid = truck with seq_lock: order.seqnum = SeqNum SeqNum += 1 # Add send message to usend table Insertusend(conn, pick.seqnum, pick.SerializeToString(), 'UGoPickup') Insertusend(conn, order.seqnum, order.SerializeToString(), 'UOrderPlaced') # Update status of package and truck Truckstatus(conn, truck, 'to warehouse') Packagestatus(conn, aor.packageid, 'truck en-route to warehouse') # Check for ALoadingFinished for alod in msg.aloaded: toWorldEmpty = False toAmazonEmpty = False print('process ALoadingFinished') # Store in amazon seqnum table exists = Arecvseq(conn, alod.seqnum) if not exists: Insertarecv(conn, alod.seqnum) else: print('process before') continue # Add ACK ToAmazon.acks.append(alod.seqnum) # Update status of package & update the truck amount Packagestatus(conn, alod.packageid, 'out for delivery') Truckamount(conn, alod.truckid, True) Truckstatus(conn, alod.truckid, 'delivering') # Add UGoDeliver to ToWorld xy = Packageaddress(conn, alod.packageid) deliver = ToWorld.deliveries.add() deliver.truckid = alod.truckid package = deliver.packages.add() package.packageid = alod.packageid package.x = xy[0] package.y = xy[1] with seq_lock: deliver.seqnum = SeqNum SeqNum += 1 # Add send message to usend table Insertusend(conn, deliver.seqnum, deliver.SerializeToString(), 'UGoDeliver') # Send ACK to World & Amazon if not toAmazonEmpty: Send(aSock, ToAmazon) if not toWorldEmpty: Send(wSock, ToWorld)
def put_acks_on_tosend(acks): msg = world_ups_pb2.UCommands() for ack in acks: msg.acks.append(ack) to_send.put(msg)
def process_UResponse(UResponse, Cw, Ca, Cdb): global seqnum global whnum send_world = False send_amazon = False to_world = wupb.UCommands() to_amazon = uapb.UA_Responses() print(UResponse) for ufin in UResponse.completions: print('receive UFinished from the world') send_world = True to_world.acks.append(ufin.seqnum) print('status:' + ufin.status) if ufin.status == 'arrive warehouse' or ufin.status == 'ARRIVE WAREHOUSE': print('a truck with truck_id = ' + str(ufin.truckid) + ' has arrived at warehouse, notify Amazon') send_amazon = True to_amazon.acks.append(ufin.seqnum) UA_TruckArrived = uapb.UA_TruckArrived() UA_TruckArrived.truck_id = ufin.truckid with whnum_lock: UA_TruckArrived.whnum = whnum with seq_lock: UA_TruckArrived.seqnum = seqnum seqnum += 1 to_amazon.truckArrived.append(UA_TruckArrived) print( 'DB update: update truck status = "loading" for truck_id = ' + str(ufin.truckid)) update_truck_status(Cdb, ufin.truckid, 'loading') if ufin.status == 'idle' or ufin.status == 'IDLE': print('DB update: update truck status = "idle" for truck_id = ' + str(ufin.truckid)) update_truck_status(Cdb, ufin.truckid, 'idle') # check UDeliveryMade for udel in UResponse.delivered: print('receive UDeliveryMade from the world') send_amazon = True send_world = True # to_world.acks.append(udel.seqnum) to_world.acks.append(udel.seqnum) UA_Delivered = uapb.UA_Delivered() UA_Delivered.packageid = udel.packageid UA_Delivered.truckid = udel.truckid with seq_lock: UA_Delivered.seqnum = seqnum seqnum += 1 to_amazon.delivered.append(UA_Delivered) print( 'DB update: update package stautus = "delivered" for package_id = ' + str(udel.packageid)) update_package_status(Cdb, udel.packageid, 'delivered') print('DB update: update truck status = "idle" for truck_id = ' + str(udel.truckid)) update_truck_status(Cdb, udel.truckid, 'idle') # send_email(udel.packageid) # check UTruck for utru in UResponse.truckstatus: print('receive Utruck from the world') send_world = True to_world.acks.append(utruck.seqnum) print('DB update: update package position for truck_id = ' + str(utru.truckid) + ', new position = ' + utru.x + ',' + utru.y) update_package_pos(Cdb, utru.truckid, utru.x, utru.y) # check UErr for uerr in UResponse.error: print('receive UErr from the world') print('Erro: ' + uerr.err) print('Original seqnum: ' + str(uerr.originseqnum)) print('Current seqnum: ' + str(uerr.seqnum)) if send_world: print('to_world:') print(to_world) send_msg(Cw, to_world) if send_amazon: print('to_amazon:') print(to_amazon) send_msg(Ca, to_amazon)
def UtoA(socW, socA, db, msg): print('Receive UResponses from World...') global seqnumA # receive acks from World for ack in msg.acks: print("The ack from World is ", ack) msgUA = ua.UMessages() msgUW = wu.UCommands() sendUtoW = False sendUtoA = False # receive UFinished from World for c in msg.completions: sendUtoW = True # reply to World with acks msgUW.acks.append(c.seqnum) # send UtoACommands to Amazon # if the truck status is 'arrive warehouse' if c.status == 'ARRIVE WAREHOUSE': print("enter arrive wrhouse if") sendUtoA = True truckReady = msgUA.truckReadies.add() truckReady.truckid = c.truckid truckReady.packageid = getPackageIDFromTruckid(db, c.truckid) print("find mapping pckid is :", truckReady.packageid) # update truck status to "arrive warehouse" updateTruckStatus(db, c.truckid, "arrive warehouse") truckReady.seqnum = seqnumA mutex = threading.Lock() with mutex: seqnumA += 1 ############### Packages Database ############### #update the current package status pckid = getPackageIDFromTruckid(db, c.truckid) updatePackageStatus(db, "packing", pckid) # receive UDeliveryMade from World for d in msg.delivered: sendUtoW = True sendUtoA = True # reply to World with acks msgUW.acks.append(d.seqnum) # notyfy the amazon with pckid pckdelivered = msgUA.deliveredpackages.add() pckdelivered.packageid = d.packageid pckdelivered.seqnum = seqnumA mutex = threading.Lock() with mutex: seqnumA += 1 # update truck status to "idle" updateTruckStatus(db, d.truckid, "idle") ############### Packages Database ############### updatePackageStatus(db, "delivered", d.packageid) emailAddr = getEmailAddrFromPckid(db, d.packageid) if (emailAddr): sendEmail(emailAddr) if sendUtoW: sendMsg(socW, msgUW) if sendUtoA: sendMsg(socA, msgUA)
def generate_command(self): command = world_ups_pb2.UCommands() return command
def AtoU(socW, socA, db, worldid, msg): print("Receive Amessages from Amazon...") global seqnumW global seqnumA # receive acks from Amazon for ack in msg.acks: print("The ack from Amazon is ", ack) ##-----------Deal with ms from A---------- # prepare UMessages to Amazon msgUA = ua.UMessages() sendUtoA = False # reply to Amazon with acks for truckCommand in msg.getTrucks: print('2222') sendUtoA = True msgUA.acks.append(truckCommand.seqnum) for deliverCommand in msg.delivers: print('3333') sendUtoA = True msgUA.acks.append(deliverCommand.seqnum) if sendUtoA: print('4444') sendMsg(socA, msgUA) # prepare UCommands to World msgUW = wu.UCommands() # receive AGetTruck from Amazon hasGetTrucks = False for truckCommand in msg.getTrucks: hasGetTrucks = True print('6666') goPick = msgUW.pickups.add() goPick.truckid = findIdleTruck(db) goPick.whid = truckCommand.whid ############### Truck Database ############### # update truck status to "travelling" updateTruckStatus(db, goPick.truckid, "travelling", truckCommand.whid) goPick.seqnum = seqnumW with mutex: seqnumW += 1 ############### Packages Database ############### #make details in each packages detail = "" for product in truckCommand.product: info = str(product.count) + " X " + product.description + "\n" #+" ,productID is "+str(product.productid)+"------\n" #info=product.description detail += info #insert new entry in pakage if (truckCommand.uAccountName != ""): print(truckCommand.uAccountName) msgUA = ua.UMessages() msgUA.accountResult.packageid = truckCommand.packageid msgUA.accountResult.uAccountExists = validateUserName( db, truckCommand.uAccountName) msgUA.accountResult.uAccountName = truckCommand.uAccountName msgUA.accountResult.uAccountid = 0 msgUA.accountResult.seqnum = seqnumA with mutex: seqnumA += 1 sendMsg(socA, msgUA) #print(detail,truckCommand.packageid,truckCommand.whid,truckCommand.uAccountName,truckCommand.x,truckCommand.y) addPackage(db, detail, truckCommand.packageid, goPick.truckid, truckCommand.uAccountName, truckCommand.x, truckCommand.y) else: addPackage(db, detail, truckCommand.packageid, goPick.truckid, "", truckCommand.x, truckCommand.y) if hasGetTrucks: sendMsg(socW, msgUW) ############### Packages Database ############### #TODO: if receive ACK from world.(gettruck),should change status to on-way pckid = getPackageIDFromTruckid(db, goPick.truckid) #for p in pckid: print("the updating package is:", pckid) updatePackageStatus(db, 'truck enroute to wharehouse', pckid) # receive ADeliver from Amazon ##### TODO hasDeliver = False for deliverCommand in msg.delivers: hasDeliver = True goDeliver = msgUW.deliveries.add() goDeliver.truckid = deliverCommand.truckid # update truck status to "delivering" updateTruckStatus(db, goDeliver.truckid, "delivering") goDeliver.seqnum = seqnumW with mutex: seqnumW += 1 # generate a subtype UDeliveryLocation #for location in deliverCommand.location: currLocation = goDeliver.packages.add() ############### Packages Database ############### #need to use x, y in database currLocation.packageid = getPackageIDFromTruckid(db, goDeliver.truckid) xy = getXY(db, currLocation.packageid) currLocation.x = xy[0] currLocation.y = xy[1] ############### Packages Database ############### pckid = getPackageIDFromTruckid(db, deliverCommand.truckid) updatePackageStatus(db, "out for deliver", pckid) if hasDeliver: sendMsg(socW, msgUW)
def process_UA_Command(UA_Commands, Cw, Ca, Cdb): global seqnum global whnum to_amazon = uapb.UA_Responses() to_world = wupb.UCommands() send_amazon = False send_world = False print(UA_Commands) # print('recieve Amazon truck call') for uatru in UA_Commands.truckCall: send_world = True send_amazon = True # received UA_TruckCall from Amazon and send UCommands to world print('received UA_TruckCall from Amazon') to_amazon.acks.append(uatru.seqnum) # set up UCommands UGoPickup = to_world.pickups.add() UGoPickup.truckid = find_free_truck(Cdb) UGoPickup.whid = uatru.whnum with whnum_lock: whnum = uatru.whnum with seq_lock: UGoPickup.seqnum = seqnum seqnum += 1 # update the databse print('DB update: insert new package with package_id = ' + str(uatru.package_id) + ' and owner_id = ' + str(uatru.owner_id)) insert_package(Cdb, uatru.package_id, None, None, 'packed', UGoPickup.truckid, 'uatru.products.description', uatru.owner_id) print('DB update: update truck status = "traveling" for truck_id = ' + str(UGoPickup.truckid)) update_truck_status(Cdb, UGoPickup.truckid, 'traveling') for uagod in UA_Commands.goDeliver: send_world = True print('receive UA_GoDeliver from Amazon') to_amazon.acks.append(uagod.seqnum) UGoDeliver = to_world.deliveries.add() UGoDeliver.truckid = uagod.truckid pack = UGoDeliver.packages.add() pack.packageid = uagod.packageid pack.x = uagod.x pack.y = uagod.y with seq_lock: UGoDeliver.seqnum = seqnum seqnum += 1 print('DB update: update truck status = "delivering" for truck_id = ' + str(uagod.truckid)) update_truck_status(Cdb, uagod.truckid, 'delivering') print( 'DB update: update package status = "delivering" for package_id = ' + str(uagod.packageid)) update_package_status(Cdb, uagod.packageid, 'delivering') print('DB update: update package destination = ' + str(uagod.x) + ', ' + str(uagod.y)) update_package_dst(Cdb, uagod.packageid, uagod.x, uagod.y) if send_world: print('to_world:') print(to_world) send_msg(Cw, to_world) if send_amazon: print('to_amazon:') print(to_amazon) send_msg(Ca, to_amazon)