def get_APutOnTruck(self): acommand = amazon_pb2.ACommands() for uarrive in self.request.uarrived: pcklist = get_packageid_from_DB(uarrive.truckid, 'packed') generate_APutOnTruck(pcklist, uarrive.truckid, acommand) return acommand
def send_APutOnTruck(self): acommand = amazon_pb2.ACommands() for uarrive in self.request.uarrived: infolist = search_for_truckid(uarrive.truckid) generate_APutOnTruck(infolist, acommand) return acommand
def get_APutOnTruck(self): acommand = amazon_pb2.ACommands() for ready in self.aresponse.ready: if pck_truck_arrived(ready.shipid): truckid = get_truckid_from_DB(ready.shipid) generate_APutOnTruck([ready.shipid], truckid, acommand) return acommand
def Commands(_purchases, _simspeed=5000, _disconnect=False): command = amazon_pb2.ACommands() command.buy.extend(_purchases) # command.load.extend(_loads) # command.topack.extend(_topacks) command.simspeed = _simspeed command.disconnect = _disconnect return command
def ALoad(self, ship_id, truck_id): command = amazon_pb2.ACommands() command.simspeed = 100000 pack = command.load.add() pack.whnum = 0 pack.shipid = ship_id pack.truckid = truck_id self.send(command)
def APurchase(self, product_id, description, quantity): command = amazon_pb2.ACommands() command.simspeed = 100000 purchase = command.buy.add() purchase.whnum = 0 pid = purchase.things.add() pid.id = product_id pid.description = description pid.count = quantity self.send(command)
def AToPack(self, product_id, description, quantity, ship_id): """ ship_id should be unique per ship """ command = amazon_pb2.ACommands() command.simspeed = 100000 pack = command.topack.add() pack.whnum = 0 pack.shipid = ship_id pid = pack.things.add() pid.id = product_id pid.description = description pid.count = quantity self.send(command)
def ups_receiver(ups_socket): print("Enter UPS Receiver") myConnection = psycopg2.connect(host=DBhostname, user=DBusername, password=DBpassword, dbname=DBdatabase) cur = myConnection.cursor() while True: # truck arrived data = ups_socket.recv(1024) if len(data) <= 1: continue response = parse_ups_response(data) truck_arrive = response.resp_truck truck_id = truck_arrive.truckid whnum = truck_arrive.whnum ship_id = truck_arrive.shipid print("daemon receive ups response, truck " + str(truck_id) + " has arrived at warehouse " + str(whnum) + " for order" + str(ship_id)) # update database: arrived = True cur.execute( "update amazon_web_orders set arrive = TRUE where order_id = %s", (ship_id, )) cur.execute( "update amazon_web_orders set truck_id = %s where order_id = %s", (truck_id, ship_id)) myConnection.commit() # if ready == True, create daemon load message cur.execute("select ready from amazon_web_orders where order_id = %s", (ship_id, )) ready_list = cur.fetchall() assert (len(ready_list) == 1) ready_status = ready_list[0][0] if ready_status == True: command_msg = amazon_pb2.ACommands() to_load = command_msg.load.add() to_load.whnum = whnum to_load.truckid = truck_id to_load.shipid = ship_id print("ups ready + arrive => load", command_msg.__str__()) mutex_django.acquire(1) msg_queue.put(command_msg) mutex_django.release()
def find_ToPack(shipid): try: connection = psycopg2.connect(user=USER, password=PASSWORD, host=HOST, port=PORT, database=DATABASE) cursor = connection.cursor() # SELECT * FROM mytable WHERE "date" >= NOW() - INTERVAL '5 minutes'; #postgreSQL_select_Query = """select message from order_upsseq where time > (current_timestamp - make_interval(secs := %s))""" #intervalInSecs = 300; #print(postgreSQL_select_Query % intervalInSecs) #cursor.execute(postgreSQL_select_Query, [intervalInSecs]) postgreSQL_select_Query = """select message from order_topack where packageid = %s""" print(postgreSQL_select_Query % (shipid, )) cursor.execute(postgreSQL_select_Query, (shipid, )) print( "Selecting message from order_topack table using cursor.fetchall") records = cursor.fetchall() print("Print each row and it's columns values") cmd = None for row in records: jsonobj = row[0] cmd = protobuf_json.json2pb(amazon_pb2.ACommands(), jsonobj) break if cmd: for topack in cmd.topack: insert_ACommands_to_DB(topack.seqnum, cmd) postgreSQL_delete_Query = """delete from order_topack where packageid = %s""" #postgreSQL_delete_Query = 'delete from order_truck where "truckId" = ' + truckid cursor.execute(postgreSQL_delete_Query, (shipid, )) connection.commit() except (Exception, psycopg2.Error) as error: print("Error while fetching data from PostgreSQL", error) finally: #closing database connection. if (connection): cursor.close() connection.close() print("PostgreSQL connection is closed") return cmd
def getAPack(self, seqnum): acommand = amazon_pb2.ACommands() pckid = None for aorderplaced in self.request.aorderplaced: topack = acommand.topack.add() topack.whnum = aorderplaced.whid topack.shipid = aorderplaced.packageid pckid = topack.shipid topack.seqnum = topack.shipid * 10 + 5 for product in aorderplaced.things: thing = topack.things.add() thing.id = int(product.name) thing.description = product.description thing.count = product.count insert_APack_to_DB(pckid, acommand)
def generate_ack_response(self): seqlist = [] for i in self.aresponse.arrived: seqlist.append(i.seqnum) for i in self.aresponse.ready: seqlist.append(i.seqnum) for i in self.aresponse.loaded: seqlist.append(i.seqnum) for i in self.aresponse.error: seqlist.append(i.seqnum) for i in self.aresponse.packagestatus: seqlist.append(i.seqnum) acommand = amazon_pb2.ACommands() for ack in seqlist: acommand.acks.append(ack) return acommand
def select_timeout_from_ACommands(): try: connection = psycopg2.connect(user=USER, password=PASSWORD, host=HOST, port=PORT, database=DATABASE) cursor = connection.cursor() # SELECT * FROM mytable WHERE "date" >= NOW() - INTERVAL '1 minutes'; #postgreSQL_select_Query = """select message from order_upsseq where time > (current_timestamp - make_interval(secs := %s))""" #intervalInSecs = 300; #print(postgreSQL_select_Query % intervalInSecs) #cursor.execute(postgreSQL_select_Query, [intervalInSecs]) postgreSQL_select_Query = """select message from order_worldseq where time < %s - INTERVAL '30 second'""" print(postgreSQL_select_Query) dt = datetime.datetime.now() cursor.execute(postgreSQL_select_Query, [dt]) print("Selecting message from wareHouse table using cursor.fetchall") records = cursor.fetchall() print("Print each row and it's columns values") cmdlist = [] for row in records: jsonobj = row[0] cmd = protobuf_json.json2pb(amazon_pb2.ACommands(), jsonobj) cmdlist.append(cmd) postgreSQL_update_Query = """update order_worldseq set time = %s where time < %s - INTERVAL '30 second'""" #postgreSQL_delete_Query = 'delete from order_truck where "truckId" = ' + truckid cursor.execute(postgreSQL_update_Query, (datetime.datetime.now(), datetime.datetime.now())) connection.commit() except (Exception, psycopg2.Error) as error: print("Error while fetching data from PostgreSQL", error) finally: #closing database connection. if (connection): cursor.close() connection.close() print("PostgreSQL connection is closed") return cmdlist
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()
"msg is " + connect_msg.__str__(); sc = connect_msg.SerializeToString() size = len(sc); delimiter = protobuf_encoder._VarintBytes(size) s.send(delimiter); s.send(sc) # send msg response = amazon_pb2.AConnected() head_byte = s.recv(4) (msg_length, msg_pos) = protobuf_decoder._DecodeVarint32(head_byte, 0) print(msg_length, msg_pos) data = s.recv(msg_length) command_msg = amazon_pb2.ACommands() buy = command_msg.buy.add() buy.whnum = 0 product = buy.things.add() product.id = 123 product.description = "sample products" product.count = 10 # topack = command_msg.topack.add() # topack.whnum = 0; # topack.things # load = command_msg.load.add(); # load.whnum = 0; # load.truckid = 0; # load.shipid = 0;
def init(request): # populate database for both sim and c++/py # this part is to make the api idempotent (at most once) if Product.objects.all().exists() or Warehouse.objects.all().exists(): return render(request, 'store/cart.html', {"info": "Already inited, not doing anything."}) sim_connect = amazon_pb2.AConnect() sim_connect.worldid = WORLD sim_connect_bytes = sim_connect.SerializeToString() try: with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.settimeout(SOCKET_TIMEOUT) bytes_size = len(sim_connect_bytes) print("size is {0}".format(bytes_size)) s.connect((SIM_HOST, SIM_PORT)) varintEncoder(s.send, bytes_size) s.sendall(sim_connect_bytes) a = s.recv(1024) # handle this warehouses = [] for w in range(N_WAREHOUSES): w_local = Warehouse(x_coord=0, y_coord=0, truck_id=-1) w_local.save() warehouses.append(w_local) command_pb = amazon_pb2.ACommands() command_pb.simspeed = 40000000 command_pb.disconnect = True prod_map = {} for name, tup in PRODUCTS.items(): count, price, description = tup p_local = Product(name=name, description=description, rating=0, num_ratings=0) p_local.save() prod_map[name] = p_local for w in warehouses: purchase_pb = command_pb.buy.add() # purchase_pb = amazon_pb2.APurchaseMore() purchase_pb.whnum = w.id for name, tup in PRODUCTS.items(): count, price, description = tup i_local = Inventory(product=prod_map[name], count=count, price=price, warehouse=w) i_local.save() thing = purchase_pb.things.add() thing.id = prod_map[name].id thing.description = description thing.count = count command_pb_bytes = command_pb.SerializeToString() print(command_pb_bytes) bytes_size = len(command_pb_bytes) print("size is {0}".format(bytes_size)) varintEncoder(s.send, bytes_size) s.sendall(command_pb_bytes) a = s.recv(1024) # handle this print(a) s.close() except socket.timeout: return render( request, 'store/cart.html', {"message": "backend error: socket timed out/conn refused."}) except ConnectionRefusedError: return render( request, 'store/cart.html', {"message": "backend error: socket timed out/conn refused."}) print("done") return render(request, 'store/cart.html', {"info": "init succeeded."})
def Recv_Responses_aaa(recv_msg): 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 for product in purchaseMore.things: thing = pack.things.add() thing.id = product.id thing.description = product.description thing.count = product.count # 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 pack.shipid = randint(1,1000)# should change later print("product: id = ", product.id, " description = ", product.description, " count = ", product.count) # mutex_django.acquire(1) # msg_queue.put(command_msg) # mutex_django.release() print("Ready List: ", end='') for rdy in msg.ready: print(rdy, end=', ') print('') # for r in ready_list: # cur.execute( "UPDATE amazon_web_orders SET ready=TRUE where tracking_num = %d",r) # cur.execute("SELECT arrive from amazon_web_orders where tracking_num = %d",r) # arrive = cur.fetchall() # if len(arrive)!=1: # print("tracking_num NOT UNIQUE!") # continue; # if arrive[0].equals("False"): # print("Order "+str(r)+" is not arrived") # continue; # cur.execute("SELECT warehouse from amazon_web_orders where tracking_num = %d",r) # command_msg = amazon_pb2.ACommands(); # load = command_msg.loaded.add() # load.whnum = cur.fetchall()[0] # load.truckid = #might need to store truckid in DB print("Loaded List: ") for load in msg.loaded: print(load, end='') 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")
def __init__(self, request): self.request = request self.ac = amazon_pb2.ACommands() # generate a protocol buff self.uc = commu_pb2.ACommunicate() # generate self.deal_with_description()
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")
# Create sockets: django, warehouse, UPS socket_dj_server = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_wh_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket_ups_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Build up the connection socket_wh_client.connect((WH_HOST, WH_PORT)) # Connect socket_ups_client.connect((UPS_HOST, UPS_PORT)) # Connect to warehouse world connect_msg = amazon_pb2.AConnect() connect_msg.worldid = 1007 send_msg(socket_wh_client, connect_msg) Recv_Connected(recv_msg_4B(socket_wh_client)) # Send Default simulated speed speed = amazon_pb2.ACommands() speed.simspeed = 10000 send_msg(socket_wh_client, speed) Recv_Responses(recv_msg_4B(socket_wh_client), msg_queue, ups_queue, mutex_django, mutex_ups) # Bind port for django server socket try: socket_dj_server.bind((SELF_HOST, SELF_PORT)) except socket.error as msg: print("socket_dj bind error:", msg) socket_dj_server.listen(5) # Start new threads _thread.start_new_thread(django_receiver, (socket_dj_server, )) _thread.start_new_thread(wh_receiver, (socket_wh_client, ))
def __init__(self, request): self.request = request self.ac = amazon_pb2.ACommands() # generate a protocol buff self.uc = commu_pb2.UCommunicate() # generate
def amazonWeb(listen_socket_web, conn): global seqnum global order_id #Used to send a order-confirmation email to our customers from_addr = '*****@*****.**' server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(from_addr, r'dengliwen1997') cursor = conn.cursor() canceltable = "TRUNCATE TABLE WEBSERVER_PACKAGE;" cursor.execute(canceltable) conn.commit() while True: client_connection, client_address = listen_socket_web.accept() request = client_connection.recv(10400) # client_connection.close() print(request.decode('utf-8')) xml_request = request.decode('utf-8') Handler = web_requestHandler() parseString(xml_request, Handler) if Handler.commandtype == "buyProduct": s_command = amazon_pb2.ACommands() #offer a faster speed to our VIP customer if uni_string(Handler.vip) == "yes": s_command.simspeed = 30000 print("purchasemore vip!") else: s_command.simspeed = 1000 print("purchasemore no vip!") #assign the fields in the purchase more command buymore = s_command.buy.add() buymore.whnum = randint(1, warehouse_num) buymore.seqnum = seqnum seqnum = seqnum + 1 product = buymore.things.add() email = uni_string(Handler.email) product.id = uni_int(Handler.itemid) product.description = uni_string(Handler.description) product.count = uni_int(Handler.count) WorldMessage[buymore.seqnum] = s_command Handler.order_id = order_id sql = "UPDATE WEBSERVER_PACKAGE SET ORDER_ID = '" + str( order_id) + "' WHERE UID = '" + str(uni_string( Handler.uid)) + "';" cursor.execute(sql) conn.commit() order_id = order_id + 1 orderList.append(Handler) message = MIMEText( 'Thank you for purchasing on miniAmazon, and your order has been placed. You can check your package status anytime on our website \n\n\n\n\n miniAmazon Team', 'plain', 'utf-8') message['From'] = Header("miniAmazon", 'utf-8') message['To'] = Header("Customer", 'utf-8') subject = 'Your Order Confirmation!' message['Subject'] = Header(subject, 'utf-8') try: server.sendmail(from_addr, [email], message.as_string()) print("Email send successfully") except smtplib.SMTPException: print("Fail to send email") elif Handler.commandtype == "query": s_command = amazon_pb2.ACommands() aquery = s_command.queries.add() aquery.packageid = uni_int(Handler.packageid) aquery.seqnum = seqnum WorldMessage[seqnum] = s_command seqnum = seqnum + 1 elif Handler.commandtype == "closeWorld": s_command = amazon_pb2.ACommands() s_command.disconnect = True WorldMessage[seqnum] = s_command seqnum = seqnum + 1 client_connection.close()
def worldServer(s, conn): timeout = 3 global seqnum global ship_id global truck_packageMap global WorldMessage global package_tcknumMap global ship_truckMap global worldspeed cursor = conn.cursor() while True: #send all commands to world including new commands and the command lost in sending process if (len(WorldMessage) > 0): for key in WorldMessage.keys(): send_message(s, WorldMessage[key]) print("SEND TO WORLD with key: " + str(key)) ''' one time one time one time one time ''' worldResponse = amazon_pb2.AResponses() msg = recv_tmessage(s, timeout) if msg == "": continue worldResponse.ParseFromString(msg) #check the ack from world, and delete the message world received for i in worldResponse.acks: for key in WorldMessage.keys(): if i == key: WorldMessage.pop(i) if len(worldResponse.error) > 0: for errors in worldResponse.error: print("Error:" + errors.err) print("Error orginsequm:" + str(errors.originseqnum)) print("Error seqnum:" + str(errors.seqnum)) ack_to_world(s, errors.seqnum) #recv purchaseMore and create topack if len(worldResponse.arrived) > 0: for arrive in worldResponse.arrived: ack_to_world(s, arrive.seqnum) s_command = amazon_pb2.ACommands() apack = s_command.topack.add() apack.whnum = arrive.whnum apack.seqnum = seqnum seqnum = seqnum + 1 apack.shipid = ship_id ship_id = ship_id + 1 print("**************arrived*************") print("arrivewhnum:" + str(arrive.whnum)) for product in arrive.things: print("Product id: " + str(product.id)) print("Product description: " + str(product.description)) print("Product count: " + str(product.count)) sqlSelect = "SELECT * FROM WEBSERVER_PACKAGE WHERE PRODUCT_NAME = '" + str( product.id) + "' AND COUNT = '" + str( product.count) + "' AND DESCRIPTION = '" + str( product.description ) + "' AND PACKAGE_ID = 0 ORDER BY ORDER_ID ASC;" cursor.execute(sqlSelect) result = cursor.fetchall() uid = result[0][11] sqlupdate = "UPDATE WEBSERVER_PACKAGE SET PACKAGE_ID = '" + str( apack.shipid) + "' WHERE UID = '" + str(uid) + "';" cursor.execute(sqlupdate) conn.commit() sproduct = apack.things.add() sproduct.id = product.id sproduct.description = product.description sproduct.count = product.count for order in orderList: print("current order id: " + str(order.itemid)) print("current order description: " + str(order.description)) print("current order count: " + str(order.count)) #go to the orderlist to find the suitable order according to the world's arrived response if str(order.itemid) == str(sproduct.id) and str( order.description) == str( sproduct.description) and str( order.count) == str(sproduct.count): items = [] items.append( Item(sproduct.id, sproduct.count, sproduct.description)) packages = [] packages.append( Package(apack.shipid, uni_int(order.address_X), uni_int(order.address_Y), uni_string(order.ups_name), items)) rTruckXml = reqTruckXML(order.order_id, arrive.whnum, packages) print(rTruckXml) UPSMessage.append(rTruckXml) orderList.remove(order) #treat VIP and normal customers differently if str(order.vip) == "yes": s_command.simspeed = 30000 print("pack vip!") else: s_command.simspeed = 1000 print("pack no vip") break WorldMessage[apack.seqnum] = s_command sqlstatuspacking = "UPDATE WEBSERVER_PACKAGE SET STATUS = 'PACKING' WHERE PACKAGE_ID = '" + str( apack.shipid) + "';" cursor.execute(sqlstatuspacking) conn.commit() print("packsequm:" + str(apack.seqnum)) #create the putontruck command for UPS thread, due to only at this time, the world's response has the information we need truck_command = amazon_pb2.ACommands() truck = truck_command.load.add() truck.whnum = arrive.whnum truck.shipid = apack.shipid truck.seqnum = seqnum seqnum = seqnum + 1 putontruck_WL.append(truck_command) if len(worldResponse.ready) > 0: print("***********Now ready************") for packed in worldResponse.ready: ack_to_world(s, packed.seqnum) sqlstatuspacked = "UPDATE WEBSERVER_PACKAGE SET STATUS = 'PACKED' WHERE PACKAGE_ID = '" + str( packed.shipid) + "';" cursor.execute(sqlstatuspacked) conn.commit() print("ready shipid:" + str(packed.shipid)) print("ready seqnum:" + str(packed.seqnum)) for pot in putontruck_WL: if pot.load[0].shipid == packed.shipid: mykey = int(pot.load[0].shipid) #package packed down! #transfer the putontruck command from waitlist to really map, waiting UPShandle thread send them ship_truckMap[mykey] = pot putontruck_WL.remove(pot) if len(worldResponse.loaded) > 0: print("***********Now loaded*************") for load in worldResponse.loaded: ack_to_world(s, load.seqnum) sqlstatusdelivering = "UPDATE WEBSERVER_PACKAGE SET STATUS = 'DELIVERED' WHERE PACKAGE_ID = '" + str( load.shipid) + "';" cursor.execute(sqlstatusdelivering) conn.commit() for key in truck_packageMap.keys(): for pakid in truck_packageMap[key]: #Remove packageid from the list, UPShandle thread will know all package were loaded down if the len is 0 if int(pakid) == int(load.shipid): print("remove:" + str(pakid)) truck_packageMap[key].remove(pakid) if len(worldResponse.packagestatus) > 0: print("************Now status*************") for package in worldResponse.packagestatus: ack_to_world(s, package.seqnum) print("package id:" + str(package.packageid)) print("status:" + package.status) sqlstatus = "UPDATE WEBSERVER_PACKAGE SET STATUS = '" + package.status + "' WHERE PACKAGE_ID = '" + str( package.packageid) + "'" cursor.execute(sqlstatus) conn.commit() if worldResponse.finished == True: closeXML = "<closeWorld>\n</closeWorld>\n" print("disconnect: " + str(worldResponse.finished)) UPSMessage.append(closeXML)
def ack_to_world(s, ack): ackcommand = amazon_pb2.ACommands() ackcommand.acks.append(ack) send_message(s, ackcommand)