From b4d383d775e321e39a33ab5417c60c83ae646447 Mon Sep 17 00:00:00 2001 From: Scratchcat1 Date: Sun, 10 Dec 2017 14:12:22 +0000 Subject: [PATCH] Add files via upload --- AATC_AStar.py | 196 ++++++++++--------- AATC_Client.py | 16 +- AATC_Client_Text_UI.py | 82 ++++---- AATC_Crypto.py | 40 ++-- AATC_DB.py | 409 ++++++++++++++++++++------------------- AATC_Drone.py | 14 +- AATC_Drone_Logic.py | 66 +++---- AATC_GPIO.py | 50 ++--- AATC_Monitor.py | 16 +- AATC_Monitor_Viewer.py | 129 ++++++------ AATC_NoFlyZoneGrapher.py | 32 +-- AATC_Server_002.py | 210 ++++++++++---------- AATC_Weather.py | 4 +- HedaBot.py | 178 ++++++++--------- 14 files changed, 727 insertions(+), 715 deletions(-) diff --git a/AATC_AStar.py b/AATC_AStar.py index c1c6c9a..617d242 100644 --- a/AATC_AStar.py +++ b/AATC_AStar.py @@ -1,4 +1,4 @@ -import os,pickle,time,math,hashlib#,AATC_Coordinate +import os,pickle,time,math,hashlib,random#,AATC_Coordinate #from AATC_Coordinate import * try: try: @@ -27,56 +27,49 @@ class DynoGraph: """ def __init__(self,BlockSize = 500,FolderName = "GraphFolder",GraphFileName = "Graph",GraphFileSuffix = ".graph",BlockFileName = "GraphBlock",BlockFileSuffix = ".blk",Node_Cache_BlockSize = 40, ABInterval = 36000, ABSlot = 0, ABSlots = 2): - self.Nodes = {} - self.BlockSize = BlockSize - self.cwd = os.getcwd() - - self.GraphFileName = GraphFileName - self.GraphFileSuffix = GraphFileSuffix - self.FolderName = FolderName - self.BlockFileName = BlockFileName - self.BlockFileSuffix = BlockFileSuffix - self.Node_Cache_BlockSize = Node_Cache_BlockSize - - self.ABInterval = ABInterval - self.ABSlot = ABSlot - self.ABSlots = ABSlots + self._Nodes = {} + self._BlockSize = BlockSize + self._cwd = os.getcwd() + + self._GraphFileName = GraphFileName + self._GraphFileSuffix = GraphFileSuffix + self._FolderName = FolderName + self._BlockFileName = BlockFileName + self._BlockFileSuffix = BlockFileSuffix + self._Node_Cache_BlockSize = Node_Cache_BlockSize + + self._ABInterval = ABInterval + self._ABSlot = ABSlot + self._ABSlots = ABSlots def Size(self,xSize,ySize,zSize): - self.xSize = xSize - self.ySize = ySize - self.zSize = zSize + self._xSize = xSize + self._ySize = ySize + self._zSize = zSize def Get_Size(self): - return self.xSize, self.ySize, self.zSize + return self._xSize, self._ySize, self._zSize def add_node(self,node): - self.Nodes[node.Get_NodeID()] = node + self._Nodes[node.Get_NodeID()] = node -## def clean_edges(self): -## print("Cleaning edges...") -## for item in self.Nodes.values(): -## for num in item.Friends: -## friend = self.Nodes[num] -## if item.Get_NodeID() not in friend.Friends: -## friend.add_friend(item.Get_NodeID()) def Add_Edges(self,xRange,yRange,zRange): print("Adding edges...") - self.xCount = int(xRange/self.xSize) - self.yCount = int(yRange/self.ySize) - self.zCount = int(zRange/self.zSize) + self._xCount = int(xRange/self._xSize) + self._yCount = int(yRange/self._ySize) + self._zCount = int(zRange/self._zSize) - print("xCount:",self.xCount) - print("yCount:",self.yCount) - print("zCount:",self.zCount) + print("xCount:",self._xCount) + print("yCount:",self._yCount) + print("zCount:",self._zCount) - for node in self.Nodes.values(): - friends = self.CalculateNeighbours(node.Get_NodeID(),self.xCount,self.yCount,self.zCount) + for node in self._Nodes.values(): + friends = self.CalculateNeighbours(node.Get_NodeID(),self._xCount,self._yCount,self._zCount) for friend in friends: node.add_friend(friend) @@ -166,33 +159,33 @@ def MapHash(self,value,div): return int(value//div) def Node_Cache_Hash(self,Key): - return int(int(hashlib.md5(str(Key).encode('utf8')).hexdigest()[:8],16)%self.Node_Cache_BlockSize) #Generates integer hash of key then int div by BlockSize + return int(int(hashlib.md5(str(Key).encode('utf8')).hexdigest()[:8],16)%self._Node_Cache_BlockSize) #Generates integer hash of key then int div by BlockSize ################################## def Build_Node_Cache(self): - self.Node_Cache = {} - for node in self.Nodes.values(): - x = node.Coords.Get_X() + 0.25*self.xSize #Prevents floating point rounding errors - y = node.Coords.Get_Y() + 0.25*self.ySize - z = node.Coords.Get_Z() + 0.25*self.zSize + self._Node_Cache = {} + for node in self._Nodes.values(): + x = node.Get_Coords().Get_X() + 0.25*self._xSize #Prevents floating point rounding errors + y = node.Get_Coords().Get_Y() + 0.25*self._ySize + z = node.Get_Coords().Get_Z() + 0.25*self._zSize - mx,my,mz = self.MapHash(x,self.xSize),self.MapHash(y,self.ySize),self.MapHash(z,self.zSize) - self.Node_Cache[(mx,my,mz)] = node.Get_NodeID() + mx,my,mz = self.MapHash(x,self._xSize),self.MapHash(y,self._ySize),self.MapHash(z,self._zSize) + self._Node_Cache[(mx,my,mz)] = node.Get_NodeID() def Save_Node_Cache(self): print("Preparing to save Node Cache") Sets = {} - for Key in self.Node_Cache: + for Key in self._Node_Cache: r = self.Node_Cache_Hash(Key) #Gets Hashed key if r not in Sets: Sets[r] = {} - Sets[r][Key] = self.Node_Cache[Key] #Adds the item to the set + Sets[r][Key] = self._Node_Cache[Key] #Adds the item to the set print("Saving Node Cache. Sets:",len(Sets)) for Letter in self.GetFolderNames(): for Set in Sets: - filename = os.path.join(self.cwd,self.FolderName,Letter,self.BlockFileName+"NC"+str(Set)+self.BlockFileSuffix) + filename = os.path.join(self._cwd,self._FolderName,Letter,self._BlockFileName+"NC"+str(Set)+self._BlockFileSuffix) data = Sets[Set] with open(filename,"wb") as file: pickle.dump(data,file,protocol = pickle.HIGHEST_PROTOCOL) @@ -200,19 +193,19 @@ def Save_Node_Cache(self): def Get_Node_Cache(self,x,y,z): Key = (x,y,z) - if Key not in self.Node_Cache: + if Key not in self._Node_Cache: NCBlockID = self.Node_Cache_Hash(Key) try: - filename = os.path.join(self.cwd,self.FolderName,self.CurrentFolderName(),self.BlockFileName+"NC"+str(NCBlockID)+self.BlockFileSuffix) + filename = os.path.join(self._cwd,self._FolderName,self.CurrentFolderName(),self._BlockFileName+"NC"+str(NCBlockID)+self._BlockFileSuffix) with open(filename,"rb") as file: block = pickle.load(file) - self.Node_Cache.update(block) + self._Node_Cache.update(block) except Exception as e: print(e) - if Key in self.Node_Cache: - return self.Node_Cache[Key] + if Key in self._Node_Cache: + return self._Node_Cache[Key] else: #Raises error if cannot get node raise ValueError("Node_Cache Key requested is not in the NCBlockID checked. Check BlockSize or regenerate blockfiles.") @@ -223,7 +216,7 @@ def Direct_NodeID(self,x,y,z): def All_NodeIDs(self,StartValue = 1, MaxValue = None): if MaxValue == None: - MaxValue = self.xCount*self.yCount*self.zCount + (StartValue-1) #Gets Maximum start value, StartValue gives the starting NodeID. -1 as x*y*z = max, if start at 1 and therefore xyz +1-1 = max value. XYZ as eg x=2,y=10,z=5 you will have 100 blocks ,starting at 1 so 100 is max. + MaxValue = self._xCount*self._yCount*self._zCount + (StartValue-1) #Gets Maximum start value, StartValue gives the starting NodeID. -1 as x*y*z = max, if start at 1 and therefore xyz +1-1 = max value. XYZ as eg x=2,y=10,z=5 you will have 100 blocks ,starting at 1 so 100 is max. NodeIDList = [] for NodeID in range(1,MaxValue+1): @@ -232,12 +225,12 @@ def All_NodeIDs(self,StartValue = 1, MaxValue = None): return NodeIDList def Find_NodeID(self,x,y,z): - mx,my,mz = self.MapHash(x,self.xSize),self.MapHash(y,self.ySize),self.MapHash(z,self.zSize) + mx,my,mz = self.MapHash(x,self._xSize),self.MapHash(y,self._ySize),self.MapHash(z,self._zSize) NodeID = self.Get_Node_Cache(mx,my,mz) return NodeID def Obj_Find_NodeID(self,Obj): - x,y,z = Obj.Coords.Get_X(),Obj.Coords.Get_Y(),Obj.Coords.Get_Z() + x,y,z = Obj.Get_Coords().Get_X(),Obj.Get_Coords().Get_Y(),Obj.Get_Coords().Get_Z() NodeID = self.Find_NodeID(x,y,z) return NodeID @@ -247,17 +240,17 @@ def Obj_Find_NodeID(self,Obj): def SaveGraph(self,AutoNodeSave = True,AutoNodeCacheSave = True): print("Saving graph...") for Letter in self.GetFolderNames(): - os.makedirs(os.path.join(os.getcwd(),self.FolderName,Letter),exist_ok = True) + os.makedirs(os.path.join(os.getcwd(),self._FolderName,Letter),exist_ok = True) if AutoNodeSave: self.SaveNodes() if AutoNodeCacheSave: self.Save_Node_Cache() - self.Nodes = {} - self.Node_Cache = {} + self._Nodes = {} + self._Node_Cache = {} for Letter in self.GetFolderNames(): try: - filename = os.path.join(self.cwd,self.FolderName,Letter,self.GraphFileName+self.GraphFileSuffix) + filename = os.path.join(self._cwd,self._FolderName,Letter,self._GraphFileName+self._GraphFileSuffix) with open(filename,"wb") as file: pickle.dump(self,file,protocol = pickle.HIGHEST_PROTOCOL) print("Saved graph sucessfully") @@ -266,9 +259,9 @@ def SaveGraph(self,AutoNodeSave = True,AutoNodeCacheSave = True): def ImportGraph(self): print("Importing graph") - ABSlot = self.ABSlot + ABSlot = self._ABSlot try: - filename = os.path.join(os.getcwd(),self.FolderName,"A",self.GraphFileName+self.GraphFileSuffix) #MUST ALWAYS HAVE ATLEAST THE FOLDER "A" in order to load the configuration + filename = os.path.join(os.getcwd(),self._FolderName,"A",self._GraphFileName+self._GraphFileSuffix) #MUST ALWAYS HAVE ATLEAST THE FOLDER "A" in order to load the configuration with open(filename,"rb") as file: ImportFile = pickle.load(file) @@ -277,67 +270,76 @@ def ImportGraph(self): except Exception as e: print("An error occured while importing graph data",e) - self.cwd = os.getcwd() - self.ABSlot = ABSlot + self._cwd = os.getcwd() + self._ABSlot = ABSlot ################ def Hash(self,Value): - return int(Value//self.BlockSize) + return int(Value//self._BlockSize) def GetNode(self,NodeID): - if NodeID not in self.Nodes: + if NodeID not in self._Nodes: BlockID = self.Hash(NodeID) try: - filename = os.path.join(self.cwd,self.FolderName,self.CurrentFolderName(),self.BlockFileName+"N"+str(BlockID)+self.BlockFileSuffix) + filename = os.path.join(self._cwd,self._FolderName,self.CurrentFolderName(),self._BlockFileName+"N"+str(BlockID)+self._BlockFileSuffix) with open(filename,"rb") as file: block = pickle.load(file) - self.Nodes.update(block) + self._Nodes.update(block) except Exception as e: print(e) - if NodeID in self.Nodes: - return self.Nodes[NodeID] + if NodeID in self._Nodes: + return self._Nodes[NodeID] else: #Raises error if cannot get node raise ValueError("NodeID requested is not in the BlockID checked. Check BlockSize or regenerate blockfiles. NodeID: "+str(NodeID)) - def SaveNodes(self): + def SaveNodes(self,FolderNames = None): + if FolderNames == None: + FolderNames = self.GetFolderNames() Sets = {} - m = self.Hash(max(self.Nodes)) #Finds max blockID + m = self.Hash(max(self._Nodes)) #Finds max blockID for x in range(m+1): Sets[x] = {} #Creates sets for each block - for node in self.Nodes.values(): + for node in self._Nodes.values(): r = self.Hash(node.Get_NodeID()) Sets[r][node.Get_NodeID()] = node - for Letter in self.GetFolderNames(): + for Letter in FolderNames: for Set in Sets: #Set = BlockID if len(Sets[Set]) != 0: #If set is not empty. Empty sets may cause issues with delta Node change saving. - filename = os.path.join(self.cwd,self.FolderName,Letter,self.BlockFileName+"N"+str(Set)+self.BlockFileSuffix) + filename = os.path.join(self._cwd,self._FolderName,Letter,self._BlockFileName+"N"+str(Set)+self._BlockFileSuffix) data = Sets[Set] with open(filename,"wb") as file: pickle.dump(data,file,protocol = pickle.HIGHEST_PROTOCOL) def EvictNode(self,NodeID): #Removes a node from the Nodes dict - if NodeID in self.Nodes: - self.Nodes.pop(NodeID) + if NodeID in self._Nodes: + self._Nodes.pop(NodeID) return True else: return False + def FlushGraph(self): + self._Nodes = {} + self._Node_Cache = {} + + def Get_Nodes(self): + return self._Nodes + ####################################### def GetFolderNames(self): names = [] - for x in range(self.ABSlots): + for x in range(self._ABSlots): names.append(chr(65+x)) return names def CurrentFolderName(self): - char = chr( int(65+ ((time.time()+self.ABInterval*self.ABSlot)//self.ABInterval)%self.ABSlots)) + char = chr( int(65+ ((time.time()+self._ABInterval*self._ABSlot)//self._ABInterval)%self._ABSlots)) return char @@ -345,25 +347,25 @@ def CurrentFolderName(self): class Node: def __init__(self,NodeID,Cost,Coords): - self.NodeID = NodeID - self.Friends = [] - self.Cost = Cost - self.Coords = Coords + self._NodeID = NodeID + self._Friends = [] + self._Cost = Cost + self._Coords = Coords def add_friend(self,friend): - if friend not in self.Friends: - self.Friends.append(friend) + if friend not in self._Friends: + self._Friends.append(friend) def Get_NodeID(self): - return self.NodeID + return self._NodeID def Get_Friends(self): - return self.Friends + return self._Friends def Get_Coords(self): - return self.Coords + return self._Coords def Get_Cost(self): - return self.Cost + return self._Cost def Set_Cost(self,cost): - self.Cost = cost + self._Cost = cost def EstimateDistance(Node,Target,xSize,ySize,zSize): Node_Coords = Node.Get_Coords() @@ -494,35 +496,39 @@ def FindPath(cameFrom,current): return path[::-1] -def Benchmark(FLUSH = 100,BlockSize = 500,MAXNODE = 80000): - import random,sys - graph = DynoGraph(BlockSize= BlockSize) +def Benchmark(FLUSH = 100,MAXNODE = 80000): + graph = DynoGraph() graph.ImportGraph() Count = 1 while True: if Count % FLUSH == 0: - graph.Nodes = {} + graph.FlushGraph() a,b = random.randint(1,MAXNODE),random.randint(1,MAXNODE) print("A:",a," B:",b," Delta:",abs(a-b)) Path = AStar2(graph,a,b) - print("Path Length",len(Path)," Graph Node length",len(graph.Nodes)) + print("Path Length",len(Path)," Graph Node length",len(graph.Get_Nodes())) print("") - +def MultiBenchmark(num_proc = 4,FLUSH=100,MAXNODE=80000): + import multiprocessing + procs = [] + for x in range(num_proc): + p = multiprocessing.Process(target = Benchmark,args = (FLUSH,MAXNODE)) + p.start() + procs.append(p) def CAStarBenchmark(Random = False): graph = DynoGraph() graph.ImportGraph() if Random: - import random source = random.randint(1,80000) target = random.randint(1,80000) else: diff --git a/AATC_Client.py b/AATC_Client.py index cac2a93..7ce7ba6 100644 --- a/AATC_Client.py +++ b/AATC_Client.py @@ -53,13 +53,13 @@ def Connect(remote_ip,PORT): class UserInterface: def __init__(self,Connection): - self.con = Connection - self.Crypto = AATC_Crypto.Crypter(self.con) - self.Username = "" + self._con = Connection + self._Crypto = AATC_Crypto.Crypter(self._con) + self._Username = "" print("Welcome to the AATC connection interface") def Login(self,Username,Password): - self.Username = Username + self._Username = Username self.Send("Login",(Username,Password)) Sucess,Message,_ = self.Recv() return Sucess,Message @@ -231,19 +231,19 @@ def GetMonitorPermissionUser(self): def Exit(self): self.Send("Exit",()) Sucess,Message,_ = self.Recv() - self.con.close() + self._con.close() return Sucess,Message ############################################## ############################################## def Send(self,Code,data): - Info = self.Crypto.Encrypt(codecs.encode(str((Code,data)))) - self.con.sendall(Info) + Info = self._Crypto.Encrypt(codecs.encode(str((Code,data)))) + self._con.sendall(Info) def Recv(self): #Returns tuple of Sucess,Message,Data of which data may just be useless for that function try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) + data = self._Crypto.Decrypt(recvall.recvall(self._con)) data = ast.literal_eval(codecs.decode(data)) # Sucess, Message , Data return data[0],data[1],data[2] diff --git a/AATC_Client_Text_UI.py b/AATC_Client_Text_UI.py index dc9ba14..07706d2 100644 --- a/AATC_Client_Text_UI.py +++ b/AATC_Client_Text_UI.py @@ -47,12 +47,12 @@ class UserTextUI: def __init__(self,UserInterface,MenuOptions): - self.UserInterface = UserInterface - self.MenuOptions = MenuOptions + self._UserInterface = UserInterface + self._MenuOptions = MenuOptions def Main_Loop(self): - self.Exit = False - while not self.Exit: + self._Exit = False + while not self._Exit: try: self.PrintMainMenu() MenuChoice = self.GetMenuChoice() @@ -64,12 +64,12 @@ def Main_Loop(self): def PrintMainMenu(self): print("\n"*2) print("AATC Client Main Menu") - for x in self.MenuOptions.items(): + for x in self._MenuOptions.items(): print("{0:>3} : {1}".format(str(x[0]),x[1])) def GetMenuChoice(self): MenuChoice = -99 - while MenuChoice not in self.MenuOptions: #will exit once valid menu option is chosen + while MenuChoice not in self._MenuOptions: #will exit once valid menu option is chosen try: MenuChoice = int(input("Choice >>")) except: @@ -77,7 +77,7 @@ def GetMenuChoice(self): return MenuChoice def EvaluateChoice(self,MenuChoice): - Command = self.MenuOptions[MenuChoice] #Gets full, easier to work with string + Command = self._MenuOptions[MenuChoice] #Gets full, easier to work with string if Command == "Login": self.Login() @@ -177,31 +177,31 @@ def DisplayResults(self,Sucess,Message,Data = None): def Login(self): Username = input("Username >>") Password = input("Password >>") - Sucess,Message = self.UserInterface.Login(Username,Password) + Sucess,Message = self._UserInterface.Login(Username,Password) self.DisplayResults(Sucess,Message) ####################################### def GetNoFlyZones(self): - Sucess,Message,NoFlyZones =self.UserInterface.GetNoFlyZones() + Sucess,Message,NoFlyZones =self._UserInterface.GetNoFlyZones() self.DisplayResults(Sucess,Message,NoFlyZones) def AddNoFlyZone(self): StartCoords = input("Enter Start Coordinates in form (x,y,z) >>") EndCoords = input("Enter End Coordinates in form (x,y,z) >>") Level = int(input("Enter Level of No Fly Zone >>")) - Sucess,Message = self.UserInterface.AddNoFlyZone(StartCoords,EndCoords,Level) + Sucess,Message = self._UserInterface.AddNoFlyZone(StartCoords,EndCoords,Level) self.DisplayResults(Sucess,Message) def RemoveNoFlyZone(self): ZoneID = int(input("Enter ZoneID >>")) - Sucess,Message = self.UserInterface.RemoveNoFlyZone(ZoneID) + Sucess,Message = self._UserInterface.RemoveNoFlyZone(ZoneID) self.DisplayResults(Sucess,Message) def ModifyNoFlyZoneLevel(self): ZoneID = int(input("Enter ZoneID >>")) Level = int(input("Enter Level >>")) - Sucess,Message = self.UserInterface.ModifyNoFlyZoneLevel(ZoneID,Level) + Sucess,Message = self._UserInterface.ModifyNoFlyZoneLevel(ZoneID,Level) self.DisplayResults(Sucess,Message) @@ -214,92 +214,92 @@ def AddDrone(self): Speed = int(input("Speed (m/s) >>")) Range = int(input("Range (m) >>")) Weight = float(input("Weight (kg) >>")) - Sucess,Message = self.UserInterface.AddDrone(DroneName,DronePassword,Type,Speed,Range,Weight) + Sucess,Message = self._UserInterface.AddDrone(DroneName,DronePassword,Type,Speed,Range,Weight) self.DisplayResults(Sucess,Message) def RemoveDrone(self): DroneID = int(input("DroneID >>")) - Sucess,Message = self.UserInterface.RemoveDrone(DroneID) + Sucess,Message = self._UserInterface.RemoveDrone(DroneID) self.DisplayResults(Sucess,Message) def GetDroneID(self): DroneName = input("Drone Name >>") - Sucess,Message,DroneID = self.UserInterface.GetDroneID(DroneName) + Sucess,Message,DroneID = self._UserInterface.GetDroneID(DroneName) self.DisplayResults(Sucess,Message,DroneID) def GetDroneCredentials(self): DroneID = int(input("DroneID >>")) - Sucess,Message,Credentials = self.UserInterface.GetDroneCredentials(DroneID) + Sucess,Message,Credentials = self._UserInterface.GetDroneCredentials(DroneID) self.DisplayResults(Sucess,Message,Credentials) def SetDroneCredentials(self): DroneID = int(input("DroneID >>")) DronePassword = input("Drone Password >>") - Sucess,Message = self.UserInterface.SetDroneCredentials(DroneID,DronePassword) + Sucess,Message = self._UserInterface.SetDroneCredentials(DroneID,DronePassword) self.DisplayResults(Sucess,Message) def CheckDroneOwnership(self): UserID = int(input("UserID >>")) DroneID = int(input("DroneID >>")) - Sucess,Message,Ownership = self.UserInterface.CheckDroneOwnership(UserID,DroneID) + Sucess,Message,Ownership = self._UserInterface.CheckDroneOwnership(UserID,DroneID) self.DisplayResults(Sucess,Message,Ownership) def GetDroneInfo(self): DroneID = int(input("DroneID >>")) - Sucess,Message,DroneInfo = self.UserInterface.GetDroneInfo(DroneID) + Sucess,Message,DroneInfo = self._UserInterface.GetDroneInfo(DroneID) self.DisplayResults(Sucess,Message,DroneInfo) def GetDronesUser(self): - Sucess,Message,DroneInfo = self.UserInterface.GetDronesUser() + Sucess,Message,DroneInfo = self._UserInterface.GetDronesUser() self.DisplayResults(Sucess,Message,DroneInfo) def GetDronesAll(self): - Sucess,Message,DroneInfo = self.UserInterface.GetDronesAll() + Sucess,Message,DroneInfo = self._UserInterface.GetDronesAll() self.DisplayResults(Sucess,Message,DroneInfo) ############################################### def GetUserID(self): Username = input("Username >>") - Sucess,Message,UserID = self.UserInterface.GetUserID(Username) + Sucess,Message,UserID = self._UserInterface.GetUserID(Username) self.DisplayResults(Sucess,Message,UserID) def GetUsername(self): UserID = int(input("UserID >>")) - Sucess,Message,Username = self.UserInterface.GetUsername(UserID) + Sucess,Message,Username = self._UserInterface.GetUsername(UserID) self.DisplayResults(Sucess,Message,Username) def AddUser(self): Username = input("Username >>") Password = input("Password >>") - Sucess,Message = self.UserInterface.AddUser(Username,Password) + Sucess,Message = self._UserInterface.AddUser(Username,Password) self.DisplayResults(Sucess,Message) def SetFlightVisibility(self): Visibility = int(input("Visibility >>")) - Sucess,Message = self.UserInterface.SetFlightVisibility(Visibility) + Sucess,Message = self._UserInterface.SetFlightVisibility(Visibility) self.DisplayResults(Sucess,Message) def SetAccountType(self): Permission = input("Account Type >>") Type = int(input("Account Type VAlue >>")) - Sucess,Message = self.UserInterface.SetAccountType(Permission,Type) + Sucess,Message = self._UserInterface.SetAccountType(Permission,Type) self.DisplayResults(Sucess,Message) def UserChangePassword(self): OldPassword = input("Old Password >>") NewPassword = input("New Password >>") - Sucess,Message = self.UserInterface.UserChangePassword(OldPassword,NewPassword) + Sucess,Message = self._UserInterface.UserChangePassword(OldPassword,NewPassword) self.DisplayResults(Sucess,Message) ################################################ def GetFlightsUser(self): - Sucess,Message,UserFlights = self.UserInterface.GetFlightsUser() + Sucess,Message,UserFlights = self._UserInterface.GetFlightsUser() self.DisplayResults(Sucess,Message,UserFlights) def GetFlightsAll(self): - Sucess,Message,AllFlights = self.UserInterface.GetFlightsAll() + Sucess,Message,AllFlights = self._UserInterface.GetFlightsAll() self.DisplayResults(Sucess,Message,AllFlights) def AddFlight(self): @@ -313,35 +313,35 @@ def AddFlight(self): if point != "Done": HighPoints.append(point) StartTime = int(input("Enter start time in seconds since UNIX time >>")) - Sucess,Message,FlightInfo = self.UserInterface.AddFlight(DroneID,HighPoints,StartTime) + Sucess,Message,FlightInfo = self._UserInterface.AddFlight(DroneID,HighPoints,StartTime) self.DisplayResults(Sucess,Message,FlightInfo) def RemoveFlight(self): FlightID = int(input("FlightID >>")) - Sucess,Message = self.UserInterface.RemoveFlight(FlightID) + Sucess,Message = self._UserInterface.RemoveFlight(FlightID) self.DisplayResults(Sucess,Message) ################################################### def GetFlightWaypointsUser(self): - Sucess,Message,UserWaypoints = self.UserInterface.GetFlightWaypointsUser() + Sucess,Message,UserWaypoints = self._UserInterface.GetFlightWaypointsUser() self.DisplayResults(Sucess,Message,UserWaypoints) def GetFlightWaypointsAll(self): - Sucess,Message,AllWaypoints = self.UserInterface.GetFlightWaypointsAll() + Sucess,Message,AllWaypoints = self._UserInterface.GetFlightWaypointsAll() self.DisplayResults(Sucess,Message,AllWaypoints) ################################################### def GetMonitorID(self): MonitorName = input("MonitorName >>") - Sucess,Message,MonitorID = self.UserInterface.GetMonitorID(MonitorName) + Sucess,Message,MonitorID = self._UserInterface.GetMonitorID(MonitorName) self.DisplayResults(Sucess,Message,MonitorID) def GetMonitorName(self): MonitorID = int(input("MonitorID >>")) - Sucess,Message,MonitorName = self.UserInterface.GetMonitorName(MonitorID) + Sucess,Message,MonitorName = self._UserInterface.GetMonitorName(MonitorID) self.DisplayResults(Sucess,Message,MonitorName) ################################################## @@ -349,22 +349,22 @@ def GetMonitorName(self): def AddMonitorPermission(self): MonitorID = int(input("MonitorID >>")) ExpiryDate = int(input("Expiry Date >>")) - Sucess,Message = self.UserInterface.AddMonitorPermission(MonitorID,ExpiryDate) + Sucess,Message = self._UserInterface.AddMonitorPermission(MonitorID,ExpiryDate) self.DisplayResults(Sucess,Message) def RemoveMonitorPermission(self): MonitorID = int(input("MonitorID >>")) - Sucess,Message = self.UserInterface.RemoveMonitorPermission(MonitorID) + Sucess,Message = self._UserInterface.RemoveMonitorPermission(MonitorID) self.DisplayResults(Sucess,Message) def ModifyMonitorPermissionDate(self): MonitorID = int(input("MonitorID >>")) ExpiryDate = int(input("ExpiryDate")) - Sucess,Message = self.UserInterface.ModifyMonitorPermissionDate(MonitorID,ExpiryDate) + Sucess,Message = self._UserInterface.ModifyMonitorPermissionDate(MonitorID,ExpiryDate) self.DisplayResults(Sucess,Message) def GetMonitorPermissionUser(self): - Sucess,Message,MonitorPermissionsUser = self.UserInterface.GetMonitorPermissionUser() + Sucess,Message,MonitorPermissionsUser = self._UserInterface.GetMonitorPermissionUser() self.DisplayResults(Sucess,Message,MonitorPermissionsUser) ################################################# @@ -372,11 +372,11 @@ def GetMonitorPermissionUser(self): def Call_Exit(self): print("Exiting..") try: - Sucess,Message = self.UserInterface.Exit() + Sucess,Message = self._UserInterface.Exit() self.DisplayResults(Sucess,Message) except: print("Unable to close server connection") - self.Exit = True + self._Exit = True diff --git a/AATC_Crypto.py b/AATC_Crypto.py index d4ff52a..d620a38 100644 --- a/AATC_Crypto.py +++ b/AATC_Crypto.py @@ -1,5 +1,5 @@ #AATC crypto module -import codecs,recvall,ast,binascii,os,AATC_Config,time,AATC_CryptoBeta,socket +import codecs,recvall,ast,binascii,os,AATC_Config,AATC_CryptoBeta from Crypto.Cipher import AES,PKCS1_OAEP from Crypto.PublicKey import RSA @@ -20,23 +20,23 @@ class Crypter: """ def __init__(self, con, mode = "CLIENT",AutoGenerate = True): - self.con = con + self._con = con self.SetMode(mode) if AutoGenerate: self.GenerateKey() def SetMode(self,mode): - self.mode = mode + self._mode = mode def GenerateKey(self,key_size = AATC_Config.DEFAULT_RSA_KEYSIZE): print("Generating encryption keys. Please stand by...") #Generating keys takes a long time and have found no way to shorted key length - if self.mode == "SERVER": + if self._mode == "SERVER": self.ServerGenerateKey() - elif self.mode == "CLIENT": + elif self._mode == "CLIENT": self.ClientGenerateKey(key_size) else: raise ValueError("Crypter: Incorrect mode set") - print("Encryption keys generated",self.AESKey) + print("Encryption keys generated",self._AESKey) @@ -70,7 +70,7 @@ def ClientPreSharedKeys(self,RSA_KeySize,AES_KeySize): raise Exception("AES key size not in ALLOWED_AES_KEYSIZES. Change keysize to an allowed value") AESKey,IV = GenerateKeys(AES_KeySize) - PublicKey = AATC_CryptoBeta.VerifyCertificates(CertificateChain,AATC_Config.ROOT_CERTIFICATES,self.con) + PublicKey = AATC_CryptoBeta.VerifyCertificates(CertificateChain,AATC_Config.ROOT_CERTIFICATES,self._con) if PublicKey: @@ -120,8 +120,8 @@ def ServerGenerateKey(self): if AATC_Config.SET_ENCRYPTION_KEYS_ENABLE: self.SetEncryptionKeys(AATC_Config.SET_AES_KEY, AATC_Config.SET_IV_KEY) - self.Exit = False - while not self.Exit: + self._Exit = False + while not self._Exit: data = self.Recv() Command, Arguments = data[0],data[1] @@ -137,14 +137,14 @@ def ServerGenerateKey(self): elif Command == "Exit": Sucess,Message,Data = True,"Exiting",[] - self.Exit = True + self._Exit = True else: Sucess,Message,Data = False,"Command does not exist",[] self.Send((Sucess,Message,Data)) - if not hasattr(self,"AESKey"): #Only set if sucessfully setup. + if not hasattr(self,"_AESKey"): #Only set if sucessfully setup. raise Exception("Failure during crypter setup") @@ -178,7 +178,7 @@ def ServerSetKey(self,Arguments): self.SetEncryptionKeys(AESKey,IV) return True,"Keys set",[] else: - #self.Exit = True + #self._Exit = True return False,"AES key size not in ALLOWED_AES_KEYSIZES:"+str(AATC_Config.ALLOWED_AES_KEYSIZES),[] @@ -189,10 +189,10 @@ def ServerSetKey(self,Arguments): def SetEncryptionKeys(self,AESKey,IV): - self.AESKey = AESKey - self.IV = IV - self.EncryptAES = AES.new(self.AESKey,AES.MODE_GCM,self.IV) #Two seperate instances to encrypt and decrypt as non ECB AES is a stream cipher - self.DecryptAES = AES.new(self.AESKey,AES.MODE_GCM,self.IV) #Errors will occur if encrypt and decrypt are not equal in count. + self._AESKey = AESKey + self._IV = IV + self._EncryptAES = AES.new(self._AESKey,AES.MODE_GCM,self._IV) #Two seperate instances to encrypt and decrypt as non ECB AES is a stream cipher + self._DecryptAES = AES.new(self._AESKey,AES.MODE_GCM,self._IV) #Errors will occur if encrypt and decrypt are not equal in count. @@ -220,18 +220,18 @@ def SetEncryptionKeys(self,AESKey,IV): def Encrypt(self,data): - return self.EncryptAES.encrypt(data) + return self._EncryptAES.encrypt(data) def Decrypt(self,data): - return self.DecryptAES.decrypt(data) + return self._DecryptAES.decrypt(data) def Send(self,data): - self.con.sendall(codecs.encode(str(data))) + self._con.sendall(codecs.encode(str(data))) def Recv(self): - data = recvall.recvall(self.con) + data = recvall.recvall(self._con) data = ast.literal_eval(codecs.decode(data)) return data def SplitData(self,data): diff --git a/AATC_DB.py b/AATC_DB.py index 8ae28ea..65f0a76 100644 --- a/AATC_DB.py +++ b/AATC_DB.py @@ -43,15 +43,15 @@ class DBConnection: def __init__(self,DatabaseName = "Main.db"): print("Initializing database connection '",DatabaseName,"'") - self.db_con = sql.connect("localhost","AATC_Server","password","AATC_Database") - self.cur = self.db_con.cursor() - self.cur_header = self.db_con.cursor() + self._db_con = sql.connect("localhost","AATC_Server","password","AATC_Database") + self._cur = self._db_con.cursor() + self._cur_header = self._db_con.cursor() def Exit(self): - self.db_con.close() + self._db_con.close() def Table_Headers(self,TableName): - self.cur_header.execute("SHOW COLUMNS FROM "+ TableName) - result = self.cur_header.fetchall() + self._cur_header.execute("SHOW COLUMNS FROM "+ TableName) + result = self._cur_header.fetchall() Headers = [] for item in result: Headers.append(item[0]) #Gets Column header @@ -59,101 +59,101 @@ def Table_Headers(self,TableName): ######################## DRONE ################################ def AddDrone(self,UserID,DroneName,DronePassword,DroneType,DroneSpeed,DroneRange,DroneWeight): - self.cur.execute("SELECT 1 FROM Drone WHERE UserID = %s AND DroneName = %s",(UserID,DroneName)) - if self.cur.fetchall() == (): - self.cur.execute("INSERT INTO Drone(UserID,DroneName,DroneType,DroneSpeed,DroneRange,DroneWeight,FlightsFlown,LastCoords,LastBattery) VALUES(%s,%s,%s,%s,%s,%s,0,'(0,0,0)',0)",(UserID,DroneName,DroneType,DroneSpeed,DroneRange,DroneWeight)) + self._cur.execute("SELECT 1 FROM Drone WHERE UserID = %s AND DroneName = %s",(UserID,DroneName)) + if self._cur.fetchall() == (): + self._cur.execute("INSERT INTO Drone(UserID,DroneName,DroneType,DroneSpeed,DroneRange,DroneWeight,FlightsFlown,LastCoords,LastBattery) VALUES(%s,%s,%s,%s,%s,%s,0,'(0,0,0)',0)",(UserID,DroneName,DroneType,DroneSpeed,DroneRange,DroneWeight)) _,_,DroneID = self.GetDroneID(UserID,DroneName) DroneID = DroneID[0][0] #Sets up password in seperate table for maintainance security - self.cur.execute("INSERT INTO DroneCredentials(DroneID,DronePassword) VALUES(%s,%s)",(DroneID,DronePassword)) - self.db_con.commit() + self._cur.execute("INSERT INTO DroneCredentials(DroneID,DronePassword) VALUES(%s,%s)",(DroneID,DronePassword)) + self._db_con.commit() return True,"Added Drone" else: return False,"This drone already exists for you" def RemoveDrone(self,UserID,DroneID): - self.cur.execute("SELECT 1 FROM Drone WHERE UserID = %s AND DroneID = %s",(UserID,DroneID)) #If drone belongs to user - if self.cur.fetchall() != (): - self.cur.execute("DELETE FROM Drone WHERE DroneID = %s",(DroneID,)) - self.cur.execute("DELETE FROM DroneCredentials WHERE DroneID = %s",(DroneID,)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM Drone WHERE UserID = %s AND DroneID = %s",(UserID,DroneID)) #If drone belongs to user + if self._cur.fetchall() != (): + self._cur.execute("DELETE FROM Drone WHERE DroneID = %s",(DroneID,)) + self._cur.execute("DELETE FROM DroneCredentials WHERE DroneID = %s",(DroneID,)) + self._db_con.commit() return True,"Removed Drone" else: return False,"This drone does not exist or you do not have permission to delete this drone" def DroneCheckCredentials(self,DroneID,DronePassword): - self.cur.execute("SELECT DroneID FROM DroneCredentials WHERE DroneID = %s AND DronePassword = %s",(DroneID,DronePassword)) - DroneIDFetch = self.cur.fetchall() + self._cur.execute("SELECT DroneID FROM DroneCredentials WHERE DroneID = %s AND DronePassword = %s",(DroneID,DronePassword)) + DroneIDFetch = self._cur.fetchall() if DroneIDFetch != (): return True,"Correct Drone Credentials",DroneIDFetch[0][0] else: return False,"Incorrect Drone Credentials",-1 def DroneGetDroneInfo(self,DroneID): - self.cur.execute("SELECT * FROM Drone WHERE DroneID = %s",(DroneID,)) - return True,str(self.Table_Headers("Drone")),self.cur.fetchall() + self._cur.execute("SELECT * FROM Drone WHERE DroneID = %s",(DroneID,)) + return True,str(self.Table_Headers("Drone")),self._cur.fetchall() def GetDroneID(self,UserID,DroneName): - self.cur.execute("SELECT DroneID FROM Drone WHERE UserID = %s AND DroneName = %s",(UserID,DroneName)) - return True,"['DroneID']",self.cur.fetchall() + self._cur.execute("SELECT DroneID FROM Drone WHERE UserID = %s AND DroneName = %s",(UserID,DroneName)) + return True,"['DroneID']",self._cur.fetchall() def GetDroneCredentials(self,UserID,DroneID): - self.cur.execute("SELECT DroneCredentials.* FROM Drone,DroneCredentials WHERE Drone.UserID = %s AND Drone.DroneID = DroneCredentials.DroneID AND DroneCredentials.DroneID = %s",(UserID,DroneID)) - return True,str(self.Table_Headers("DroneCredentials")),self.cur.fetchall() + self._cur.execute("SELECT DroneCredentials.* FROM Drone,DroneCredentials WHERE Drone.UserID = %s AND Drone.DroneID = DroneCredentials.DroneID AND DroneCredentials.DroneID = %s",(UserID,DroneID)) + return True,str(self.Table_Headers("DroneCredentials")),self._cur.fetchall() def SetDroneCredentials(self,UserID,DroneID,DronePassword): - self.cur.execute("SELECT 1 FROM Drone WHERE Drone.UserID = %s AND Drone.DroneID = %s",(UserID,DroneID)) - if self.cur.fetchall() != (): - self.cur.execute("UPDATE DroneCredentials SET DronePassword = %s WHERE DroneID = %s",(DronePassword,DroneID)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM Drone WHERE Drone.UserID = %s AND Drone.DroneID = %s",(UserID,DroneID)) + if self._cur.fetchall() != (): + self._cur.execute("UPDATE DroneCredentials SET DronePassword = %s WHERE DroneID = %s",(DronePassword,DroneID)) + self._db_con.commit() return True,"Updated Drone Credentials" else: return False,"This drone does not exist or you do not have permission to change it's credentials" def CheckDroneOwnership(self,UserID,DroneID): - self.cur.execute("SELECT 1 FROM Drone WHERE UserID = %s AND DroneID = %s",(UserID,DroneID)) - return True,"['DroneOwnership']",self.cur.fetchall() + self._cur.execute("SELECT 1 FROM Drone WHERE UserID = %s AND DroneID = %s",(UserID,DroneID)) + return True,"['DroneOwnership']",self._cur.fetchall() def GetDroneInfo(self,UserID,DroneID): - self.cur.execute("SELECT DISTINCT Drone.* FROM Drone,User WHERE Drone.DroneID = %s AND (Drone.UserID = %s OR (Drone.UserID = User.UserID AND User.PublicVisibleFlights = 1))",(DroneID,UserID)) - return True,str(self.Table_Headers("Drone")),self.cur.fetchall() + self._cur.execute("SELECT DISTINCT Drone.* FROM Drone,User WHERE Drone.DroneID = %s AND (Drone.UserID = %s OR (Drone.UserID = User.UserID AND User.PublicVisibleFlights = 1))",(DroneID,UserID)) + return True,str(self.Table_Headers("Drone")),self._cur.fetchall() def GetDronesUser(self,UserID): - self.cur.execute("SELECT * FROM Drone WHERE UserID = %s",(UserID,)) - self.db_con.commit() - return True,str(self.Table_Headers("Drone")),self.cur.fetchall() + self._cur.execute("SELECT * FROM Drone WHERE UserID = %s",(UserID,)) + self._db_con.commit() + return True,str(self.Table_Headers("Drone")),self._cur.fetchall() def GetDronesAll(self): - self.cur.execute("SELECT Drone.* FROM User,Drone WHERE User.UserID = Drone.UserID AND User.PublicVisibleFlights = 1") - return True,str(self.Table_Headers("Drone")),self.cur.fetchall() + self._cur.execute("SELECT Drone.* FROM User,Drone WHERE User.UserID = Drone.UserID AND User.PublicVisibleFlights = 1") + return True,str(self.Table_Headers("Drone")),self._cur.fetchall() def UpdateDroneStatus(self,DroneID,LastCoords,LastBattery): - self.cur.execute("UPDATE Drone SET LastCoords = %s,LastBattery = %s WHERE DroneID = %s",(str(LastCoords),int(LastBattery),DroneID)) - self.db_con.commit() + self._cur.execute("UPDATE Drone SET LastCoords = %s,LastBattery = %s WHERE DroneID = %s",(str(LastCoords),int(LastBattery),DroneID)) + self._db_con.commit() return True,"Updated Drone Status" ########################## USER ############################# def GetUserID(self,Username): - self.cur.execute("SELECT UserID FROM User WHERE Username = %s",(Username,)) - return True,"['UserID']",self.cur.fetchall() + self._cur.execute("SELECT UserID FROM User WHERE Username = %s",(Username,)) + return True,"['UserID']",self._cur.fetchall() def GetUsername(self,UserID): - self.cur.execute("SELECT Username FROM User WHERE UserID = %s",(UserID,)) - return True,"['Username']",self.cur.fetchall() + self._cur.execute("SELECT Username FROM User WHERE UserID = %s",(UserID,)) + return True,"['Username']",self._cur.fetchall() def AddUser(self,Username,Password): - self.cur.execute("SELECT 1 FROM User WHERE Username = %s",(Username,)) - if self.cur.fetchall() == (): - self.cur.execute("INSERT INTO User(Username,Password,PublicVisibleFlights,PermissionAdder,ZoneCreatorPermission,ZoneRemoverPermission,ZoneModifierPermission) VALUES(%s,%s,0,0,0,0,0)",(Username,Hash(Password,Username))) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM User WHERE Username = %s",(Username,)) + if self._cur.fetchall() == (): + self._cur.execute("INSERT INTO User(Username,Password,PublicVisibleFlights,PermissionAdder,ZoneCreatorPermission,ZoneRemoverPermission,ZoneModifierPermission) VALUES(%s,%s,0,0,0,0,0)",(Username,Hash(Password,Username))) + self._db_con.commit() return True,"Added User" else: return False,"User already exists" def CheckCredentials(self,Username,Password): - self.cur.execute("SELECT UserID FROM User WHERE Username = %s AND Password = %s",(Username,Hash(Password,Username))) - UserIDFetch = self.cur.fetchall() + self._cur.execute("SELECT UserID FROM User WHERE Username = %s AND Password = %s",(Username,Hash(Password,Username))) + UserIDFetch = self._cur.fetchall() if UserIDFetch != (): return True,"Correct Credentials",UserIDFetch[0][0] else: @@ -161,8 +161,8 @@ def CheckCredentials(self,Username,Password): def SetFlightVisibility(self,UserID,Value): if Value in [0,1]: - self.cur.execute("UPDATE User SET PublicVisibleFlights = %s WHERE UserID = %s",(Value,UserID)) - self.db_con.commit() + self._cur.execute("UPDATE User SET PublicVisibleFlights = %s WHERE UserID = %s",(Value,UserID)) + self._db_con.commit() return True,"Changed PublicVisibleFlights Value" else: return False,"Invalid PublicVisibleFlights Value" @@ -170,17 +170,17 @@ def SetAccountType(self,UserID,Permission,Value): options = ["ZoneCreatorPermission","ZoneRemoverPermission","ZoneModifierPermission"] if Permission not in options: return False,"This setting does not exist. Options are :"+str(options) - self.cur.execute("UPDATE User SET "+Permission+" =%s WHERE UserID = %s AND PermissionAdder > 2",(Value,UserID)) #The string concatation is safe as only strings which are found exactly in options can be inserted and so are safe strings, cannot contain any other commands - self.db_con.commit() + self._cur.execute("UPDATE User SET "+Permission+" =%s WHERE UserID = %s AND PermissionAdder > 2",(Value,UserID)) #The string concatation is safe as only strings which are found exactly in options can be inserted and so are safe strings, cannot contain any other commands + self._db_con.commit() return True,"Set AccountType Value" def UserChangePassword(self,UserID,OldPassword,NewPassword): - self.cur.execute("SELECT Username from User WHERE UserID = ?",(UserID,)) - Username = self.cur.fetchall()[0][0] - self.cur.execute("SELECT 1 FROM User WHERE UserID = %s and Password = %s",(UserID,Hash(OldPassword,Username))) - if self.cur.fetchall() != (): - self.cur.execute("UPDATE User SET Password = %s WHERE UserID = %s",(Hash(NewPassword,Username),UserID)) - self.db_con.commit() + self._cur.execute("SELECT Username from User WHERE UserID = ?",(UserID,)) + Username = self._cur.fetchall()[0][0] + self._cur.execute("SELECT 1 FROM User WHERE UserID = %s and Password = %s",(UserID,Hash(OldPassword,Username))) + if self._cur.fetchall() != (): + self._cur.execute("UPDATE User SET Password = %s WHERE UserID = %s",(Hash(NewPassword,Username),UserID)) + self._db_con.commit() return True,"Changed password" else: return False,"Incorrect old password" @@ -188,208 +188,209 @@ def UserChangePassword(self,UserID,OldPassword,NewPassword): ##################### FLIGHT ############################## def GetFlightsUser(self,UserID): - self.cur.execute("SELECT Flight.* FROM Flight,Drone WHERE Flight.DroneID = Drone.DroneID AND Drone.UserID = %s",(UserID,)) - return True,str(self.Table_Headers("Flight")),self.cur.fetchall() + self._cur.execute("SELECT Flight.* FROM Flight,Drone WHERE Flight.DroneID = Drone.DroneID AND Drone.UserID = %s",(UserID,)) + return True,str(self.Table_Headers("Flight")),self._cur.fetchall() def GetFlightsAll(self): - self.cur.execute("SELECT Flight.* FROM Flight,Drone,User WHERE Flight.DroneID = Drone.DroneID AND Drone.UserID = User.UserID AND User.PublicVisibleFlights = 1") - return True,str(self.Table_Headers("Flight")),self.cur.fetchall() + self._cur.execute("SELECT Flight.* FROM Flight,Drone,User WHERE Flight.DroneID = Drone.DroneID AND Drone.UserID = User.UserID AND User.PublicVisibleFlights = 1") + return True,str(self.Table_Headers("Flight")),self._cur.fetchall() def AddFlight(self,UserID,DroneID,StartCoords,EndCoords,StartTime,ETA,EndTime,Distance,XOffset,YOffset,ZOffset): - self.cur.execute("SELECT 1 FROM User,Drone WHERE Drone.DroneID = %s AND Drone.UserID = %s",(DroneID,UserID)) - if self.cur.fetchall() !=(): - self.cur.execute("INSERT INTO Flight(DroneID,StartCoords,EndCoords,StartTime,ETA,EndTime,Distance,XOffset,YOffset,ZOffset,Completed) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,0)",(DroneID,str(StartCoords),str(EndCoords),int(StartTime),int(ETA),int(EndTime),int(Distance),XOffset,YOffset,ZOffset)) - self.db_con.commit() - return True,"Flight added" + self._cur.execute("SELECT 1 FROM User,Drone WHERE Drone.DroneID = %s AND Drone.UserID = %s",(DroneID,UserID)) + if self._cur.fetchall() !=(): + self._cur.execute("INSERT INTO Flight(DroneID,StartCoords,EndCoords,StartTime,ETA,EndTime,Distance,XOffset,YOffset,ZOffset,Completed) VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,0)",(DroneID,str(StartCoords),str(EndCoords),int(StartTime),int(ETA),int(EndTime),int(Distance),XOffset,YOffset,ZOffset)) + self._db_con.commit() + FlightID = self._cur.lastrowid + return True,"Flight added",FlightID else: - return False,"You do not have permission to launch this drone" + return False,"You do not have permission to launch this drone",-1 def RemoveFlight(self,UserID,FlightID): - self.cur.execute("SELECT 1 FROM Flight,Drone,User WHERE Flight.FlightID = %s AND Flight.DroneID = Drone.DroneID AND Drone.UserID = %s",(FlightID,UserID)) #If User owns this drone - if self.cur.fetchall() != (): - self.cur.execute("DELETE FROM Flight WHERE FlightID = %s",(FlightID,)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM Flight,Drone,User WHERE Flight.FlightID = %s AND Flight.DroneID = Drone.DroneID AND Drone.UserID = %s",(FlightID,UserID)) #If User owns this drone + if self._cur.fetchall() != (): + self._cur.execute("DELETE FROM Flight WHERE FlightID = %s",(FlightID,)) + self._db_con.commit() return True,"Flight Removed" else: return False,"You do not have permission to remove this flight" def CheckForFlight(self,DroneID,MaxLookAheadTime): InvalidateDelay = 1800 - self.cur.execute("SELECT FlightID FROM Flight WHERE DroneID = %s AND StartTime < (%s+%s) AND StartTime > (%s-%s) AND Completed = 0 ORDER BY StartTime ASC LIMIT 1",(DroneID,GetTime(),MaxLookAheadTime, GetTime(),InvalidateDelay)) - FlightIDFetch = self.cur.fetchall() - self.db_con.commit() + self._cur.execute("SELECT FlightID FROM Flight WHERE DroneID = %s AND StartTime < (%s+%s) AND StartTime > (%s-%s) AND Completed = 0 ORDER BY StartTime ASC LIMIT 1",(DroneID,GetTime(),MaxLookAheadTime, GetTime(),InvalidateDelay)) + FlightIDFetch = self._cur.fetchall() + self._db_con.commit() if FlightIDFetch != (): return True,"Flight is available",FlightIDFetch else: return False,"Flight is not available",[] def GetFlight(self,DroneID,FlightID): - self.cur.execute("SELECT * FROM Flight WHERE DroneID = %s AND FlightID = %s",(DroneID,FlightID)) - FlightFetch = self.cur.fetchall() + self._cur.execute("SELECT * FROM Flight WHERE DroneID = %s AND FlightID = %s",(DroneID,FlightID)) + FlightFetch = self._cur.fetchall() if FlightFetch != (): return True,str(self.Table_Headers("Flight")),FlightFetch else: return False,"Flight not obtained, Flight may not exist or you may not have permission",[] def MarkFlightComplete(self,DroneID,FlightID,Code): - self.cur.execute("SELECT 1 FROM Flight WHERE DroneID = %s AND FlightID = %s",(DroneID,FlightID)) - if self.cur.fetchall() != (): - self.cur.execute("UPDATE Flight SET Completed = %s,EndTime = %s WHERE FlightID = %s",(Code,GetTime(),FlightID)) - self.cur.execute("UPDATE Drone SET FlightsFlown = FlightsFlown +1 WHERE DroneID = %s",(DroneID,)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM Flight WHERE DroneID = %s AND FlightID = %s",(DroneID,FlightID)) + if self._cur.fetchall() != (): + self._cur.execute("UPDATE Flight SET Completed = %s,EndTime = %s WHERE FlightID = %s",(Code,GetTime(),FlightID)) + self._cur.execute("UPDATE Drone SET FlightsFlown = FlightsFlown +1 WHERE DroneID = %s",(DroneID,)) + self._db_con.commit() return True,"Marked Flight complete" else: return False,"You do not have permission to mark this flight complete" def GetCompletedFlightIDs(self,EndTimeThreshold): - self.cur.execute("SELECT FlightID FROM Flight WHERE (Completed > 0 AND (EndTime + %s) < %s) OR (EndTime+ %s) < %s",(EndTimeThreshold,GetTime(),EndTimeThreshold*3,GetTime())) - return True,"['FlightID']",self.cur.fetchall() + self._cur.execute("SELECT FlightID FROM Flight WHERE (Completed > 0 AND (EndTime + %s) < %s) OR (EndTime+ %s) < %s",(EndTimeThreshold,GetTime(),EndTimeThreshold*3,GetTime())) + return True,"['FlightID']",self._cur.fetchall() def CleanFlights(self,FlightIDList): - self.cur.executemany("DELETE FROM Flight WHERE FlightID = %s",FlightIDList) - self.db_con.commit() + self._cur.executemany("DELETE FROM Flight WHERE FlightID = %s",FlightIDList) + self._db_con.commit() return True,"Deleted completed flights above threshold" #---------------------------- FLIGHT WAYPOINT------------------------------------ def GetFlightWaypoints(self,DroneID,FlightID): - self.cur.execute("SELECT FlightWaypoints.* FROM Flight,FlightWaypoints WHERE Flight.DroneID = %s AND Flight.FlightID = FlightWaypoints.FlightID AND FlightWaypoints.FlightID = %s",(DroneID,FlightID)) - return True,str(self.Table_Headers("FlightWaypoints")),self.cur.fetchall() + self._cur.execute("SELECT FlightWaypoints.* FROM Flight,FlightWaypoints WHERE Flight.DroneID = %s AND Flight.FlightID = FlightWaypoints.FlightID AND FlightWaypoints.FlightID = %s",(DroneID,FlightID)) + return True,str(self.Table_Headers("FlightWaypoints")),self._cur.fetchall() def GetFlightWaypointsUser(self,UserID): - self.cur.execute("SELECT FlightWaypoints.* FROM FlightWaypoints,Flight,Drone WHERE FlightWaypoints.FlightID = Flight.FlightID AND Flight.DroneID = Drone.DroneID AND Drone.UserID = %s ORDER BY FlightWaypoints.FlightID, FlightWaypoints.WaypointNumber",(UserID,)) - return True,str(self.Table_Headers("FlightWaypoints")),self.cur.fetchall() + self._cur.execute("SELECT FlightWaypoints.* FROM FlightWaypoints,Flight,Drone WHERE FlightWaypoints.FlightID = Flight.FlightID AND Flight.DroneID = Drone.DroneID AND Drone.UserID = %s ORDER BY FlightWaypoints.FlightID, FlightWaypoints.WaypointNumber",(UserID,)) + return True,str(self.Table_Headers("FlightWaypoints")),self._cur.fetchall() def GetFlightWaypointsAll(self): - self.cur.execute("SELECT FlightWaypoints.* FROM FlightWaypoints,Flight,Drone,User WHERE FlightWaypoints.FlightID = Flight.FlightID AND Flight.DroneID = Drone.DroneID AND Drone.UserID = User.UserID AND User.PublicVisibleFlights = 1 ORDER BY FlightWaypoints.FlightID,FlightWaypoints.WaypointNumber") - return True,str(self.Table_Headers("FlightWaypoints")),self.cur.fetchall() + self._cur.execute("SELECT FlightWaypoints.* FROM FlightWaypoints,Flight,Drone,User WHERE FlightWaypoints.FlightID = Flight.FlightID AND Flight.DroneID = Drone.DroneID AND Drone.UserID = User.UserID AND User.PublicVisibleFlights = 1 ORDER BY FlightWaypoints.FlightID,FlightWaypoints.WaypointNumber") + return True,str(self.Table_Headers("FlightWaypoints")),self._cur.fetchall() def AddWaypoint(self,UserID,FlightID,WaypointNumber,Coords,ETA,BlockTime=0): - self.cur.execute("SELECT 1 FROM User,Flight,Drone WHERE User.UserID = %s AND User.UserID = Drone.UserID AND Drone.DroneID = Flight.DroneID AND Flight.FlightID = %s",(UserID,FlightID)) - if self.cur.fetchall() !=(): - self.cur.execute("INSERT INTO FlightWaypoints(FlightID,WaypointNumber,Coords,ETA,BlockTime) VALUES(%s,%s,%s,%s,%s)",(FlightID,WaypointNumber,str(Coords),int(ETA),BlockTime)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM User,Flight,Drone WHERE User.UserID = %s AND User.UserID = Drone.UserID AND Drone.DroneID = Flight.DroneID AND Flight.FlightID = %s",(UserID,FlightID)) + if self._cur.fetchall() !=(): + self._cur.execute("INSERT INTO FlightWaypoints(FlightID,WaypointNumber,Coords,ETA,BlockTime) VALUES(%s,%s,%s,%s,%s)",(FlightID,WaypointNumber,str(Coords),int(ETA),BlockTime)) + self._db_con.commit() return True,"Added Waypoint" else: return False,"You do not have permission to add a waypoint for this flight" def AddWaypoints(self,UserID,FlightID,Waypoints): - self.cur.execute("SELECT 1 FROM User,Flight,Drone WHERE User.UserID = %s AND User.UserID = Drone.UserID AND Drone.DroneID = Flight.DroneID AND Flight.FlightID = %s",(UserID,FlightID)) - if self.cur.fetchall() !=(): - self.cur.executemany("INSERT INTO FlightWaypoints(FlightID,WaypointNumber,Coords,ETA,BlockTime) VALUES(%s,%s,%s,%s,%s)",Waypoints) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM User,Flight,Drone WHERE User.UserID = %s AND User.UserID = Drone.UserID AND Drone.DroneID = Flight.DroneID AND Flight.FlightID = %s",(UserID,FlightID)) + if self._cur.fetchall() !=(): + self._cur.executemany("INSERT INTO FlightWaypoints(FlightID,WaypointNumber,Coords,ETA,BlockTime) VALUES(%s,%s,%s,%s,%s)",Waypoints) + self._db_con.commit() return True,"Added Waypoints" else: return False,"You do not have permission to add a waypoint for this flight" def RemoveFlightWaypoints(self,UserID,FlightID): - self.cur.execute("SELECT 1 FROM User,Flight,Drone WHERE User.UserID = %s AND User.UserID = Drone.UserID AND Drone.DroneID = Flight.DroneID AND Flight.FlightID = %s",(UserID,FlightID)) - if self.cur.fetchall() !=(): - self.cur.execute("DELETE FROM FlightWaypoints WHERE FlightID = %s",(FlightID,)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM User,Flight,Drone WHERE User.UserID = %s AND User.UserID = Drone.UserID AND Drone.DroneID = Flight.DroneID AND Flight.FlightID = %s",(UserID,FlightID)) + if self._cur.fetchall() !=(): + self._cur.execute("DELETE FROM FlightWaypoints WHERE FlightID = %s",(FlightID,)) + self._db_con.commit() return True,"Deleted waypoint" else: return False,"You do not have permission to delete these waypoints" def CleanCompletedFlightWaypoints(self,FlightID): #Server only command - self.cur.execute("DELETE FROM FlightWaypoints WHERE FlightID = %s",(FlightID,)) - self.db_con.commit() + self._cur.execute("DELETE FROM FlightWaypoints WHERE FlightID = %s",(FlightID,)) + self._db_con.commit() return True,"Deleted waypoints" ########################### MONITOR ################################## def AddMonitor(self,MonitorName,MonitorPassword): - self.cur.execute("SELECT 1 FROM Monitor WHERE MonitorName = %s",(MonitorName,)) - if self.cur.fetchall() == (): - self.cur.execute("INSERT INTO Monitor(MonitorName,MonitorPassword) VALUES(%s,%s)",(MonitorName,Hash(MonitorPassword,MonitorName))) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM Monitor WHERE MonitorName = %s",(MonitorName,)) + if self._cur.fetchall() == (): + self._cur.execute("INSERT INTO Monitor(MonitorName,MonitorPassword,AccountType) VALUES(%s,%s,'Default')",(MonitorName,Hash(MonitorPassword,MonitorName))) + self._db_con.commit() return True,"Added Monitor" else: return False,"Monitor already exists" def MonitorCheckCredentials(self,MonitorName,MonitorPassword): - self.cur.execute("SELECT MonitorID FROM Monitor WHERE MonitorName = %s AND MonitorPassword = %s",(MonitorName,Hash(MonitorPassword,MonitorName))) - MonitorIDFetch = self.cur.fetchall() + self._cur.execute("SELECT MonitorID FROM Monitor WHERE MonitorName = %s AND MonitorPassword = %s",(MonitorName,Hash(MonitorPassword,MonitorName))) + MonitorIDFetch = self._cur.fetchall() if MonitorIDFetch != (): return True,"Correct Credentials",MonitorIDFetch[0][0] else: return False,"Incorrect Credentials",-1 def MonitorChangePassword(self,MonitorID,OldPassword,NewPassword): - self.cur.execute("SELECT MonitorName FROM Monitor WHERE MonitorID = ?",(MonitorID,)) - MonitorName = self.cur.fetchall()[0][0] - self.cur.execute("SELECT 1 FROM Monitor WHERE MonitorID = %s AND MonitorPassword = %s",(MonitorID,Hash(OldPassword,MonitorName))) - if self.cur.fetchall() != (): - self.cur.execute("UPDATE Monitor SET MonitorPassword = %s WHERE MonitorID = %s",(Hash(NewPassword,MonitorName),MonitorID)) - self.db_con.commit() + self._cur.execute("SELECT MonitorName FROM Monitor WHERE MonitorID = ?",(MonitorID,)) + MonitorName = self._cur.fetchall()[0][0] + self._cur.execute("SELECT 1 FROM Monitor WHERE MonitorID = %s AND MonitorPassword = %s",(MonitorID,Hash(OldPassword,MonitorName))) + if self._cur.fetchall() != (): + self._cur.execute("UPDATE Monitor SET MonitorPassword = %s WHERE MonitorID = %s",(Hash(NewPassword,MonitorName),MonitorID)) + self._db_con.commit() return True,"Password updated" else: return False, "Incorrect old password" def GetMonitorDrones(self,MonitorID): - self.cur.execute("SELECT Drone.* FROM Drone,MonitorPermission WHERE Drone.UserID = MonitorPermission.UserID and MonitorPermission.MonitorID = %s",(MonitorID,)) - self.db_con.commit() - return True,str(self.Table_Headers("Drone")),self.cur.fetchall() + self._cur.execute("SELECT Drone.* FROM Drone,MonitorPermission WHERE Drone.UserID = MonitorPermission.UserID and MonitorPermission.MonitorID = %s",(MonitorID,)) + self._db_con.commit() + return True,str(self.Table_Headers("Drone")),self._cur.fetchall() def GetMonitorFlights(self,MonitorID): - self.cur.execute("SELECT Flight.* FROM Flight,Drone,MonitorPermission WHERE Flight.DroneID = Drone.DroneID AND Drone.UserID = MonitorPermission.UserID and MonitorPermission.MonitorID = %s",(MonitorID,)) - self.db_con.commit() - return True,str(self.Table_Headers("Flight")),self.cur.fetchall() + self._cur.execute("SELECT Flight.* FROM Flight,Drone,MonitorPermission WHERE Flight.DroneID = Drone.DroneID AND Drone.UserID = MonitorPermission.UserID and MonitorPermission.MonitorID = %s",(MonitorID,)) + self._db_con.commit() + return True,str(self.Table_Headers("Flight")),self._cur.fetchall() def GetMonitorFlightWaypoints(self,MonitorID): - self.cur.execute("SELECT FlightWaypoints.* FROM FlightWaypoints,Flight,Drone,MonitorPermission WHERE FlightWaypoints.FlightID = Flight.FlightID AND Flight.DroneID = Drone.DroneID AND Drone.UserID = MonitorPermission.UserID and MonitorPermission.MonitorID = %s",(MonitorID,)) - self.db_con.commit() - return True,str(self.Table_Headers("FlightWaypoints")),self.cur.fetchall() + self._cur.execute("SELECT FlightWaypoints.* FROM FlightWaypoints,Flight,Drone,MonitorPermission WHERE FlightWaypoints.FlightID = Flight.FlightID AND Flight.DroneID = Drone.DroneID AND Drone.UserID = MonitorPermission.UserID and MonitorPermission.MonitorID = %s",(MonitorID,)) + self._db_con.commit() + return True,str(self.Table_Headers("FlightWaypoints")),self._cur.fetchall() def GetMonitorID(self,MonitorName): - self.cur.execute("SELECT MonitorID FROM Monitor WHERE MonitorName = %s",(MonitorName,)) - result = self.cur.fetchall() + self._cur.execute("SELECT MonitorID FROM Monitor WHERE MonitorName = %s",(MonitorName,)) + result = self._cur.fetchall() if len(result) != 0: Sucess = True else: Sucess = False return Sucess,"['MonitorID']",result def GetMonitorName(self,MonitorID): - self.cur.execute("SELECT MonitorName FROM Monitor WHERE MonitorID = %s",(MonitorID,)) - return True,"['MonitorName']",self.cur.fetchall() + self._cur.execute("SELECT MonitorName FROM Monitor WHERE MonitorID = %s",(MonitorID,)) + return True,"['MonitorName']",self._cur.fetchall() #-------------------------- MONITOR PERMISSION ------------------------------------ def AddMonitorPermission(self,UserID,MonitorID,ExpiryDate): - self.cur.execute("SELECT 1 FROM MonitorPermission WHERE UserID = %s AND MonitorID = %s",(UserID,MonitorID)) - if self.cur.fetchall() ==(): - self.cur.execute("INSERT INTO MonitorPermission(MonitorID,UserID,LastAccessed,ExpiryDate) VALUES (%s,%s,%s,%s)",(MonitorID,UserID,0,ExpiryDate)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM MonitorPermission WHERE UserID = %s AND MonitorID = %s",(UserID,MonitorID)) + if self._cur.fetchall() ==(): + self._cur.execute("INSERT INTO MonitorPermission(MonitorID,UserID,LastAccessed,ExpiryDate) VALUES (%s,%s,%s,%s)",(MonitorID,UserID,0,ExpiryDate)) + self._db_con.commit() return True,"Sucessfully added MonitorPermission" else: return False,"MonitorPermission already exists" def RemoveMonitorPermission(self,UserID,MonitorID): - self.cur.execute("DELETE FROM MonitorPermission WHERE UserID = %s AND MonitorID = %s",(UserID,MonitorID)) - self.db_con.commit() + self._cur.execute("DELETE FROM MonitorPermission WHERE UserID = %s AND MonitorID = %s",(UserID,MonitorID)) + self._db_con.commit() return True,"Deleted MonitorPermission" def ModifyMonitorPermissionDate(self,UserID,MonitorID,NewDate): - self.cur.execute("UPDATE MonitorPermission SET ExpiryDate = %s WHERE UserID = %s AND MonitorID = %s",(NewDate,UserID,MonitorID)) - self.db_con.commit() + self._cur.execute("UPDATE MonitorPermission SET ExpiryDate = %s WHERE UserID = %s AND MonitorID = %s",(NewDate,UserID,MonitorID)) + self._db_con.commit() return True,"Updated Date for MonitorPermission" def GetMonitorPermissionUser(self,UserID): - self.cur.execute("SELECT * FROM MonitorPermission WHERE UserID = %s",(UserID,)) + self._cur.execute("SELECT * FROM MonitorPermission WHERE UserID = %s",(UserID,)) Headers = self.Table_Headers("MonitorPermission") - return True,str(Headers),self.cur.fetchall() + return True,str(Headers),self._cur.fetchall() def GetMonitorPermissionMonitor(self,MonitorID): - self.cur.execute("SELECT * FROM MonitorPermission WHERE MonitorID = %s",(MonitorID,)) + self._cur.execute("SELECT * FROM MonitorPermission WHERE MonitorID = %s",(MonitorID,)) Headers = self.Table_Headers("MonitorPermission") - return True,str(Headers),self.cur.fetchall() + return True,str(Headers),self._cur.fetchall() def UpdateMonitorPermissionLastAccessed(self,UserID,MonitorID,NewDate = None): if NewDate == None: NewDate = GetTime() - self.cur.execute("UPDATE MonitorPermission SET LastAccessed = %s WHERE MonitorID = %s AND UserID = %s",(NewDate,MonitorID,UserID)) - self.db_con.commit() + self._cur.execute("UPDATE MonitorPermission SET LastAccessed = %s WHERE MonitorID = %s AND UserID = %s",(NewDate,MonitorID,UserID)) + self._db_con.commit() return True,"Updated LastAccessed" def CleanMonitorPermissions(self): - self.cur.execute("DELETE FROM MonitorPermission WHERE ExpiryDate < %s",(GetTime(),)) - self.db_con.commit() + self._cur.execute("DELETE FROM MonitorPermission WHERE ExpiryDate < %s",(GetTime(),)) + self._db_con.commit() return True,"Cleaned Monitor Permission" @@ -401,19 +402,19 @@ def AddNoFlyZone(self,Coord1,Coord2,Level,UserID): else: if type(Level) is not int or Level <= 0: return False, "Invalid Level. Must be an integer and > 0" - self.cur.execute("SELECT 1 FROM User WHERE UserID = %s AND ZoneCreatorPermission =1",(UserID,)) - if self.cur.fetchall() != (): - self.cur.execute("INSERT INTO NoFlyZone(StartCoord,EndCoord,Level,OwnerUserID) VALUES(%s,%s,%s,%s)",(str(Coord1),str(Coord2),Level,UserID)) - self.db_con.commit() + self._cur.execute("SELECT 1 FROM User WHERE UserID = %s AND ZoneCreatorPermission =1",(UserID,)) + if self._cur.fetchall() != (): + self._cur.execute("INSERT INTO NoFlyZone(StartCoord,EndCoord,Level,OwnerUserID) VALUES(%s,%s,%s,%s)",(str(Coord1),str(Coord2),Level,UserID)) + self._db_con.commit() return True,"Sucessfully added NoFlyZone" else: return False,"You do not have ZoneCreator Permission" def RemoveNoFlyZone(self,UserID,ZoneID): - self.cur.execute("SELECT 1 FROM NoFlyZone,User WHERE (NoFlyZone.ZoneID = %s AND NoFlyZone.OwnerUserID = %s ) OR (User.UserID = %s AND User.ZoneRemoverPermission = 1)",(ZoneID,UserID,UserID)) # Gets 1 if (Zone with ZoneID has UserID as owner) OR (User with UserID has ZoneRemoverPermission) - if self.cur.fetchall() != (): + self._cur.execute("SELECT 1 FROM NoFlyZone,User WHERE (NoFlyZone.ZoneID = %s AND NoFlyZone.OwnerUserID = %s ) OR (User.UserID = %s AND User.ZoneRemoverPermission = 1)",(ZoneID,UserID,UserID)) # Gets 1 if (Zone with ZoneID has UserID as owner) OR (User with UserID has ZoneRemoverPermission) + if self._cur.fetchall() != (): #Runs if user has permission to delete this no fly zone - self.cur.execute("DELETE FROM NoFlyZone WHERE ZoneID = %s",(ZoneID,)) - self.db_con.commit() + self._cur.execute("DELETE FROM NoFlyZone WHERE ZoneID = %s",(ZoneID,)) + self._db_con.commit() return True,"Sucessfully deleted NoFlyZone" else: return False,"You do not own this NoFlyZone or you do not have the ZoneRemoverPermission" #Replace String permission with max no fly zone level permission @@ -422,66 +423,66 @@ def RemoveNoFlyZone(self,UserID,ZoneID): def ModifyNoFlyZoneLevel(self,UserID,ZoneID,Level): if type(Level) is not int or Level <=0: return False,"Invalid Level. Must be an integer and > 0" - self.cur.execute("SELECT 1 FROM NoFlyZone,User WHERE (NoFlyZone.ZoneID = %s AND NoFlyZone.OwnerUserID = %s ) OR (User.UserID = %s AND User.ZoneModifierPermission = 1)",(ZoneID,UserID,UserID)) # Gets 1 if (Zone with ZoneID has UserID as owner) OR (User with UserID has ZoneModifier Permission) - if self.cur.fetchall() != (): + self._cur.execute("SELECT 1 FROM NoFlyZone,User WHERE (NoFlyZone.ZoneID = %s AND NoFlyZone.OwnerUserID = %s ) OR (User.UserID = %s AND User.ZoneModifierPermission = 1)",(ZoneID,UserID,UserID)) # Gets 1 if (Zone with ZoneID has UserID as owner) OR (User with UserID has ZoneModifier Permission) + if self._cur.fetchall() != (): #Runs if user has permission to delete this no fly zone - self.cur.execute("UPDATE NoFlyZone SET Level = %s WHERE ZoneID = %s",(Level,ZoneID)) - self.db_con.commit() + self._cur.execute("UPDATE NoFlyZone SET Level = %s WHERE ZoneID = %s",(Level,ZoneID)) + self._db_con.commit() return True,"Sucessfully modified NoFlyZone" else: return False,"You do not own this NoFlyZone or you do not have the ZoneModifier Permission" #Replace String permission with max no fly zone level permission def GetNoFlyZones(self): - self.cur.execute("SELECT * FROM NoFlyZone") + self._cur.execute("SELECT * FROM NoFlyZone") Headers = self.Table_Headers("NoFlyZone") #Gets Headers of table to be sent as message - return True,str(Headers),self.cur.fetchall() + return True,str(Headers),self._cur.fetchall() ########################################################################### ################## InputStack ################################# def Bot_addValue(self,value,chat_id): - self.cur.execute("SELECT MAX(stack_pos) FROM InputStack WHERE chat_id = %s",(chat_id,)) - result = self.cur.fetchall() + self._cur.execute("SELECT MAX(stack_pos) FROM InputStack WHERE chat_id = %s",(chat_id,)) + result = self._cur.fetchall() if not result[0][0] == None: stack_pos = result[0][0] +1 else: stack_pos = 0 - self.cur.execute("INSERT INTO InputStack VALUES(%s,%s,%s)",(chat_id,stack_pos,value)) - self.db_con.commit() + self._cur.execute("INSERT INTO InputStack VALUES(%s,%s,%s)",(chat_id,stack_pos,value)) + self._db_con.commit() def Bot_getCommand(self,chat_id): - self.cur.execute("SELECT value FROM InputStack WHERE chat_id = %s AND stack_pos = 0",(chat_id,)) - result = self.cur.fetchall() + self._cur.execute("SELECT value FROM InputStack WHERE chat_id = %s AND stack_pos = 0",(chat_id,)) + result = self._cur.fetchall() return result[0][0] def Bot_getStack(self,chat_id): - self.cur.execute("SELECT value FROM InputStack WHERE chat_id = %s ORDER BY stack_pos ASC",(chat_id,)) - result = self.cur.fetchall() + self._cur.execute("SELECT value FROM InputStack WHERE chat_id = %s ORDER BY stack_pos ASC",(chat_id,)) + result = self._cur.fetchall() return result def Bot_getStackSize(self,chat_id): - self.cur.execute("SELECT COUNT(1) FROM InputStack WHERE chat_id = %s",(chat_id,)) - result = self.cur.fetchall() + self._cur.execute("SELECT COUNT(1) FROM InputStack WHERE chat_id = %s",(chat_id,)) + result = self._cur.fetchall() return result[0][0] def Bot_flushStack(self,chat_id): - self.cur.execute("DELETE FROM InputStack WHERE chat_id = %s",(chat_id,)) - self.db_con.commit() + self._cur.execute("DELETE FROM InputStack WHERE chat_id = %s",(chat_id,)) + self._db_con.commit() ################################################################## ####################### Sessions ########################## def Bot_SetUserID(self,chat_id,UserID): - self.cur.execute("SELECT 1 FROM Sessions WHERE chat_id = %s",(chat_id,)) - if len(self.cur.fetchall()) == 0: - self.cur.execute("INSERT INTO Sessions VALUES(%s,%s)",(chat_id,UserID)) + self._cur.execute("SELECT 1 FROM Sessions WHERE chat_id = %s",(chat_id,)) + if len(self._cur.fetchall()) == 0: + self._cur.execute("INSERT INTO Sessions VALUES(%s,%s)",(chat_id,UserID)) else: - self.cur.execute("UPDATE Sessions SET UserID = %s WHERE chat_id = %s",(UserID,chat_id)) - self.db_con.commit() + self._cur.execute("UPDATE Sessions SET UserID = %s WHERE chat_id = %s",(UserID,chat_id)) + self._db_con.commit() def Bot_GetUserID(self,chat_id): - self.cur.execute("SELECT UserID FROM Sessions WHERE chat_id = %s",(chat_id,)) - result = self.cur.fetchall() + self._cur.execute("SELECT UserID FROM Sessions WHERE chat_id = %s",(chat_id,)) + result = self._cur.fetchall() if len(result) == 0: return -1 else: @@ -490,25 +491,25 @@ def Bot_GetUserID(self,chat_id): ########################################################################## def ResetDatabase(self): - self.cur.execute("SET FOREIGN_KEY_CHECKS = 0") + self._cur.execute("SET FOREIGN_KEY_CHECKS = 0") TABLES = ["User","Drone","Monitor","MonitorPermission","Flight","FlightWaypoints","NoFlyZone","DroneCredentials","InputStack","Sessions"] for item in TABLES: - self.cur.execute("DROP TABLE IF EXISTS {0}".format(item)) + self._cur.execute("DROP TABLE IF EXISTS {0}".format(item)) - self.cur.execute("CREATE TABLE User(UserID INTEGER PRIMARY KEY AUTO_INCREMENT, Username TEXT,Password TEXT, PublicVisibleFlights INT, PermissionAdder INT , ZoneCreatorPermission INT, ZoneRemoverPermission INT,ZoneModifierPermission INT)") - self.cur.execute("CREATE TABLE Drone(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT, UserID INT, DroneName TEXT, DroneType TEXT, DroneSpeed INT, DroneRange INT, DroneWeight REAL, FlightsFlown INT, LastCoords TEXT, LastBattery REAL)") - self.cur.execute("CREATE TABLE Monitor(MonitorID INTEGER PRIMARY KEY AUTO_INCREMENT, MonitorName TEXT, MonitorPassword TEXT)") - self.cur.execute("CREATE TABLE MonitorPermission(MonitorID INT ,UserID INT, LastAccessed TEXT, ExpiryDate TEXT,PRIMARY KEY(MonitorID,UserID),FOREIGN KEY(MonitorID) REFERENCES Monitor(MonitorID))") - self.cur.execute("CREATE TABLE Flight(FlightID INTEGER PRIMARY KEY AUTO_INCREMENT, DroneID INT, StartCoords TEXT, EndCoords TEXT, StartTime REAL, ETA REAL, EndTime REAL, Distance REAL,XOffset REAL , YOffset REAL , ZOffset REAL,Completed INT)") - self.cur.execute("CREATE TABLE FlightWaypoints(FlightID INT, WaypointNumber INT, Coords TEXT, ETA REAL, BlockTime INT)") - self.cur.execute("CREATE TABLE NoFlyZone(ZoneID INTEGER PRIMARY KEY AUTO_INCREMENT, StartCoord TEXT, EndCoord TEXT, Level INT, OwnerUserID INT)") - self.cur.execute("CREATE TABLE DroneCredentials(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT ,DronePassword TEXT)") - - self.cur.execute("CREATE TABLE InputStack(chat_id INT , stack_pos INT, value TEXT)") - self.cur.execute("CREATE TABLE Sessions(chat_id INT PRIMARY KEY, UserID INT)") + self._cur.execute("CREATE TABLE User(UserID INTEGER PRIMARY KEY AUTO_INCREMENT, Username TEXT,Password TEXT, PublicVisibleFlights INT, PermissionAdder INT , ZoneCreatorPermission INT, ZoneRemoverPermission INT,ZoneModifierPermission INT)") + self._cur.execute("CREATE TABLE Drone(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT, UserID INT, DroneName TEXT, DroneType TEXT, DroneSpeed INT, DroneRange INT, DroneWeight REAL, FlightsFlown INT, LastCoords TEXT, LastBattery REAL)") + self._cur.execute("CREATE TABLE Monitor(MonitorID INTEGER PRIMARY KEY AUTO_INCREMENT, MonitorName TEXT, MonitorPassword TEXT)") + self._cur.execute("CREATE TABLE MonitorPermission(MonitorID INT ,UserID INT, LastAccessed TEXT, ExpiryDate TEXT,PRIMARY KEY(MonitorID,UserID),FOREIGN KEY(MonitorID) REFERENCES Monitor(MonitorID))") + self._cur.execute("CREATE TABLE Flight(FlightID INTEGER PRIMARY KEY AUTO_INCREMENT, DroneID INT, StartCoords TEXT, EndCoords TEXT, StartTime REAL, ETA REAL, EndTime REAL, Distance REAL,XOffset REAL , YOffset REAL , ZOffset REAL,Completed INT)") + self._cur.execute("CREATE TABLE FlightWaypoints(FlightID INT, WaypointNumber INT, Coords TEXT, ETA REAL, BlockTime INT)") + self._cur.execute("CREATE TABLE NoFlyZone(ZoneID INTEGER PRIMARY KEY AUTO_INCREMENT, StartCoord TEXT, EndCoord TEXT, Level INT, OwnerUserID INT)") + self._cur.execute("CREATE TABLE DroneCredentials(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT ,DronePassword TEXT)") + + self._cur.execute("CREATE TABLE InputStack(chat_id INT , stack_pos INT, value TEXT)") + self._cur.execute("CREATE TABLE Sessions(chat_id INT PRIMARY KEY, UserID INT)") - self.cur.execute("SET FOREIGN_KEY_CHECKS = 1") - self.db_con.commit() + self._cur.execute("SET FOREIGN_KEY_CHECKS = 1") + self._db_con.commit() @@ -516,11 +517,11 @@ def ResetDatabase(self): #Code of stuff with foriegn keys, not used as causes trouble and has no advantage -####self.cur.execute("CREATE TABLE User(UserID INTEGER PRIMARY KEY AUTO_INCREMENT, Username TEXT,Password TEXT, PublicVisibleFlights INT, AccountType TEXT)") -####self.cur.execute("CREATE TABLE Drone(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT, UserID INT, DroneName TEXT, DroneType TEXT, DroneSpeed INT, DroneRange INT, DroneWeight REAL, FlightsFlown INT, LastCoords TEXT, LastBattery REAL,FOREIGN KEY(UserID) REFERENCES User(UserID))") -####self.cur.execute("CREATE TABLE Monitor(MonitorID INTEGER PRIMARY KEY AUTO_INCREMENT, MonitorName TEXT, MonitorPassword TEXT,AccountType TEXT)") -####self.cur.execute("CREATE TABLE MonitorPermission(MonitorID INT ,UserID INT, LastAccessed TEXT, ExpiryDate TEXT,PRIMARY KEY(MonitorID,UserID),FOREIGN KEY(MonitorID) REFERENCES Monitor(MonitorID),FOREIGN KEY(UserID) REFERENCES User(UserID))") -####self.cur.execute("CREATE TABLE Flight(FlightID INTEGER PRIMARY KEY AUTO_INCREMENT, DroneID INT, StartCoords TEXT, EndCoords TEXT, StartTime REAL, ETA REAL, EndTime REAL, Distance REAL,XOffset REAL , YOffset REAL , ZOffset REAL,Completed INT,FOREIGN KEY(DroneID) REFERENCES Drone(DroneID))") -####self.cur.execute("CREATE TABLE FlightWaypoints(FlightID INT, WaypointNumber INT, Coords TEXT, ETA REAL, BlockTime INT ,FOREIGN KEY(FlightID) REFERENCES Flight(FlightID))") -####self.cur.execute("CREATE TABLE NoFlyZone(ZoneID INTEGER PRIMARY KEY AUTO_INCREMENT, StartCoord TEXT, EndCoord TEXT, Level INT, OwnerUserID INT,FOREIGN KEY(OwnerUserID) REFERENCES User(UserID))") -####self.cur.execute("CREATE TABLE DroneCredentials(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT ,DronePassword TEXT,FOREIGN KEY(DroneID) REFERENCES Drone(DroneID))") +####self._cur.execute("CREATE TABLE User(UserID INTEGER PRIMARY KEY AUTO_INCREMENT, Username TEXT,Password TEXT, PublicVisibleFlights INT, AccountType TEXT)") +####self._cur.execute("CREATE TABLE Drone(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT, UserID INT, DroneName TEXT, DroneType TEXT, DroneSpeed INT, DroneRange INT, DroneWeight REAL, FlightsFlown INT, LastCoords TEXT, LastBattery REAL,FOREIGN KEY(UserID) REFERENCES User(UserID))") +####self._cur.execute("CREATE TABLE Monitor(MonitorID INTEGER PRIMARY KEY AUTO_INCREMENT, MonitorName TEXT, MonitorPassword TEXT,AccountType TEXT)") +####self._cur.execute("CREATE TABLE MonitorPermission(MonitorID INT ,UserID INT, LastAccessed TEXT, ExpiryDate TEXT,PRIMARY KEY(MonitorID,UserID),FOREIGN KEY(MonitorID) REFERENCES Monitor(MonitorID),FOREIGN KEY(UserID) REFERENCES User(UserID))") +####self._cur.execute("CREATE TABLE Flight(FlightID INTEGER PRIMARY KEY AUTO_INCREMENT, DroneID INT, StartCoords TEXT, EndCoords TEXT, StartTime REAL, ETA REAL, EndTime REAL, Distance REAL,XOffset REAL , YOffset REAL , ZOffset REAL,Completed INT,FOREIGN KEY(DroneID) REFERENCES Drone(DroneID))") +####self._cur.execute("CREATE TABLE FlightWaypoints(FlightID INT, WaypointNumber INT, Coords TEXT, ETA REAL, BlockTime INT ,FOREIGN KEY(FlightID) REFERENCES Flight(FlightID))") +####self._cur.execute("CREATE TABLE NoFlyZone(ZoneID INTEGER PRIMARY KEY AUTO_INCREMENT, StartCoord TEXT, EndCoord TEXT, Level INT, OwnerUserID INT,FOREIGN KEY(OwnerUserID) REFERENCES User(UserID))") +####self._cur.execute("CREATE TABLE DroneCredentials(DroneID INTEGER PRIMARY KEY AUTO_INCREMENT ,DronePassword TEXT,FOREIGN KEY(DroneID) REFERENCES Drone(DroneID))") diff --git a/AATC_Drone.py b/AATC_Drone.py index bc7b026..60e3890 100644 --- a/AATC_Drone.py +++ b/AATC_Drone.py @@ -23,17 +23,17 @@ class DroneInterface: Eg calculate trip distance and get range*battery, if not enough, wait and charge. """ def __init__(self,Connection): - self.con = Connection - self.Crypto = AATC_Crypto.Crypter(self.con) - self.DroneName = "" + self._con = Connection + self._Crypto = AATC_Crypto.Crypter(self._con) + self._DroneName = "" print("Welcome to the AATC Connection interface") def Send(self,Code,data): - Info = self.Crypto.Encrypt(codecs.encode(str((Code,data)))) - self.con.sendall(Info) + Info = self._Crypto.Encrypt(codecs.encode(str((Code,data)))) + self._con.sendall(Info) def Recv(self): #Returns tuple of Sucess,Message,Data of which data may just be useless for that function try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) + data = self._Crypto.Decrypt(recvall.recvall(self._con)) data = ast.literal_eval(codecs.decode(data)) # Sucess, Message , Data return data[0],data[1],data[2] @@ -90,7 +90,7 @@ def MarkFlightComplete(self,FlightID,Code): def Exit(self): self.Send("Exit",()) Sucess,Message,_ = self.Recv() - self.con.close() + self._con.close() return Sucess,Message diff --git a/AATC_Drone_Logic.py b/AATC_Drone_Logic.py index 55b654e..06f97be 100644 --- a/AATC_Drone_Logic.py +++ b/AATC_Drone_Logic.py @@ -3,47 +3,47 @@ class DroneLogicSystem: def __init__(self,DroneID,DronePassword,FlightQueue,StatusQueue,GPIO_Queue,Sleep_Time = 30): - self.DroneID = DroneID - self.DronePassword = DronePassword - self.FlightQueue = FlightQueue - self.StatusQueue = StatusQueue - self.GPIO_Queue = GPIO_Queue - self.Sleep_Time = Sleep_Time + self._DroneID = DroneID + self._DronePassword = DronePassword + self._FlightQueue = FlightQueue + self._StatusQueue = StatusQueue + self._GPIO_Queue = GPIO_Queue + self._Sleep_Time = Sleep_Time def Main(self): Exit = False InFlight = False while not Exit: try: - self.D = AATC_Drone.CreateDroneInterface(IP = "127.0.0.1") - LoginSucess,Message = self.D.Login(self.DroneID,self.DronePassword) + self._D = AATC_Drone.CreateDroneInterface(IP = "127.0.0.1") + LoginSucess,Message = self._D.Login(self._DroneID,self._DronePassword) if LoginSucess: if not InFlight: AATC_GPIO.GPIO_Wait_Switch(26,Indicator_Pin = 13) print("Entering Flight Check Mode") - self.GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.Pattern,( [(21,1,5),(21,0,1)],)))) #Let the Thread for the GREEN LED blink on pin 21 at 0.5 Hz for 1 cycle repeatedly until stopped + self._GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.Pattern,( [(21,1,5),(21,0,1)],)))) #Let the Thread for the GREEN LED blink on pin 21 at 0.5 Hz for 1 cycle repeatedly until stopped self.CheckForFlight() - self.D.Exit() + self._D.Exit() InFlight = True else: print("Entering Run Flight Mode") - self.GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.Blink,(21,0.5,1,True)))) #Let the Thread for the GREEN LED blink on pin 21 at 0.5 Hz for 1 cycle repeatedly until stopped + self._GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.Blink,(21,0.5,1,True)))) #Let the Thread for the GREEN LED blink on pin 21 at 0.5 Hz for 1 cycle repeatedly until stopped self.RunFlight() InFlight = False #Once RunFlight has completed sucessfully go back to checking for flights. Will only complete once finished, if crashes will not pass here. - self.D.Exit() - self.GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.BlankFunction,()))) # Resets the green LED to be off. + self._D.Exit() + self._GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.BlankFunction,()))) # Resets the green LED to be off. else: - self.GPIO_Queue.put(("RED","Function",(AATC_GPIO.Blink,(11,1,10,False)))) #Let the Thread for RED LED blink on pin 11 at 1Hz 10 times and not repeat. + self._GPIO_Queue.put(("RED","Function",(AATC_GPIO.Blink,(11,1,10,False)))) #Let the Thread for RED LED blink on pin 11 at 1Hz 10 times and not repeat. print("Login failure",Message) - time.sleep(self.Sleep_Time) #To prevent spamming server + time.sleep(self._Sleep_Time) #To prevent spamming server except Exception as e: print("Error occured in DroneLogic Main",e) - self.GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.BlankFunction,()))) - self.GPIO_Queue.put(("RED","Function",(AATC_GPIO.Blink,(11,3,30,False)))) #Let the Thread for RED LED blink on pin 11 at 3Hz 30 times and not repeat. - time.sleep(self.Sleep_Time) #To prevent spamming server + self._GPIO_Queue.put(("GREEN","Function",(AATC_GPIO.BlankFunction,()))) + self._GPIO_Queue.put(("RED","Function",(AATC_GPIO.Blink,(11,3,30,False)))) #Let the Thread for RED LED blink on pin 11 at 3Hz 30 times and not repeat. + time.sleep(self._Sleep_Time) #To prevent spamming server @@ -52,39 +52,39 @@ def CheckForFlight(self): AvailableFlight = False while not AvailableFlight: - if not self.StatusQueue.empty(): #Updates status - Status = self.StatusQueue.get() - self.StatusQueue.task_done() - self.D.UpdateDroneStatus(Status["Coords"],Status["Battery"])#dfjsafkdsajdfjs + if not self._StatusQueue.empty(): #Updates status + Status = self._StatusQueue.get() + self._StatusQueue.task_done() + self._D.UpdateDroneStatus(Status["Coords"],Status["Battery"])#dfjsafkdsajdfjs - Sucess,Message,FlightID = self.D.CheckForFlight() + Sucess,Message,FlightID = self._D.CheckForFlight() AvailableFlight = Sucess - time.sleep(self.Sleep_Time) #At the end to pause to wait so that if the server is still writing waypoints it can finish. + time.sleep(self._Sleep_Time) #At the end to pause to wait so that if the server is still writing waypoints it can finish. FlightID = FlightID[0][0] print("Obtaining flight and drone information. FlightID :",FlightID) - DroneInfo, Flight, Waypoints = GetAllFlightInfo(self.D,self.DroneID,FlightID) + DroneInfo, Flight, Waypoints = GetAllFlightInfo(self._D,self._DroneID,FlightID) - self.FlightQueue.put((False,(DroneInfo,Flight,Waypoints))) + self._FlightQueue.put((False,(DroneInfo,Flight,Waypoints))) def RunFlight(self): complete = False while not complete: #While drone not at target location - while self.StatusQueue.empty(): - time.sleep(self.Sleep_Time) + while self._StatusQueue.empty(): + time.sleep(self._Sleep_Time) - Status = self.StatusQueue.get() - self.StatusQueue.task_done() + Status = self._StatusQueue.get() + self._StatusQueue.task_done() - Sucess,Message = self.D.UpdateDroneStatus(Status["Coords"],Status["Battery"]) + Sucess,Message = self._D.UpdateDroneStatus(Status["Coords"],Status["Battery"]) if "MarkComplete" in Status: complete = True print("Flight ",Status["MarkComplete"]," complete") - Sucess,Message = self.D.MarkFlightComplete(Status["MarkComplete"],1) + Sucess,Message = self._D.MarkFlightComplete(Status["MarkComplete"],1) print("Sucess",Sucess," Message:",Message) - time.sleep(self.Sleep_Time) + time.sleep(self._Sleep_Time) diff --git a/AATC_GPIO.py b/AATC_GPIO.py index 0883dcf..9b5da9a 100644 --- a/AATC_GPIO.py +++ b/AATC_GPIO.py @@ -1,9 +1,10 @@ import threading,multiprocessing,queue,time,random, sys try: import RPi.GPIO as GPIO + ENABLE_GPIO = True except: print("No RPi.GPIO module available. Features depending on this will not work/crash") - + ENABLE_GPIO = False #GPIO.setmode(GPIO.BOARD) ##GPIO.setup(11, GPIO.OUT) #red @@ -12,7 +13,8 @@ ##GPIO.setup(26, GPIO.IN) #button def GPIO_Wait_Switch(pin,wait_time = 1, SWITCH_MODE= 1, Indicator_Pin = False): # Will wait for pin to switch to the SWITCH_MODE setting. If not will sleep for wait_time seconds. - if "GPIO" not in sys.modules: # If does not have GPIO will automatically pass through. + #if "GPIO" in sys.modules: # If does not have GPIO will automatically pass through. + if ENABLE_GPIO: GPIO.setmode(GPIO.BOARD) GPIO.setup(pin,GPIO.IN) @@ -60,18 +62,18 @@ def GPIO_Thread(Thread_Name,GPIO_Queue): class Thread_Handle: def __init__(self,Thread_Name,ThreadPointer,Queue): - self.Thread_Name = Thread_Name - self.ThreadPointer = ThreadPointer - self.Queue = Queue + self._Thread_Name = Thread_Name + self._ThreadPointer = ThreadPointer + self._Queue = Queue def Get_Thread_Name(self): - return self.Thread_Name + return self._Thread_Name def Get_ThreadPointer(self): - return self.ThreadPointer + return self._ThreadPointer def Get_Queue(self): - return self.Queue + return self._Queue @@ -80,12 +82,12 @@ def Get_Queue(self): class Thread_Controller: def __init__(self,Command_Queue,Name = ""): print("Creating Thread Controller",Name) - self.Name ="TC"+ Name + " >" - self.Command_Queue = Command_Queue - self.Threads = {} + self._Name ="TC"+ Name + " >" + self._Command_Queue = Command_Queue + self._Threads = {} def Create_Thread(self,Thread_Name,TargetCommand = GPIO_Thread,TargetArgs = (),Process = False): #If Process is True, will use a Process rather than a thread. - if Thread_Name in self.Threads: #Close thread if already exists + if Thread_Name in self._Threads: #Close thread if already exists self.Close_Thread(Thread_Name) if Process: @@ -94,27 +96,27 @@ def Create_Thread(self,Thread_Name,TargetCommand = GPIO_Thread,TargetArgs = (),P else: Thread_Queue = queue.Queue() threadPointer = threading.Thread(target = TargetCommand,args = (Thread_Name,Thread_Queue)+TargetArgs) - self.Threads[Thread_Name] = Thread_Handle(Thread_Name,threadPointer,Thread_Queue) + self._Threads[Thread_Name] = Thread_Handle(Thread_Name,threadPointer,Thread_Queue) threadPointer.start() def Close_Thread(self,Thread_Name): - ClosingThreadHandle = self.Threads.pop(Thread_Name) + ClosingThreadHandle = self._Threads.pop(Thread_Name) Queue = ClosingThreadHandle.Get_Queue() Queue.put(("Exit",())) - print(self.Name,"GPIO Controller closed Thread",Thread_Name) + print(self._Name,"GPIO Controller closed Thread",Thread_Name) return ClosingThreadHandle #Returns Thread_Handle of thread def PassData(self,Thread_Name,Data): - Queue = self.Threads[Thread_Name].Get_Queue() + Queue = self._Threads[Thread_Name].Get_Queue() Queue.put(Data) def Main(self): Exit = False while not Exit: try: - Request = self.Command_Queue.get() #(Thread_Name/Controller command,"Command",Args) - self.Command_Queue.task_done() + Request = self._Command_Queue.get() #(Thread_Name/Controller command,"Command",Args) + self._Command_Queue.task_done() if Request[0] == "Controller": Command,Args = Request[1],Request[2] @@ -126,7 +128,7 @@ def Main(self): self.Close_Thread(*Args) elif Command == "Exit": #Shutdown everything self.Reset(*Args) - self.Exit = True + self._Exit = True elif Command == "Reset": #Shutdown all threads, not controller self.Reset(*Args) @@ -135,13 +137,13 @@ def Main(self): except Exception as e: - print(self.Name,"Error in GPIO_Thread_Controller",e) - print(self.Name,"Shutting down") + print(self._Name,"Error in GPIO_Thread_Controller",e) + print(self._Name,"Shutting down") def Reset(self,Wait_Join = False): - print(self.Name,"Reseting GPIO Threading Controller...") - Thread_Names = list(self.Threads.keys()) + print(self._Name,"Reseting GPIO Threading Controller...") + Thread_Names = list(self._Threads.keys()) ThreadHandles = [] for Thread_Name in Thread_Names: ClosingThreadHandle = self.Close_Thread(Thread_Name) @@ -152,7 +154,7 @@ def Reset(self,Wait_Join = False): ThreadPointer = ThreadHandle.Get_ThreadPointer() ThreadPointer.join() - print(self.Name,"Reset GPIO Threading Controller") + print(self._Name,"Reset GPIO Threading Controller") diff --git a/AATC_Monitor.py b/AATC_Monitor.py index 3f7f32d..0551591 100644 --- a/AATC_Monitor.py +++ b/AATC_Monitor.py @@ -13,17 +13,17 @@ class MonitorInterface: These two sets are accessed seperatly. """ def __init__(self,Connection): - self.con = Connection - self.Crypto = AATC_Crypto.Crypter(self.con) - self.MonitorName = "" + self._con = Connection + self._Crypto = AATC_Crypto.Crypter(self._con) + self._MonitorName = "" print("Welcome to the AATC Connection interface") def Send(self,Code,data): - Info = self.Crypto.Encrypt(codecs.encode(str((Code,data)))) - self.con.sendall(Info) + Info = self._Crypto.Encrypt(codecs.encode(str((Code,data)))) + self._con.sendall(Info) def Recv(self): #Returns tuple of Sucess,Message,Data of which data may just be useless for that function try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) + data = self._Crypto.Decrypt(recvall.recvall(self._con)) data = ast.literal_eval(codecs.decode(data)) # Sucess, Message , Data return data[0],data[1],data[2] @@ -37,7 +37,7 @@ def Recv(self): #Returns tuple of Sucess,Message,Data of which data may just ############################## def Login(self,MonitorName,MonitorPassword): - self.MonitorName = MonitorName + self._MonitorName = MonitorName self.Send("Login",(MonitorName,MonitorPassword)) Sucess,Message,_ = self.Recv() return Sucess,Message @@ -120,7 +120,7 @@ def GetFlightWaypointsAll(self): def Exit(self): self.Send("Exit",()) Sucess,Message,_ = self.Recv() - self.con.close() + self._con.close() return Sucess,Message diff --git a/AATC_Monitor_Viewer.py b/AATC_Monitor_Viewer.py index 95b7d8b..b61b754 100644 --- a/AATC_Monitor_Viewer.py +++ b/AATC_Monitor_Viewer.py @@ -44,57 +44,59 @@ def MaxLimit(value,Max): class Camera: def __init__(self,xpixel,ypixel,MinCoords,MaxCoords): #COORDS (X,Y,Z) - self.xpixel = xpixel - self.ypixel = ypixel - self.gameDisplay = pygame.display.set_mode((self.xpixel,self.ypixel)) - self.MinCoords = MinCoords - self.MaxCoords = MaxCoords - self.CameraCoord = self.MinCoords.copy() - self.CameraCoord.Set_XSize( self.MaxCoords.Get_X() - self.MinCoords.Get_X()) - self.CameraCoord.Set_YSize( self.MaxCoords.Get_Y() - self.MinCoords.Get_Y()) - self.CameraZoom = 1 - self.DrawObjects = [] + self._xpixel = xpixel + self._ypixel = ypixel + self._gameDisplay = pygame.display.set_mode((self._xpixel,self._ypixel)) + self._MinCoords = MinCoords + self._MaxCoords = MaxCoords + self._CameraCoord = self._MinCoords.copy() + self._CameraCoord.Set_XSize( self._MaxCoords.Get_X() - self._MinCoords.Get_X()) + self._CameraCoord.Set_YSize( self._MaxCoords.Get_Y() - self._MinCoords.Get_Y()) + self._CameraZoom = 1 + self._DrawObjects = [] def GetZoom(self): - return self.CameraZoom + return self._CameraZoom def SetZoom(self,Zoom): - self.CameraZoom = Zoom + self._CameraZoom = Zoom def GetCameraCoords(self): - return self.CameraCoord + return self._CameraCoord def IncrementCameraCoordX(self,Amount): - self.CameraCoord.Set_X( Amount+self.CameraCoord.Get_X()) + self._CameraCoord.Set_X( Amount+self._CameraCoord.Get_X()) def IncrementCameraCoordY(self,Amount): - self.CameraCoord.Set_Y( Amount+self.CameraCoord.Get_Y()) + self._CameraCoord.Set_Y( Amount+self._CameraCoord.Get_Y()) def SetCameraCoords(self,CameraX,CameraY): - self.CameraCoord.Set_X( CameraX) - self.CameraCoord.Set_Y(CameraY) + self._CameraCoord.Set_X( CameraX) + self._CameraCoord.Set_Y(CameraY) def UpdateCameraSize(self): #Gets width of map divided by zoom level eg at zoom 1x it has whole map - self.CameraCoord.Set_XSize ((self.MaxCoords.Get_X() - self.MinCoords.Get_X())/self.CameraZoom) - self.CameraCoord.Set_YSize ((self.MaxCoords.Get_Y() - self.MinCoords.Get_Y())/self.CameraZoom) + self._CameraCoord.Set_XSize ((self._MaxCoords.Get_X() - self._MinCoords.Get_X())/self._CameraZoom) + self._CameraCoord.Set_YSize ((self._MaxCoords.Get_Y() - self._MinCoords.Get_Y())/self._CameraZoom) def CameraWipe(self,Colour = (0,0,0)): - self.gameDisplay.fill(Colour) + self._gameDisplay.fill(Colour) def ResetDrawObject(self): - self.DrawObjects = [] + self._DrawObjects = [] def AddDrawObject(self,Object,ForceDraw): - self.DrawObjects.append({"Object":Object,"ForceDraw":ForceDraw}) + self._DrawObjects.append({"Object":Object,"ForceDraw":ForceDraw}) + def Get_DrawObjects(self): + return self._DrawObjects def Get_Coord(self): - return self.CameraCoord + return self._CameraCoord def Draw(self): - CameraEndX= self.CameraCoord.Get_X() + self.CameraCoord.Get_XSize() #Moved to new variablt to reduce recalculation - CameraEndY = self.CameraCoord.Get_Y() + self.CameraCoord.Get_YSize() - CameraX = self.CameraCoord.Get_X() - CameraY = self.CameraCoord.Get_Y() - CameraXSize = self.CameraCoord.Get_XSize() - CameraYSize = self.CameraCoord.Get_YSize() + CameraEndX= self._CameraCoord.Get_X() + self._CameraCoord.Get_XSize() #Moved to new variablt to reduce recalculation + CameraEndY = self._CameraCoord.Get_Y() + self._CameraCoord.Get_YSize() + CameraX = self._CameraCoord.Get_X() + CameraY = self._CameraCoord.Get_Y() + CameraXSize = self._CameraCoord.Get_XSize() + CameraYSize = self._CameraCoord.Get_YSize() - for DrawObject in self.DrawObjects: + for DrawObject in self._DrawObjects: Object = DrawObject["Object"] Object_Coords = Object.Get_Coords() x = Object_Coords.Get_X() @@ -105,18 +107,18 @@ def Draw(self): ((y < CameraEndY) and ((y+ySize) > CameraY )) : #If DrawObject intersects with Camera , Render, otherwise ignore - width,height = int(xSize/CameraXSize*self.xpixel) ,int(ySize/CameraYSize*self.ypixel) # Would benifit from being cythonised + width,height = int(xSize/CameraXSize*self._xpixel) ,int(ySize/CameraYSize*self._ypixel) # Would benifit from being cythonised if width > 0 and height > 0: - PosX = ((x- CameraX)/CameraXSize)* self.xpixel # Would benifit from being cythonised - PosY = ((y- CameraY)/CameraYSize)* self.ypixel - width = MaxLimit(width,self.xpixel) - height = MaxLimit(height,self.ypixel) - font_size = int(100*width/self.xpixel) # Would benifit from being cythonised + PosX = ((x- CameraX)/CameraXSize)* self._xpixel # Would benifit from being cythonised + PosY = ((y- CameraY)/CameraYSize)* self._ypixel + width = MaxLimit(width,self._xpixel) + height = MaxLimit(height,self._ypixel) + font_size = int(100*width/self._xpixel) # Would benifit from being cythonised image = Object.Make_Image(width,height) - self.gameDisplay.blit(image,(PosX,PosY)) + self._gameDisplay.blit(image,(PosX,PosY)) if font_size > 5: font = (None, font_size) - self.gameDisplay.blit(Object.Make_Text(font) ,(PosX+width,PosY)) + self._gameDisplay.blit(Object.Make_Text(font) ,(PosX+width,PosY)) @@ -125,27 +127,26 @@ def Draw(self): class Monitor_Sprite(pygame.sprite.Sprite): def __init__(self,CoordObject,Type = "",Text = "",Colour = (255,255,255)): - self.Coords = CoordObject - self.Type = Type - self.Text = Text - self.Colour = Colour - self.image = pygame.Surface((1,1)) + self._Coords = CoordObject + self._Type = Type + self._Text = Text + self._Colour = Colour + self._image = pygame.Surface((1,1)) #self.Make_Image(2,2) # No longer needed, is similar to that above. def Make_Image(self,width,height): - if self.image.get_size() != (width,height): #If new image does not match with previous - self.image = GetImage(width,height,self.Colour) - - return self.image + if self._image.get_size() != (width,height): #If new image does not match with previous + self._image = GetImage(width,height,self._Colour) + return self._image ## self.image = pygame.Surface((width,height)).convert() ## self.image.fill(self.Colour) def Make_Text(self,font): - text = str((self.Coords.Get_X(),self.Coords.Get_Y(),self.Coords.Get_Z())) +" " +self.Text + " "+ self.Type - return GetText(text,font,False,self.Colour) + text = str((self._Coords.Get_X(),self._Coords.Get_Y(),self._Coords.Get_Z())) +" " +self._Text + " "+ self._Type + return GetText(text,font,False,self._Colour) def Get_Coords(self): - return self.Coords + return self._Coords ## ## def Make_CoordsText(self,font): ## self.CoordsText = GetText(str((self.Coords.x,self.Coords.y,self.Coords.z)),font,False,self.Colour) @@ -267,7 +268,7 @@ def MakeSprites(M): SpriteList += MakeZoneSprites(Message,NoFlyZones) #Sprites are created in this function to simplify code in case of an error(False) - print("Refreshed data") + print("Refreshed data. Sprites :",len(SpriteList)) return SpriteList #All sprites which were sucessfully created class TimeWarper: @@ -276,14 +277,14 @@ class TimeWarper: The time warp will be relative to the target frame rate. If the warp is greater that of the minimum frame rate then the minimum time warp is taken. """ def __init__(self,targetFrameRate = 60,minimumFrameRate = 1): - self.targetFrameRate = targetFrameRate - self.minimumFrameRate = minimumFrameRate - self.Time = time.time() + self._targetFrameRate = targetFrameRate + self._minimumFrameRate = minimumFrameRate + self._Time = time.time() def GetTimeWarp(self): - TimeWarpFactor = (time.time()-self.Time)*self.targetFrameRate - self.Time = time.time() - return min([self.targetFrameRate/self.minimumFrameRate,TimeWarpFactor]) + TimeWarpFactor = (time.time()-self._Time)*self._targetFrameRate + self._Time = time.time() + return min([self._targetFrameRate/self._minimumFrameRate,TimeWarpFactor]) @@ -300,7 +301,7 @@ def GetTimeWarp(self): while Exit != "Y": try: M = AATC_Monitor.CreateMonitorInterface(IP = "127.0.0.1",Port = 8001) - M.Login("Zini","") + print(M.Login("Zini","")) #Sucess,Message,Data = M.GetCoordDetails() #MinCoords,MaxCoords,StepCoords = Data[0],Data[1],Data[2] MinCoords,MaxCoords = AATC_Coordinate.Coordinate(0,0,0),AATC_Coordinate.Coordinate(1,1,50) @@ -331,11 +332,11 @@ def GetTimeWarp(self): elif event.type == pygame.MOUSEBUTTONDOWN: print("Camera details") #Mainly for debugging print(MonCamera.GetZoom()) - print(MonCamera.CameraCoord.Get_X()) - print(MonCamera.CameraCoord.Get_Y()) - print(MonCamera.CameraCoord.Get_XSize()) - print(MonCamera.CameraCoord.Get_YSize()) - print(len(MonCamera.DrawObjects)) + print(MonCamera.Get_Coord().Get_X()) + print(MonCamera.Get_Coord().Get_Y()) + print(MonCamera.Get_Coord().Get_XSize()) + print(MonCamera.Get_Coord().Get_YSize()) + print(len(MonCamera.Get_DrawObjects())) print("FPS:"+str(clock.get_fps())) elif event.type == pygame.KEYDOWN: pass @@ -363,7 +364,7 @@ def GetTimeWarp(self): MonCamera.UpdateCameraSize() MonCamera.Draw() pygame.display.flip() - clock.tick(20) + clock.tick(60) diff --git a/AATC_NoFlyZoneGrapher.py b/AATC_NoFlyZoneGrapher.py index 2f7de73..f84ac13 100644 --- a/AATC_NoFlyZoneGrapher.py +++ b/AATC_NoFlyZoneGrapher.py @@ -14,34 +14,34 @@ class NoFlyZoneGrapher: """ def __init__(self,Thread_Name,Thread_Queue,Interval = 36000): - self.DB = AATC_DB.DBConnection() - self.Interval = Interval - self.Thread_Name = Thread_Name - self.Thread_Queue = Thread_Queue + self._DB = AATC_DB.DBConnection() + self._Interval = Interval + self._Thread_Name = Thread_Name + self._Thread_Queue = Thread_Queue graph = AATC_AStar.DynoGraph() graph.ImportGraph() - self.xSize,self.ySize,self.zSize = graph.Get_Size() + self._xSize,self._ySize,self._zSize = graph.Get_Size() del graph self.Main_Loop() def Main_Loop(self): - self.Exit = False - while not self.Exit: + self._Exit = False + while not self._Exit: try: NoFlyZoneData = self.GetNoFlyZones() self.Make_Values(NoFlyZoneData) except Exception as e: print("Error occured in NoFlyZoneGrapher",e) print("NoFlyZoneGrapher completed. Sleeping...") - time.sleep(self.Interval) + time.sleep(self._Interval) - if not self.Thread_Queue.empty(): - data = self.Thread_Queue.get() + if not self._Thread_Queue.empty(): + data = self._Thread_Queue.get() Command,Arguments = data[0],data[1] if Command == "Exit": - self.Exit = True + self._Exit = True print("NoFlyZoneGrapher exiting...") @@ -53,10 +53,10 @@ def Force_Write(self): #Cycles through all slots and writes current state. self.Make_Values(NoFlyZoneData,ABSlot = Slot) def Mod(self,Coords): - return int(Coords.Get_X()//self.xSize),int(Coords.Get_Y()//self.ySize),int(Coords.Get_Z()//self.zSize) + return int(Coords.Get_X()//self._xSize),int(Coords.Get_Y()//self._ySize),int(Coords.Get_Z()//self._zSize) def GetNoFlyZones(self): - _,Columns,Data = self.DB.GetNoFlyZones() + _,Columns,Data = self._DB.GetNoFlyZones() Columns = ast.literal_eval(Columns) ZoneIDIndex = Columns.index("ZoneID")#Gets indexes for the columns @@ -107,12 +107,12 @@ def Make_Values(self,NoFlyZoneData,ABSlot = 1): for NodeID in list(Values.keys()): #CHECK THIS. Only using those involved with a new no fly zone may cause issues if a no fly zone was removed. Maybe should be set to all node IDs. node = graph.GetNode(NodeID) if node.Get_NodeID() in Values: - node.Set_Cost( Values[node.NodeID]) - Values.pop(node.NodeID)# Reduce memory usage by evicting Node values which have been added already + node.Set_Cost( Values[node.Get_NodeID()]) + Values.pop(node.Get_NodeID())# Reduce memory usage by evicting Node values which have been added already else: node.Set_Cost(1) try: - graph.SaveNodes() + graph.SaveNodes([graph.CurrentFolderName()]) except Exception as e: print("Error saving nodes",e," Most likely no NoFlyZoneData yet") diff --git a/AATC_Server_002.py b/AATC_Server_002.py index c72f84b..0b7b256 100644 --- a/AATC_Server_002.py +++ b/AATC_Server_002.py @@ -24,12 +24,12 @@ class ClientConnection: """ def __init__(self,Thread_Name,Thread_Queue,Connection): - self.DB = AATC_DB.DBConnection() - self.Thread_Name = Thread_Name - self.Thread_Queue = Thread_Queue - self.con = Connection - self.Crypto = AATC_Crypto.Crypter(self.con, mode = "SERVER" ) - self.ClientID = -1 #Used to identify if has logged in yet + self._DB = AATC_DB.DBConnection() + self._Thread_Name = Thread_Name + self._Thread_Queue = Thread_Queue + self._con = Connection + self._Crypto = AATC_Crypto.Crypter(self._con, mode = "SERVER" ) + self._ClientID = -1 #Used to identify if has logged in yet def Connection_Loop(self): """ @@ -41,8 +41,8 @@ def Connection_Loop(self): Arguments may be converted from Tuple to Dict in future for clarity """ - self.ExitLoop = False - while not self.ExitLoop: + self._ExitLoop = False + while not self._ExitLoop: try: data = self.Recv() Command,Arguments = data[0],data[1] @@ -50,37 +50,37 @@ def Connection_Loop(self): except Exception as e: Sucess,Message,Data = False,"An Error occured"+str(e),[] - print("Error occured with",self.Thread_Name,":",str(self.ClientID),"Error :",str(e)," Sending failure message") + print("Error occured with",self._Thread_Name,":",str(self._ClientID),"Error :",str(e)," Sending failure message") try: self.Send((Sucess,Message,Data)) except Exception as e: - print(self.Thread_Name,self.ClientID," disconnected") - self.ExitLoop = True + print(self._Thread_Name,self._ClientID," disconnected") + self._ExitLoop = True - if not self.Thread_Queue.empty(): + if not self._Thread_Queue.empty(): data = Thread_Queue.get() Command,Arguments = data[0],data[1] if Command == "Exit": - self.ExitLoop = True + self._ExitLoop = True - self.DB.Exit() - self.con.close() + self._DB.Exit() + self._con.close() print("Process is exiting") def Send(self,data): - self.con.sendall(self.Crypto.Encrypt(codecs.encode(str(data)))) + self._con.sendall(self._Crypto.Encrypt(codecs.encode(str(data)))) def Recv(self): try: - data = self.Crypto.Decrypt(recvall.recvall(self.con)) + data = self._Crypto.Decrypt(recvall.recvall(self._con)) data = ast.literal_eval(codecs.decode(data)) return data except Exception as e: return ("",())#Never references a command def Exit(self,Arguments = None): - #self.DB.db_con.close() - print("Process for ",self.Thread_Name,":",self.ClientID," is exiting..") + #self._DB.db_con.close() + print("Process for ",self._Thread_Name,":",self._ClientID," is exiting..") return True,"Server process is exiting. Ok to disconnect",[] @@ -88,7 +88,7 @@ def Exit(self,Arguments = None): class UserConnection(ClientConnection): def ProcessCommand(self,Command,Arguments): - if self.ClientID == -1: + if self._ClientID == -1: if Command == "Login": Sucess,Message,Data = self.Login(Arguments) elif Command == "AddUser": # If adding a new user, one must create it first, then log in seperatly @@ -171,85 +171,85 @@ def ProcessCommand(self,Command,Arguments): elif Command == "Exit": Sucess,Message,Data = self.Exit(Arguments) - self.ExitLoop = True + self._ExitLoop = True #Else if command doesnt exist send back Failure else: Sucess,Message,Data = False,"Command does not exist",[] - print(self.Thread_Name,self.ClientID," tried to use unregistered command") + print(self._Thread_Name,self._ClientID," tried to use unregistered command") return Sucess,Message,Data def Login(self,Arguments): Username,Password = Arguments[0],Arguments[1] - Sucess,Message,self.ClientID = self.DB.CheckCredentials(Username,Password) + Sucess,Message,self._ClientID = self._DB.CheckCredentials(Username,Password) return Sucess,Message,[] ######################################################## def GetNoFlyZones(self,Arguments = None): - Sucess,Message,Data = self.DB.GetNoFlyZones() + Sucess,Message,Data = self._DB.GetNoFlyZones() return Sucess,Message,Data def AddNoFlyZone(self,Arguments): if len(Arguments) == 3: Coord1,Coord2,Level = Arguments[0],Arguments[1],Arguments[2] Coord1,Coord2 = ast.literal_eval(Coord1),ast.literal_eval(Coord2) - Sucess,Message = self.DB.AddNoFlyZone(Coord1,Coord2,Level,self.ClientID) + Sucess,Message = self._DB.AddNoFlyZone(Coord1,Coord2,Level,self._ClientID) else: Sucess,Message = False,"Incorrect Argument format" return Sucess,Message,[] def RemoveNoFlyZone(self,Arguments): ZoneID = Arguments[0] - Sucess,Message = self.DB.RemoveNoFlyZone(self.ClientID,ZoneID) + Sucess,Message = self._DB.RemoveNoFlyZone(self._ClientID,ZoneID) return Sucess,Message,[] def ModifyNoFlyZoneLevel(self,Arguments): ZoneID,Level = Arguments[0],Arguments[1] - Sucess,Message = self.DB.ModifyNoFlyZoneLevel(self.ClientID,ZoneID,Level) + Sucess,Message = self._DB.ModifyNoFlyZoneLevel(self._ClientID,ZoneID,Level) return Sucess,Message,[] ######################################################## def AddDrone(self,Arguments): DroneName,DronePassword,DroneType,DroneSpeed,DroneRange,DroneWeight = Arguments[0],Arguments[1],Arguments[2],Arguments[3],Arguments[4],Arguments[5] - Sucess,Message = self.DB.AddDrone(self.ClientID,DroneName,DronePassword,DroneType,DroneSpeed,DroneRange,DroneWeight) + Sucess,Message = self._DB.AddDrone(self._ClientID,DroneName,DronePassword,DroneType,DroneSpeed,DroneRange,DroneWeight) return Sucess,Message,[] def RemoveDrone(self,Arguments): DroneID = Arguments[0] - Sucess,Message = self.DB.RemoveDrone(self.ClientID,DroneID) + Sucess,Message = self._DB.RemoveDrone(self._ClientID,DroneID) return Sucess,Message,[] def GetDroneID(self,Arguments): DroneName = Arguments[0] - Sucess,Message,Data = self.DB.GetDroneID(self.ClientID,DroneName) + Sucess,Message,Data = self._DB.GetDroneID(self._ClientID,DroneName) return Sucess,Message,Data def GetDroneCredentials(self,Arguments): DroneID = Arguments[0] - Sucess,Message,Data = self.DB.GetDroneCredentials(self.ClientID,DroneID) + Sucess,Message,Data = self._DB.GetDroneCredentials(self._ClientID,DroneID) return Sucess,Message,Data def SetDroneCredentials(self,Arguments): DroneID,DronePassword = Arguments[0],Arguments[1] - Sucess,Message = self.DB.SetDroneCredentials(self.ClientID,DroneID,DronePassword) + Sucess,Message = self._DB.SetDroneCredentials(self._ClientID,DroneID,DronePassword) return Sucess,Message,[] def CheckDroneOwnership(self,Arguments): UserID,DroneID = Arguments[0],Arguments[1] - Sucess,Message,Data = self.DB.CheckDroneOwnership(UserID,DroneID) + Sucess,Message,Data = self._DB.CheckDroneOwnership(UserID,DroneID) return Sucess,Message,Data def GetDroneInfo(self,Arguments): DroneID = Arguments[0] - Sucess,Message,Data = self.DB.GetDroneInfo(self.ClientID,DroneID) + Sucess,Message,Data = self._DB.GetDroneInfo(self._ClientID,DroneID) return Sucess,Message,Data def GetDronesUser(self,Arguments = None): - Sucess,Message,Data = self.DB.GetDronesUser(self.ClientID) + Sucess,Message,Data = self._DB.GetDronesUser(self._ClientID) return Sucess,Message,Data def GetDronesAll(self,Arguments = None): - Sucess,Message,Data = self.DB.GetDronesAll() + Sucess,Message,Data = self._DB.GetDronesAll() return Sucess,Message,Data ######################################################## @@ -259,46 +259,46 @@ def GetDronesAll(self,Arguments = None): def GetUserID(self,Arguments): Username = Arguments[0] - Sucess,Message,Data = self.DB.GetUserID(Username) + Sucess,Message,Data = self._DB.GetUserID(Username) return Sucess,Message,Data def GetUsername(self,Arguments): UserID = Arguments[0] - Sucess,Message,Data = self.DB.GetUsername(UserID) + Sucess,Message,Data = self._DB.GetUsername(UserID) return Sucess,Message,Data def AddUser(self,Arguments): Username,Password = Arguments[0],Arguments[1] - Sucess,Message = self.DB.AddUser(Username,Password) + Sucess,Message = self._DB.AddUser(Username,Password) return Sucess,Message,[] def SetFlightVisibility(self,Arguments): Value = Arguments[0] - Sucess,Message = self.DB.SetFlightVisibility(self.ClientID,Value) + Sucess,Message = self._DB.SetFlightVisibility(self._ClientID,Value) return Sucess,Message,[] def SetAccountType(self,Arguments): Permission,Value = Arguments[0],Arguments[1] - Sucess,Message = self.DB.SetAccountType(self.ClientID,Permission,Value) + Sucess,Message = self._DB.SetAccountType(self._ClientID,Permission,Value) return Sucess,Message,[] def UserChangePassword(self,Arguments): OldPassword,NewPassword = Arguments[0],Arguments[1] - Sucess,Message = self.DB.UserChangePassword(self.ClientID,OldPassword,NewPassword) + Sucess,Message = self._DB.UserChangePassword(self._ClientID,OldPassword,NewPassword) return Sucess,Message,[] ####################################################### def GetFlightsUser(self,Arguments = None): - Sucess,Message,Data = self.DB.GetFlightsUser(self.ClientID) + Sucess,Message,Data = self._DB.GetFlightsUser(self._ClientID) return Sucess,Message,Data def GetFlightsAll(self,Arguments = None): - Sucess,Message,Data = self.DB.GetFlightsAll() + Sucess,Message,Data = self._DB.GetFlightsAll() return Sucess,Message,Data def AddFlight(self,Arguments): @@ -323,12 +323,12 @@ def AddFlight(self,Arguments): return False,"A point in this set is in a restricted area or not in service area. Flight denied.",[] except Exception as e: - print(self.Thread_Name,":",self.ClientID,"Error in AddFlight HighPointOK assesment",e) + print(self._Thread_Name,":",self._ClientID,"Error in AddFlight HighPointOK assesment",e) return False,"A point in this set is in a restricted area or not in service area. Flight denied.",[] - S_,M_,Result = self.DB.CheckDroneOwnership(self.ClientID,DroneID) + S_,M_,Result = self._DB.CheckDroneOwnership(self._ClientID,DroneID) if len(Result) !=0: Start = 0 Next = 1 @@ -351,16 +351,17 @@ def AddFlight(self,Arguments): return False,"Pathfinding was not able to find a path between the two nodes "+str([HighPoints[Start],HighPoints[Next]]),[] else: - XOffset,YOffset,ZOffset = round(random.random()*0.5*graph.xSize,8),round(random.random()*0.5*graph.ySize,8),round(random.random()*0.5*graph.zSize,8) + xSize,ySize,zSize = graph.Get_Size() + XOffset,YOffset,ZOffset = round(random.random()*0.5*xSize,8),round(random.random()*0.5*ySize,8),round(random.random()*0.5*zSize,8) CoordList = [] for NodeID in Path: Node = graph.GetNode(NodeID) - Coords = Node.Coords + Coords = Node.Get_Coords() Coords.Set_X( Coords.Get_X()+XOffset), Coords.Set_Y(Coords.Get_Y()+YOffset), Coords.Set_Z(Coords.Get_Z()+ZOffset) CoordList.append({"Coords":Coords}) Time = StartTime - _,Columns,DroneData = self.DB.GetDroneInfo(self.ClientID,DroneID) + _,Columns,DroneData = self._DB.GetDroneInfo(self._ClientID,DroneID) Columns = ast.literal_eval(Columns) DroneData = DroneData[0] SpeedIndex,RangeIndex = Columns.index("DroneSpeed"),Columns.index("DroneRange") @@ -386,21 +387,22 @@ def AddFlight(self,Arguments): #Adding Flight to Database - self.DB.AddFlight(self.ClientID,DroneID,HighPoints[0],HighPoints[len(HighPoints)-1],StartTime,EndTime,EndTime,TotalDistance,XOffset,YOffset,ZOffset) + _,_,FlightID = self._DB.AddFlight(self._ClientID,DroneID,HighPoints[0],HighPoints[len(HighPoints)-1],StartTime,EndTime,EndTime,TotalDistance,XOffset,YOffset,ZOffset) ###################### ###################### TEMP WORKAROUND ########## - self.DB.cur.execute("SELECT FlightID FROM Flight WHERE DroneID = %s AND StartTime = %s",(DroneID,StartTime)) - FlightID = self.DB.cur.fetchall()[0][0] +## self._DB.cur.execute("SELECT FlightID FROM Flight WHERE DroneID = %s AND StartTime = %s",(DroneID,StartTime)) +## FlightID = self._DB.cur.fetchall()[0][0] ###################### ###################### + Waypoints = [] for WaypointNumber in range(len(CoordList)): Waypoints.append((FlightID,WaypointNumber+1,str(CoordList[WaypointNumber]["Coords"]),int(CoordList[WaypointNumber]["Time"]),0)) - self.DB.AddWaypoints(self.ClientID,FlightID,Waypoints) + self._DB.AddWaypoints(self._ClientID,FlightID,Waypoints) return True,"['FlightID','NumberOfWaypoints','StartTime','EndTime','Distance']",[(FlightID,len(CoordList),StartTime,EndTime,TotalDistance)] #Returns data about the flight @@ -417,31 +419,31 @@ def AddFlight(self,Arguments): def RemoveFlight(self,Arguments): FlightID = Arguments[0] - Sucess,Message = self.DB.RemoveFlight(self.ClientID,FlightID) + Sucess,Message = self._DB.RemoveFlight(self._ClientID,FlightID) return Sucess,Message,[] ####################################################### def GetFlightWaypointsUser(self,Arguments = None): - Sucess,Message,Data = self.DB.GetFlightWaypointsUser(self.ClientID) + Sucess,Message,Data = self._DB.GetFlightWaypointsUser(self._ClientID) return Sucess,Message,Data def GetFlightWaypointsAll(self,Arguments = None): - Sucess,Message,Data = self.DB.GetFlightWaypointsAll() + Sucess,Message,Data = self._DB.GetFlightWaypointsAll() return Sucess,Message,Data ####################################################### def GetMonitorID(self,Arguments): MonitorName = Arguments[0] - Sucess,Message,Data = self.DB.GetMonitorID(MonitorName) + Sucess,Message,Data = self._DB.GetMonitorID(MonitorName) return Sucess,Message,Data def GetMonitorName(self,Arguments): MonitorID = Arguments[0] - Sucess,Message,Data = self.DB.GetMonitorName(MonitorID) + Sucess,Message,Data = self._DB.GetMonitorName(MonitorID) return Sucess,Message,Data @@ -449,24 +451,24 @@ def GetMonitorName(self,Arguments): def AddMonitorPermission(self,Arguments): MonitorID,ExpiryDate = Arguments[0],Arguments[1] - Sucess,Message = self.DB.AddMonitorPermission(self.ClientID,MonitorID,ExpiryDate) + Sucess,Message = self._DB.AddMonitorPermission(self._ClientID,MonitorID,ExpiryDate) return Sucess,Message,[] def RemoveMonitorPermission(self,Arguments): MonitorID = Arguments[0] - Sucess,Message = self.DB.RemoveMonitorPermission(self.ClientID,MonitorID) + Sucess,Message = self._DB.RemoveMonitorPermission(self._ClientID,MonitorID) return Sucess,Message,[] def ModifyMonitorPermissionDate(self,Arguments): MonitorID,NewDate = Arguments[0],Arguments[1] - Sucess,Message = self.DB.ModifyMonitorPermissionDate(self.ClientID,MonitorID,NewDate) + Sucess,Message = self._DB.ModifyMonitorPermissionDate(self._ClientID,MonitorID,NewDate) return Sucess,Message,[] def GetMonitorPermissionUser(self,Arguments = None): - Sucess,Message,Data = self.DB.GetMonitorPermissionUser(self.ClientID) + Sucess,Message,Data = self._DB.GetMonitorPermissionUser(self._ClientID) return Sucess,Message,Data @@ -481,11 +483,11 @@ def GetMonitorPermissionUser(self,Arguments = None): class BotConnection(UserConnection): def __init__(self,UserID,chat_id,packet,OutputQueue): - self.ClientID = UserID + self._ClientID = UserID self.chat_id = chat_id self.OutputQueue = OutputQueue - self.DB = AATC_DB.DBConnection() - self.Thread_Name = "[BOT FOR UID "+str(self.ClientID)+"]" + self._DB = AATC_DB.DBConnection() + self._Thread_Name = "[BOT FOR UID "+str(self._ClientID)+"]" Command, Arguments = packet[0],packet[1] self.Main(Command,Arguments) @@ -496,13 +498,13 @@ def Main(self,Command,Arguments): except Exception as e: Sucess,Message,Data = False,"An Error occured"+str(e),[] - print("Error occured with UserID:",str(self.ClientID),". Error :",str(e),". Sending failure message") + print("Error occured with UserID:",str(self._ClientID),". Error :",str(e),". Sending failure message") try: self.Send((Sucess,Message,Data)) except Exception as e: print("Error sending message back to chat",e) - self.DB.Exit() + self._DB.Exit() @@ -513,17 +515,17 @@ def Send(self,data): def Login(self,Arguments): Username,Password = Arguments[0],Arguments[1] - Sucess,Message,UserID = self.DB.CheckCredentials(Username,Password) - self.DB.Bot_SetUserID(self.chat_id,UserID) + Sucess,Message,UserID = self._DB.CheckCredentials(Username,Password) + self._DB.Bot_SetUserID(self.chat_id,UserID) return Sucess,Message,[] class WebConnection(UserConnection): def __init__(self,UserID): - self.ClientID = UserID - self.DB = AATC_DB.DBConnection() - self.Thread_Name = "[WEB FOR UID "+str(self.ClientID)+"]" + self._ClientID = UserID + self._DB = AATC_DB.DBConnection() + self._Thread_Name = "[WEB FOR UID "+str(self._ClientID)+"]" @@ -534,15 +536,15 @@ def Main(self,packet): except Exception as e: Sucess,Message,Data = False,"An Error occured"+str(e),[] - print("Error occured with UserID:",str(self.ClientID),". Error :",str(e),". Sending failure message") + print("Error occured with UserID:",str(self._ClientID),". Error :",str(e),". Sending failure message") - self.DB.Exit() + self._DB.Exit() return Sucess,Message,Data def Login(self,Arguments): Username,Password = Arguments[0],Arguments[1] - Sucess,Message,UserID = self.DB.CheckCredentials(Username,Password) + Sucess,Message,UserID = self._DB.CheckCredentials(Username,Password) return Sucess,Message,UserID @@ -558,7 +560,7 @@ def Login(self,Arguments): class MonitorConnection(ClientConnection): def ProcessCommand(self,Command,Arguments): - if self.ClientID == -1: + if self._ClientID == -1: if Command == "Login": Sucess,Message,Data = self.Login(Arguments) elif Command == "AddMonitor": # If adding a new Monitor, one must create it first, then log in seperatly @@ -611,96 +613,96 @@ def ProcessCommand(self,Command,Arguments): elif Command == "Exit": Sucess,Message,Data = self.Exit(Arguments) - self.ExitLoop = True + self._ExitLoop = True #Else if command doesnt exist send back Failure else: Sucess,Message,Data = False,"Command does not exist",[] - print(self.Thread_Name,self.ClientID," tried to use unregistered command") + print(self._Thread_Name,self._ClientID," tried to use unregistered command") return Sucess,Message,Data ################################ def Login(self,Arguments): MonitorName,MonitorPassword = Arguments[0],Arguments[1] - Sucess,Message,self.ClientID = self.DB.MonitorCheckCredentials(MonitorName,MonitorPassword) + Sucess,Message,self._ClientID = self._DB.MonitorCheckCredentials(MonitorName,MonitorPassword) return Sucess,Message,[] def AddMonitor(self,Arguments): MonitorName,MonitorPassword = Arguments[0],Arguments[1] - Sucess,Message = self.DB.AddMonitor(MonitorName,MonitorPassword) + Sucess,Message = self._DB.AddMonitor(MonitorName,MonitorPassword) return Sucess,Message,[] def MonitorChangePassword(self,Arguments): OldPassword,NewPassword = Arguments[0],Arguments[1] - Sucess,Message = self.DB.MonitorChangePassword(self.ClientID,OldPassword,NewPassword) + Sucess,Message = self._DB.MonitorChangePassword(self._ClientID,OldPassword,NewPassword) return Sucess,Message,[] ######### No Fly Zone ################## def GetNoFlyZones(self,Arguments = None): - Sucess,Message,Data = self.DB.GetNoFlyZones() + Sucess,Message,Data = self._DB.GetNoFlyZones() return Sucess,Message,Data ####### Drones ################ def GetDronesAll(self,Arguments = None): - Sucess,Message,Data = self.DB.GetDronesAll() + Sucess,Message,Data = self._DB.GetDronesAll() return Sucess,Message,Data ####### User ################# def GetUserID(self,Arguments): Username = Arguments[0] - Sucess,Message,Data = self.DB.GetUserID(Username) + Sucess,Message,Data = self._DB.GetUserID(Username) return Sucess,Message,Data def GetUsername(self,Arguments): UserID = Arguments[0] - Sucess,Message,Data = self.DB.GetUsername(UserID) + Sucess,Message,Data = self._DB.GetUsername(UserID) return Sucess,Message,Data ###### Monitor ################ def GetMonitorDrones(self,Arguments = None): - Sucess,Message,Data = self.DB.GetMonitorDrones(self.ClientID) + Sucess,Message,Data = self._DB.GetMonitorDrones(self._ClientID) return Sucess,Message,Data def GetMonitorFlights(self,Arguments = None): - Sucess,Message,Data = self.DB.GetMonitorFlights(self.ClientID) + Sucess,Message,Data = self._DB.GetMonitorFlights(self._ClientID) return Sucess,Message,Data def GetMonitorFlightWaypoints(self,Arguments = None): - Sucess,Message,Data = self.DB.GetMonitorFlightWaypoints(self.ClientID) + Sucess,Message,Data = self._DB.GetMonitorFlightWaypoints(self._ClientID) return Sucess,Message,Data def GetMonitorID(self,Arguments): MonitorName = Arguments[0] - Sucess,Message,Data = self.DB.GetMonitorID(MonitorName) + Sucess,Message,Data = self._DB.GetMonitorID(MonitorName) return Sucess,Message,Data def GetMonitorName(self,Arguments): MonitorID = Arguments[0] - Sucess,Message,Data = self.DB.GetMonitorName(MonitorID) + Sucess,Message,Data = self._DB.GetMonitorName(MonitorID) return Sucess,Message,Data ######## Monitor Permisssion ############ def RemoveMonitorPermission(self,Arguments): UserID = Arguments[0] - Sucess,Message = self.DB.RemoveMonitorPermission(UserID,self.ClientID) + Sucess,Message = self._DB.RemoveMonitorPermission(UserID,self._ClientID) return Sucess,Message,[] def GetMonitorPermissionMonitor(self,Arguments = None): - Sucess,Message,Data = self.DB.GetMonitorPermissionMonitor(self.ClientID) + Sucess,Message,Data = self._DB.GetMonitorPermissionMonitor(self._ClientID) return Sucess,Message,Data ################################################### def GetFlightsAll(self,Arguments = None): - Sucess,Message,Data = self.DB.GetFlightsAll() + Sucess,Message,Data = self._DB.GetFlightsAll() return Sucess,Message,Data def GetFlightWaypointsAll(self,Arguments = None): - Sucess,Message,Data = self.DB.GetFlightWaypointsAll() + Sucess,Message,Data = self._DB.GetFlightWaypointsAll() return Sucess,Message,Data ############################################# @@ -713,7 +715,7 @@ def GetFlightWaypointsAll(self,Arguments = None): class DroneConnection(ClientConnection): def ProcessCommand(self,Command,Arguments): - if self.ClientID == -1: + if self._ClientID == -1: if Command == "Login": Sucess,Message,Data = self.Login(Arguments) elif Command == "Exit": @@ -741,52 +743,52 @@ def ProcessCommand(self,Command,Arguments): elif Command == "Exit": Sucess,Message,Data = self.Exit(Arguments) - self.ExitLoop = True + self._ExitLoop = True #Else if command doesnt exist send back Failure else: Sucess,Message,Data = False,"Command does not exist",[] - print(self.Thread_Name,self.ClientID," tried to use unregistered command") + print(self._Thread_Name,self._ClientID," tried to use unregistered command") return Sucess,Message,Data def Login(self,Arguments): DroneID,DronePassword = Arguments[0],Arguments[1] - Sucess,Message,self.ClientID = self.DB.DroneCheckCredentials(DroneID,DronePassword) + Sucess,Message,self._ClientID = self._DB.DroneCheckCredentials(DroneID,DronePassword) return Sucess,Message,[] ######################################################## def UpdateDroneStatus(self,Arguments): LastCoords,LastBattery = Coordinate(*Arguments[0]),Arguments[1] - Sucess,Message = self.DB.UpdateDroneStatus(self.ClientID,LastCoords,LastBattery) + Sucess,Message = self._DB.UpdateDroneStatus(self._ClientID,LastCoords,LastBattery) return Sucess,Message,[] ######################################################## def DroneGetDroneInfo(self,Arguments = None): - Sucess,Message,Data = self.DB.DroneGetDroneInfo(self.ClientID) + Sucess,Message,Data = self._DB.DroneGetDroneInfo(self._ClientID) return Sucess,Message,Data ########################################################## def CheckForFlight(self,Arguments): MaxLookAheadTime = Arguments[0] # How many seconds until flight start should the search allow. Would lead to the drone being locked into that flight most likely. - Sucess,Message,Data = self.DB.CheckForFlight(self.ClientID,MaxLookAheadTime) + Sucess,Message,Data = self._DB.CheckForFlight(self._ClientID,MaxLookAheadTime) return Sucess,Message,Data def GetFlight(self,Arguments): FlightID = Arguments[0] - Sucess,Message,Data = self.DB.GetFlight(self.ClientID,FlightID) + Sucess,Message,Data = self._DB.GetFlight(self._ClientID,FlightID) return Sucess,Message,Data def GetFlightWaypoints(self,Arguments): FlightID = Arguments[0] - Sucess,Message,Data = self.DB.GetFlightWaypoints(self.ClientID,FlightID) + Sucess,Message,Data = self._DB.GetFlightWaypoints(self._ClientID,FlightID) return Sucess,Message,Data def MarkFlightComplete(self,Arguments): FlightID,Code = Arguments[0],Arguments[1] - Sucess,Message = self.DB.MarkFlightComplete(self.ClientID,FlightID,Code) + Sucess,Message = self._DB.MarkFlightComplete(self._ClientID,FlightID,Code) return Sucess,Message,[] ###################################################### diff --git a/AATC_Weather.py b/AATC_Weather.py index f0230a6..e083d99 100644 --- a/AATC_Weather.py +++ b/AATC_Weather.py @@ -5,12 +5,12 @@ def Get_OWM(): class OWM_Control: def __init__(self): - self.owm = pyowm.OWM('5b943c4857a45d75ef7ee9b301666fa8') + self._owm = pyowm.OWM('5b943c4857a45d75ef7ee9b301666fa8') def Get_Ajusted_Speed(self,CoordA,CoordB,Speed,At_Time = time.time()): try: - forecast = self.owm.daily_forecast_at_coords(CoordA.Get_Y(),CoordA.Get_X()) + forecast = self._owm.daily_forecast_at_coords(CoordA.Get_Y(),CoordA.Get_X()) wind = forecast.get_weather_at(int(At_Time)).get_wind() bearing = AATC_Coordinate.GetBearing(CoordA,CoordB) diff --git a/HedaBot.py b/HedaBot.py index 6ea89e4..8d040f0 100644 --- a/HedaBot.py +++ b/HedaBot.py @@ -20,110 +20,110 @@ def StringBlock(string, block_size): class Ticker: def __init__(self,frequency): - self.last_call = time.time() - self.time_period = 1/frequency + self._last_call = time.time() + self._time_period = 1/frequency def wait_ok(self): - dtime = (self.last_call+self.time_period)-time.time() + dtime = (self._last_call+self._time_period)-time.time() if dtime > 0: time.sleep(dtime) - self.last_call = time.time() + self._last_call = time.time() def reset(self): - self.last_call = 0 + self._last_call = 0 class Telebot: def __init__(self,Thread_Name,Input_Queue,signature = "\nHeda ∞",start_update_id= 0,inputSorterNumber = 2): - self.Thread_Name = Thread_Name - self.Input_Queue = Input_Queue - self.bot = telepot.Bot(BOT_TOKEN) - self.signature = signature - self.update_id = start_update_id - self.chat_id = 0 + self._Thread_Name = Thread_Name + self._Input_Queue = Input_Queue + self._bot = telepot.Bot(BOT_TOKEN) + self._signature = signature + self._update_id = start_update_id + self._chat_id = 0 - self.ticker = Ticker(3) # Used to limit the frequency at which messages are sent - self.Restart_Ticker = Ticker(1/60) - self.Update_Queue = [] - self.DB = AATC_DB.DBConnection() - self.OutputQueue = multiprocessing.Queue() + self._ticker = Ticker(3) # Used to limit the frequency at which messages are sent + self._Restart_Ticker = Ticker(1/60) + self._Update_Queue = [] + self._DB = AATC_DB.DBConnection() + self._OutputQueue = multiprocessing.Queue() - self.inputSorterNumber = inputSorterNumber - self.TC_Queue = AATC_GPIO.Create_Controller() - for ProcessID in range(self.inputSorterNumber): - self.TC_Queue.put(("Controller","Create_Process",(ProcessID,inputSorter,(self.OutputQueue,)))) + self._inputSorterNumber = inputSorterNumber + self._TC_Queue = AATC_GPIO.Create_Controller() + for ProcessID in range(self._inputSorterNumber): + self._TC_Queue.put(("Controller","Create_Process",(ProcessID,inputSorter,(self._OutputQueue,)))) def setChatID(self,chat_id): - self.chat_id = chat_id + self._chat_id = chat_id def sendMessage(self,message,chat_id = None): if chat_id != None: - self.chat_id = chat_id - blocks = StringBlock(message+self.signature,4000) + self._chat_id = chat_id + blocks = StringBlock(message+self._signature,4000) for string in blocks: - self.ticker.wait_ok() - self.bot.sendMessage(self.chat_id,string) + self._ticker.wait_ok() + self._bot.sendMessage(self._chat_id,string) def getUpdate(self): - if len(self.Update_Queue) ==0: + if len(self._Update_Queue) ==0: updates = [] while len(updates) == 0: - updates = self.bot.getUpdates(self.update_id +1) + updates = self._bot.getUpdates(self._update_id +1) if len(updates) != 0: pass else: time.sleep(1) for item in updates: - self.update_id = max([self.update_id, item["update_id"]]) - self.Update_Queue.append(item) + self._update_id = max([self._update_id, item["update_id"]]) + self._Update_Queue.append(item) - return self.Update_Queue.pop(0) + return self._Update_Queue.pop(0) def textInput(self,Message=""): #relays message between user and machine - self.sendMessage(Message,self.chat_id) + self.sendMessage(Message,self._chat_id) return self.getUpdate()["message"]["text"] def mainLoop(self): Exit = False while not Exit: try: - while not self.OutputQueue.empty(): #Sends the messages which have been created. - packet = self.OutputQueue.get() + while not self._OutputQueue.empty(): #Sends the messages which have been created. + packet = self._OutputQueue.get() self.sendMessage(*packet) - update = self.bot.getUpdates(self.update_id + 1) + update = self._bot.getUpdates(self._update_id + 1) for packet in update: - self.update_id = max([self.update_id,packet["update_id"]]) + self._update_id = max([self._update_id,packet["update_id"]]) messageText = packet["message"]["text"] chatID = packet["message"]["chat"]["id"] if ord(messageText[0]) >200: #Deal with emojis -_- continue - Thread_Name = chatID % self.inputSorterNumber - self.TC_Queue.put((Thread_Name,"ProcessMessage",(messageText,chatID))) + Thread_Name = chatID % self._inputSorterNumber + self._TC_Queue.put((Thread_Name,"ProcessMessage",(messageText,chatID))) time.sleep(0.5) except Exception as e: - print("Error in Telebot",self.Thread_Name,"Error:",e) - self.Restart_Ticker.wait_ok() + print("Error in Telebot",self._Thread_Name,"Error:",e) + self._Restart_Ticker.wait_ok() try: - self.bot = telepot.Bot(BOT_TOKEN) + self._bot = telepot.Bot(BOT_TOKEN) except Exception as e: - print("Error in Telebot",self.Thread_Name,"Error connecting to telegram servers. Check your internet connection and API Token. Connection may be blocked by administrator.") + print("Error in Telebot",self._Thread_Name,"Error connecting to telegram servers. Check your internet connection and API Token. Connection may be blocked by administrator.") - if not self.Input_Queue.empty(): - data = self.Input_Queue.get() + if not self._Input_Queue.empty(): + data = self._Input_Queue.get() command,arguments = data[0],data[1] if command == "Exit": Exit = True - self.TC_Queue.put(("Controller","Exit",(True,))) - print("Telebot", self.Thread_Name," is exiting") + self._TC_Queue.put(("Controller","Exit",(True,))) + print("Telebot", self._Thread_Name," is exiting") def processMessage(self,messageText,chat_id = 0): @@ -155,18 +155,18 @@ def processMessage(self,messageText,chat_id = 0): class inputSorter: def __init__(self,Thread_Name,Input_Queue,OutputQueue,Exec_Processes = 1): - self.Thread_Name = Thread_Name - self.Input_Queue = Input_Queue - self.OutputQueue = OutputQueue - self.Exec_Processes = Exec_Processes + self._Thread_Name = Thread_Name + self._Input_Queue = Input_Queue + self._OutputQueue = OutputQueue + self._Exec_Processes = Exec_Processes - self.DB = AATC_DB.DBConnection() - self.ShowCommandsList = ShowCommands() - self.CommandDictionary = CreateCommandDictionary() + self._DB = AATC_DB.DBConnection() + self._ShowCommandsList = ShowCommands() + self._CommandDictionary = CreateCommandDictionary() - self.EC_Queue = AATC_GPIO.Create_Controller() - for ProcessID in range(self.Exec_Processes): - self.EC_Queue.put(("Controller","Create_Process",(ProcessID,CommandExecutor,(self.OutputQueue,)))) + self._EC_Queue = AATC_GPIO.Create_Controller() + for ProcessID in range(self._Exec_Processes): + self._EC_Queue.put(("Controller","Create_Process",(ProcessID,CommandExecutor,(self._OutputQueue,)))) self.mainLoop() @@ -174,7 +174,7 @@ def mainLoop(self): Exit = False while not Exit: try: - data = self.Input_Queue.get() + data = self._Input_Queue.get() command,arguments = data[0],data[1] if command == "Exit": Exit = True @@ -187,11 +187,11 @@ def mainLoop(self): ## print() ## print("Message:",messageText) ## print("Response:",response) - self.OutputQueue.put((response,chat_id)) + self._OutputQueue.put((response,chat_id)) except Exception as e: - print("Error in inputSorter",self.Thread_Name,"Error:",e) - self.EC_Queue.put(("Controller","Exit",(True,))) - print("Closing inputSorter",self.Thread_Name) + print("Error in inputSorter",self._Thread_Name,"Error:",e) + self._EC_Queue.put(("Controller","Exit",(True,))) + print("Closing inputSorter",self._Thread_Name) def processInput(self,messageText,chat_id): @@ -199,40 +199,40 @@ def processInput(self,messageText,chat_id): try: if "/" in messageText: if "/cancel" == messageText: - self.DB.Bot_flushStack(chat_id) + self._DB.Bot_flushStack(chat_id) return "Command cancelled" elif "/quote" == messageText: return SkyrimQuote.SkyrimQuote() else: - self.DB.Bot_flushStack(chat_id) + self._DB.Bot_flushStack(chat_id) messageText = messageText.replace("/","") elif lowerText in ["help","?"]: - return self.ShowCommandsList + return self._ShowCommandsList - self.DB.Bot_addValue(messageText,chat_id) + self._DB.Bot_addValue(messageText,chat_id) - stack_size = self.DB.Bot_getStackSize(chat_id) - command = self.DB.Bot_getCommand(chat_id) - command_size = len(self.CommandDictionary[command]) + stack_size = self._DB.Bot_getStackSize(chat_id) + command = self._DB.Bot_getCommand(chat_id) + command_size = len(self._CommandDictionary[command]) if stack_size == command_size+1: - UserID = self.DB.Bot_GetUserID(chat_id) - stack = self.DB.Bot_getStack(chat_id) - self.DB.Bot_flushStack(chat_id) + UserID = self._DB.Bot_GetUserID(chat_id) + stack = self._DB.Bot_getStack(chat_id) + self._DB.Bot_flushStack(chat_id) - packet = convertDBStack(stack,self.CommandDictionary) + packet = convertDBStack(stack,self._CommandDictionary) -## p = multiprocessing.Process(target = AATC_Server.BotConnection, args = (UserID,chat_id,packet,self.OutputQueue)) +## p = multiprocessing.Process(target = AATC_Server.BotConnection, args = (UserID,chat_id,packet,self._OutputQueue)) ## p.start() - Thread_Name = random.randint(0,self.Exec_Processes-1) - self.EC_Queue.put((Thread_Name,"RunCommand",(UserID,chat_id,packet))) + Thread_Name = random.randint(0,self._Exec_Processes-1) + self._EC_Queue.put((Thread_Name,"RunCommand",(UserID,chat_id,packet))) else: - return self.CommandDictionary[command][stack_size]["Query"] + return self._CommandDictionary[command][stack_size]["Query"] except Exception as e: - return "Error processing message "+str(e) + "\n" + self.ShowCommandsList + return "Error processing message "+str(e) + "\n" + self._ShowCommandsList @@ -240,9 +240,9 @@ def processInput(self,messageText,chat_id): class CommandExecutor: def __init__(self,Thread_Name,Input_Queue,OutputQueue): - self.Thread_Name = Thread_Name - self.Input_Queue = Input_Queue - self.OutputQueue = OutputQueue + self._Thread_Name = Thread_Name + self._Input_Queue = Input_Queue + self._OutputQueue = OutputQueue self.mainLoop() @@ -250,7 +250,7 @@ def mainLoop(self): Exit = False while not Exit: try: - data = self.Input_Queue.get() + data = self._Input_Queue.get() command,arguments = data[0],data[1] if command == "Exit": Exit = True @@ -259,13 +259,13 @@ def mainLoop(self): elif command == "RunCommand": UserID,chat_id,packet = arguments[0],arguments[1],arguments[2] - AATC_Server.BotConnection(UserID,chat_id,packet,self.OutputQueue) + AATC_Server.BotConnection(UserID,chat_id,packet,self._OutputQueue) else: - print("CommandExecutor",self.Thread_Name," obtained incorrect command",command) + print("CommandExecutor",self._Thread_Name," obtained incorrect command",command) except Exception as e: - print("Exception in CommandExecutor",self.Thread_Name,"Error:",e) + print("Exception in CommandExecutor",self._Thread_Name,"Error:",e) @@ -407,8 +407,8 @@ def CreateCommandDictionary(): ##import sqlite3 as sql ##class DB_Connection: ## def __init__(self): -## self.db_con = sql.connect("db.name") -## self.cur = self.db_con.cursor() +## self._DB_con = sql.connect("db.name") +## self.cur = self._DB_con.cursor() ## ## def addValue(self,value,chat_id): ## self.cur.execute("SELECT MAX(stack_pos) FROM InputStack WHERE chat_id = ?",(chat_id,)) @@ -418,7 +418,7 @@ def CreateCommandDictionary(): ## else: ## stack_pos = 0 ## self.cur.execute("INSERT INTO InputStack VALUES(?,?,?)",(chat_id,stack_pos,value)) -## self.db_con.commit() +## self._DB_con.commit() ## ## def getCommand(self,chat_id): ## self.cur.execute("SELECT value FROM InputStack WHERE chat_id = ? AND stack_pos = 0",(chat_id,)) @@ -437,7 +437,7 @@ def CreateCommandDictionary(): ## ## def flushStack(self,chat_id): ## self.cur.execute("DELETE FROM InputStack WHERE chat_id = ?",(chat_id,)) -## self.db_con.commit() +## self._DB_con.commit() ## ## ## ############################################################## @@ -448,7 +448,7 @@ def CreateCommandDictionary(): ## self.cur.execute("INSERT INTO Sessions VALUES(?,?)",(chat_id,UserID)) ## else: ## self.cur.execute("UPDATE Sessions SET UserID = ? WHERE chat_id = ?",(UserID,chat_id)) -## self.db_con.commit() +## self._DB_con.commit() ## ## def GetUserID(self,chat_id): ## self.cur.execute("SELECT UserID FROM Sessions WHERE chat_id = ?",(chat_id,)) @@ -469,7 +469,7 @@ def CreateCommandDictionary(): ## self.cur.execute("DROP TABLE IF EXISTS Sessions") ## self.cur.execute("CREATE TABLE IF NOT EXISTS InputStack(chat_id INT , stack_pos INT, value TEXT)") ## self.cur.execute("CREATE TABLE IF NOT EXISTS Sessions(chat_id INT PRIMARY KEY, UserID INT)") -## self.db_con.commit() +## self._DB_con.commit() ##