async def requestReceived(websocket, session, request):
	global notificationsSubscribers
	#Websockets endpoints
	if request['operation'] == 'get':
		#get endpoint
		notifications = Notification.getNotifications(session)
		response = convertToJson({'operation' : 'get', 'table' : 'Notifications', 'data' : notifications})
		await websocket.send(response)
	
	elif request['operation'] == 'subscribe':
		#subscription endpoint
		notifications = Notification.getNotifications(session)
		response = convertToJson({'operation' : 'get', 'table' : 'Notifications', 'data' : notifications})
		notificationsSubscribers.add(websocket)
		await websocket.send(response)
	
	elif request['operation'] == 'add':
		#add endpoint
		if checkArguments(request, ['title', 'message']) == False:
			print('Not all parameters were provided for ADD in Notifications')
			await websocket.send(convertToJson({'error' : 'Invalid request'}))
			return
		notification = dict_as_obj(request['data'], Notification.Notification(), ['notificationId', 'creationTime'])
		notification = Notification.addNotification(session, notification)
		response = convertToJson({'operation' : 'add', 'table' : 'Notifications', 'data' : notification})
		notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers))
		for subscriber in notificationsSubscribers:
			 await subscriber.send(response)
	
	elif request['operation'] == 'update':
		#update endpoint
		if checkArguments(request, ['notificationId']) == False:
			print('Not all parameters were provided for UPDATE in Notifications')
			await websocket.send(convertToJson({'error' : 'Invalid request'}))
			return
		data = request['data']
		notification = Notification.getNotificationsByNotificationId(session, data['notificationId'])[0]
		notification = dict_as_obj(data, notification)
		notification = Notification.updateNotification(session, notification)
		response = convertToJson({'operation' : 'update', 'table' : 'Notifications', 'data' : notification})
		notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers))
		for subscriber in notificationsSubscribers:
			 await subscriber.send(response)
	
	elif request['operation'] == 'delete':
		#delete endpoint
		if checkArguments(request, ['notificationId']) == False:
			print('Not all parameters were provided for DELETE in Notifications')
			await websocket.send(convertToJson({'error' : 'Invalid request'}))
			return
		notification = Notification.deleteNotification(session, request['data']['notificationId'])
		response = convertToJson({'operation' : 'delete', 'table' : 'Notifications', 'data' : notification})
		notificationsSubscribers = set(filter(removeClosedConnection, notificationsSubscribers))
		for subscriber in notificationsSubscribers:
			 await subscriber.send(response)
 def post(self):
     requestedArgs = getArguments(['title', 'message'])
     args = requestedArgs.parse_args()
     notification = dict_as_obj(args, Notification.Notification())
     return Notification.addNotification(self.session, notification)
Ejemplo n.º 3
0
def tick():
    global LiveVehicles
    global CurrentTick
    global VehicleTypes
    global MaxTick
    global Mon
    global LastBillTime

    TotalMonthlyCost = 0

    if (CurrentTick >= MaxTick):
        for vehicle in LiveVehicles:
            currentpos = vehicle[0]
            path = vehicle[5]
            pathindex = vehicle[6]
            endpos = vehicle[2]
            vehicleType = VehicleTypes[vehicle[1]]
            #print("Current Pos: " + str(currentpos) + "   End Pos: " + str(endpos) + "   Path Length: " + str(len(path)) + "   Path Index: " + str(pathindex))

            TotalMonthlyCost += vehicleType[4]

            #ADD GARBAGE IF NEXT TO HOUSE
            if (vehicle[4] < vehicleType[1]):
                if (Map.isHouseTile(currentpos[0] + 1, currentpos[1])
                        or Map.isHouseTile(currentpos[0] - 1, currentpos[1])
                        or Map.isHouseTile(currentpos[0], currentpos[1] - 1)
                        or Map.isHouseTile(currentpos[0], currentpos[1] + 1)):
                    #print("HOUSE NEXT TO")
                    rand = random.randint(0, RANDOM_CHANCE_OF_GARBAGE_GET)
                    if (rand == 0 and City.AmoutOfTrash >= 1):
                        vehicle[4] += 1
                        Company.Money += 10
                        City.AmoutOfTrash -= 1
                        #print("Trash: " + str(vehicle[4]) + "      CITY TRASH: " + str(City.AmoutOfTrash))

            #IF IT HAS REACHED THE END OF ITS RANDOM PATH GENERATE A NEW ONE AND DUMP TRASH IF HAS SOME
            if ((currentpos[0] == endpos[0] and currentpos[1] == endpos[1])
                    or endpos[0] == None or len(path) <= 0
                    or pathindex >= len(path)):

                #IF AT LANDFILL
                if (Map.getTile(currentpos[0],
                                currentpos[1]) == Map.TILES["landfill"]):
                    landfill = Map.Landfillgroups[Map.LandfillTiles[(
                        currentpos[0], currentpos[1])]]
                    spaceLeft = landfill[1] - landfill[0]
                    if spaceLeft >= vehicle[4]:
                        landfill[0] += vehicle[4]
                        vehicle[4] = 0
                    else:
                        landfill[0] += spaceLeft
                        vehicle[4] -= spaceLeft

                endpos = None
                path = None
                if (vehicle[4] >= vehicleType[1]):
                    newfill = getNewLandfillTarget()
                    if (newfill == None):
                        vehicle[2] = getNewRoadTarget()
                        #print("NO Landfill")
                        Notification.addNotification(
                            "Citizens worry as full garbage trucks roam the city without a landfill to go to!"
                        )
                    else:
                        vehicle[2] = newfill
                        #print("yay landfill!")
                else:
                    vehicle[2] = getNewRoadTarget()

                startpos = currentpos
                path = getPath(startpos, vehicle[2])

                if (len(path) == 0):
                    Notification.addNotification(
                        "Truck drivers begin a trip to insanity as they can't find a road to a landfill!"
                    )
                #print(path)

                vehicle[5] = path
                vehicle[6] = 0
                Map.testTruckEnd = endpos
                continue

            #SET POSIITON TO NEXT POOSITION IN PATH
            vehicle[0] = [path[pathindex][0], path[pathindex][1]]
            vehicle[6] += 1

        #MONTHLY COSTS
        currentTime = datetime.datetime.now()
        if (LastBillTime == None):
            LastBillTime = currentTime

        if ((currentTime - LastBillTime).total_seconds() >= SECONDS_PER_MONTH):
            Company.Money -= TotalMonthlyCost
            LastBillTime = currentTime

        CurrentTick = 0
    else:
        CurrentTick += 1