def __init__(self): self.type = "EngineDataModule" # ||=======================|| # Program Classes self.engineDataController = EngineDataController() self.communicationController = CommunicationController(self.type) # ||=======================|| configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) # ||=======================|| self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Defaults self.pipes = {}
def __init__(self, networkClient): self.type = "ControllerDataSync" self.active = False # ||=======================|| # Program Classes self.networkClient = networkClient configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Communication Pipes # self.networkClientPipe = None # self.engineDataControllerPipe = None # ||=======================|| # Config <bool> self.debug = self.config["Debug"] self.log = self.config["Log"] # ||=======================|| # Defaults self.duty = "Inactive" self.childPipes = []
def __init__(self): self.type = "GpsController" self.active = False # ||=======================|| # Program Classes configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Communication Pipes # ||=======================|| # Config <bool> self.debug = self.config["Debug"] self.log = self.config["Log"] # ||=======================|| # Default Values self.duty = "Inactive" self.latitude = 41.3507584 self.longitude = -81.8814976
def __init__(self, username, password): self.username = username self.password = password opts = selenium.webdriver.chrome.options.Options() #useragent = UserAgent() # opts.add_argument("user-agent={}".format(useragent.random)) opts.add_argument('--disable-infobars') # Initialize webdriver OS Based.. operation_system = sys.platform if operation_system == "win32": self.browser = webdriver.Chrome(os.getcwd() + "/webdrivers/win/chromedriver.exe", options=opts) elif operation_system == "darwin": self.browser = webdriver.Chrome(os.getcwd() + "/webdrivers/mac/chromedriver", options=opts) elif operation_system == "linux" or operation_system == "linux2": self.browser = webdriver.Chrome(os.getcwd() + "/webdrivers/linux/chromedriver", options=opts) self.mConfig = ConfigLoader() self.mConfig.ReadConfig() self.commented_posts_count = 0 self.liked_posts_count = 0
def __init__(self): self.type = "NetworkClient" self.active = False # ||=======================|| # Program Classes configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Config <bool> self.debug = self.config["Debug"] self.log = self.config["Log"] # ||=======================|| # Config <string> self.host = self.config["Address"] self.port = self.config["Port"] # ||=======================|| # Defaults self.duty = "Inactive" self.connectionStatus = False self.connectionHolder = socket.socket() self.socketTimeout = 1
def __init__(self): self.type = "ThermoController" self.active = False # ||=======================|| # Program Classes configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Communication Pipes # ||=======================|| # Config <bool> self.debug = self.config["Debug"] self.log = self.config["Log"] # ||=======================|| # Default Values self.duty = "Inactive" self.temperature = 40 self.degreeUnit = "Fahrenheit"
def __init__(self): self.type = "RoboticsEngine" self.active = False # ||=======================|| # Program Config Varaibles self.useNetworkClient = True self.useControllerDataSync = True self.useEngineDataController = True # ||=======================|| # Program Classes self.networkClientModule = NetworkClientModule() self.engineDataModule = EngineDataModule() configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Config <bool> self.debug = self.config["Debug"] self.log = self.config["Log"] # ||=======================|| # Defaults self.duty = "Inactive" self.parentPipes = []
def __init__(self,BotHandle=None): super().__init__() self.botHandle = BotHandle self.config = ConfigLoader() self.config.ReadConfig() self.handle = Tk() self.handle.protocol('WM_DELETE_WINDOW', self.withdraw_window) self.handle.geometry('500x350') self.handle.title("InstagramBot 2020") self.handle.resizable(False, False) self.tab_main = ttk.Notebook(self.handle) self.account_tab = AccountTab(self.tab_main) self.settings_tab = SettingsTab(self.tab_main) self.comments_tab = CommentsTab(self.tab_main,self.botHandle.getDatabaseHandle()) self.hashtag_tab = HashtagTab(self.tab_main,self.botHandle.getDatabaseHandle()) self.stats_tab = StatsTab(self.tab_main) self.log_tab = LogTab(self.tab_main) self.donate_tab = ttk.Frame(self.tab_main) self.tab_main.add(self.donate_tab, text="Donation") def openweb(): webbrowser.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Q8EANTRLUBWZ6&source=url",new=1) photo = PhotoImage(file = "webdrivers/etc/paypal.png") Btn = Button(self.donate_tab, text = "Click me",image = photo,compound = BOTTOM, command=openweb) Btn.image = photo Btn.place(x=140,y=100) self.setupAccount() self.loadSettings() self.botHandle.getGuiHandle(self) self.temp_ban_text = tk.Label(self.account_tab.account_tab, text="Temp Ban: False") self.temp_ban_text.place(x=150,y=280) self.temp_ban_text.configure(font=Font(family="Consolas", size=11, weight="normal")) self.tab_main.pack(expand=1, fill='both')
def main(self): # ||=======================|| configLoader = ConfigLoader() config = configLoader.getConfig("FlaskServer") print(config["Address"]) print(self.networkServer.jsonify()) print(sys.getsizeof(self.networkServer.jsonify())) self.debugLogger = DebugLogger("Main") self.debugLogger.setMessageSettings(True, True, True) for i in range(650): # print(i) self.debugLogger.log("Warning", "Hello World "+str(i))
def main(): settings = ConfigLoader("./config.yml").config keyboardWatcher = KeyboardWatcher() for setting in settings: keyboardWatcher.addShortcut(setting["shortcut"], setting["script"], setting["suppress"]) keyboardWatcher.run()
class IRCBot: def __init__(self, configname): self.config = ConfigLoader(configname) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.irc = IRCInterface(self.socket) self.plugins = {} self.dispatcher = EventDispatcher(self.irc) def rise(self): self.loadAllPlugins() self.connect() def loadPlugin(self, pluginName): plugin = importlib.import_module("plugins." + pluginName) for name in dir(plugin): local = getattr(plugin, name) if hasattr(local, "_ircEvent"): self.dispatcher.hookEvent(getattr(local, "_ircEvent"), local) def loadAllPlugins(self): for m in self.config.get("plugins"): self.loadPlugin(m) def connect(self): self.socket.connect( (self.config.get("server"), int(self.config.get("port"))) ) self.handshake() self.loop() def handshake(self): self.irc.nick(self.config.get("nick")) self.irc.user(self.config.get("nick"), "...", "...", "...") for channel in self.config.get("channels"): self.irc.join(channel) def loop(self): buffer = "" while True: data = self.irc.read() for cmd in data: if cmd["command"] == "PING": self.irc.pong(cmd["params"][0]) self.dispatcher.dispatch(cmd)
def __init__(self): self.type = "EngineDataController" self.active = False # ||=======================|| # Data Storage Types self.dataStorage = { "NetworkClient": CacheModule(), "RoboticsEngine": CacheModule() } # self.networkClientCache = NetworkClientCache() # ||=======================|| # Program Classes configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Communication Pipes self.networkClientPipe = None # ||=======================|| # Config <bool> self.debug = self.config["Debug"] self.log = self.config["Log"] self.useCache = { "NetworkClient": self.config["useNetworkClientCache"], "RoboticsEngine": self.config["useRoboticsEngineCache"] } # ||=======================|| # Defaults self.duty = "Inactive" self.parentPipes = [] self.childPipes = []
def __init__(self): self.type = "NetworkClientModule" # ||=======================|| # Program Classes self.networkClient = NetworkClient() self.controllerDataSync = ControllerDataSync(self.networkClient) # ||=======================|| configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) # ||=======================|| self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"]))
def main(): IPs = dict() # Get settings from configuration file settings = ConfigLoader.load(__file__, 'whitelist.cf') # Prepare the dispatcher socket context = zmq.Context() dispatcher = context.socket(zmq.ROUTER) dispatcher.bind(settings['dispatcher']) # Start the worker processes processes = [] for thread in xrange(settings['processes']): p = multiprocessing.Process(target=worker, kwargs={'settings': settings}) processes.append(p) p.start() # Send jobs to the active threads for url in settings['httpLists'] + settings['spfDomains']: # LRU worker is next waiting in the queue address, empty, ready, prevResult = dispatcher.recv_multipart() # Send the task to the worker dispatcher.send_multipart([address, b'', url]) # The worker might have sent a result with the ready message if prevResult == '': continue # We received a result, add it to the dictionary IPs[prevResult] = 1 # We're done, tell workers to exit for i in range(settings['processes']): # LRU worker is next waiting in the queue address, empty, ready, prevResult = dispatcher.recv_multipart() dispatcher.send_multipart([address, b'', b'term']) # The worker might have sent a result with the ready message if prevResult == '': continue # We received a result, add it to the dictionary IPs[prevResult] = 1 for ipSet in IPs: ips = msgpack.unpackb(ipSet) print "#{}".format(ips[0]) for IP in ips[1]: print IP
def __init__(self, _class): self.type = _class + ".CommunicationController" # ||=======================|| configLoader = ConfigLoader() self.config = configLoader.getConfig(self.type) # ||=======================|| self.debugLogger = DebugLogger(self.type) self.debugLogger.setMessageSettings( ast.literal_eval(self.config["Debug"]), ast.literal_eval(self.config["Standard"]), ast.literal_eval(self.config["Warning"]), ast.literal_eval(self.config["Error"])) # ||=======================|| # Defaults self.duty = "Inactive" self.pipes = {} self.connectionList = {}
def set_smartcard_puk(self, puk): ConfigLoader.set_smartcard_puk(self, puk) self.config.set('smartcard', 'puk', puk)
def set_timestamp_password(self, password): ConfigLoader.set_timestamp_password(self, password) self.config.set('timestamp', 'password', password)
def set_smartcard_pin(self, pin): ConfigLoader.set_smartcard_pin(self, pin) self.config.set('smartcard', 'pin', pin)
def __init__(self, configname): self.config = ConfigLoader(configname) self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.irc = IRCInterface(self.socket) self.plugins = {} self.dispatcher = EventDispatcher(self.irc)
def set_timestamp_username(self, username): ConfigLoader.set_timestamp_username(self, username) self.config.set('timestamp', 'username', username)
class InstagramMain(): def __init__(self, username, password): self.username = username self.password = password opts = selenium.webdriver.chrome.options.Options() #useragent = UserAgent() # opts.add_argument("user-agent={}".format(useragent.random)) opts.add_argument('--disable-infobars') # Initialize webdriver OS Based.. operation_system = sys.platform if operation_system == "win32": self.browser = webdriver.Chrome(os.getcwd() + "/webdrivers/win/chromedriver.exe", options=opts) elif operation_system == "darwin": self.browser = webdriver.Chrome(os.getcwd() + "/webdrivers/mac/chromedriver", options=opts) elif operation_system == "linux" or operation_system == "linux2": self.browser = webdriver.Chrome(os.getcwd() + "/webdrivers/linux/chromedriver", options=opts) self.mConfig = ConfigLoader() self.mConfig.ReadConfig() self.commented_posts_count = 0 self.liked_posts_count = 0 def WaitForObject(self, type, string): try: return selenium.webdriver.support.ui.WebDriverWait( self.browser, 5).until(EC.presence_of_element_located((type, string))) except Exception as error: with open("errorlog.txt", "a") as errorfile: finalmsg = "[{}] Message: {}\n".format( datetime.now().strftime("%d-%m-%Y / %H:%M:%S"), error) errorfile.write(finalmsg) return False def WaitForObjects(self, type, string): try: return selenium.webdriver.support.ui.WebDriverWait( self.browser, 5).until(EC.presence_of_all_elements_located((type, string))) except Exception as error: with open("errorlog.txt", "a") as errorfile: finalmsg = "[{}] Message: {}\n".format( datetime.now().strftime("%d-%m-%Y / %H:%M:%S"), error) errorfile.write(finalmsg) return False def FindByCSSAndAttribute(self, mobject, css, attribute): try: return mobject.find_element_by_css_selector(css).get_attribute( attribute) except: return False def ClickObject(self, mObject): try: mObject.click() return True except Exception as error: with open("errorlog.txt", "a") as errorfile: finalmsg = "[{}] Message: {}\n".format( datetime.now().strftime("%d-%m-%Y / %H:%M:%S"), error) errorfile.write(finalmsg) return False def login(self): self.browser.get("https://www.instagram.com/accounts/login") login_objects = self.WaitForObjects(By.CSS_SELECTOR, "input._2hvTZ.pexuQ.zyHYP") if login_objects != False: login_objects[0].send_keys(self.username) login_objects[1].send_keys(self.password) login_objects[1].send_keys(Keys.ENTER) time.sleep(3) ''' Bot Functions ''' def collect_photos_by_hashtag(self, hashtag): self.browser.get(f"https://www.instagram.com/explore/tags/{hashtag}/") for n in range(1, 8): self.browser.execute_script("window.scrollTo(0, {})".format(n * 4000)) time.sleep(1) all_photos = self.WaitForObjects(By.CSS_SELECTOR, "div.v1Nh3.kIKUG._bz0w") if all_photos != False: all_links = [] for photo in all_photos: link = self.FindByCSSAndAttribute(photo, 'a', 'href') if link != False: all_links.append(link) liked_photos = self.mConfig.ReadLikedPhotos() filtered_links = [] for link in all_links: if link in liked_photos: continue filtered_links.append(link) return filtered_links return False def like(self, photo): if self.liked_posts_count < self.mConfig.likestoday: self.browser.get(photo) time.sleep(random.randint(2, 5)) like_photo = self.WaitForObject(By.CSS_SELECTOR, "[aria-label='Gefällt mir']") if like_photo != False: like_photo.click() self.mConfig.SaveLikedPhoto(photo) self.liked_posts_count += 1 def get_Profile(self): profile_link = self.WaitForObject(By.CLASS_NAME, "sqdOP.yWX7d._8A5w5.ZIAjV") if profile_link != False: return profile_link.get_attribute('href') elif profile_link == False: return False def follow_user(self, userprofile): followed_pofiles_list, _ = self.mConfig.ReadFollowedProfiles() if userprofile not in followed_pofiles_list: self.browser.get(userprofile) follow_button = self.WaitForObject(By.CLASS_NAME, "_5f5mN.jIbKX._6VtSN.yZn4P") if follow_button != False: follow_button.click() with open("settings/followed.json") as oldfile: data = json.load(oldfile) data["follow"].append({ "link": userprofile, "timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S") }) with open("settings/followed.json", "w+") as newfile: json.dump(data, newfile, indent=4) def unfollow_users(self): _, unfollow_list = self.mConfig.ReadFollowedProfiles() for unfollow in unfollow_list: self.browser.get(unfollow) unfollow_button = self.WaitForObject(By.CLASS_NAME, "_5f5mN.-fzfL._6VtSN.yZn4P") if unfollow_button != False: unfollow_button.click() unfollow_button2 = self.WaitForObject(By.CLASS_NAME, "aOOlW.-Cab_") if unfollow_button2 != False: unfollow_button2.click() with open("settings/followed.json") as file: data = json.load(file) for follow in data['follow'][:]: if follow['link'] == unfollow: data['follow'].remove(follow) with open("settings/followed.json", "w+") as newfile: json.dump(data, newfile, indent=4) #time between each Unfollow => 4 to 20 Seconds time.sleep(random.randint(4, 20)) def write_comment(self, link): if self.commented_posts_count < self.mConfig.commentstoday: commentbox = self.WaitForObject(By.CLASS_NAME, "Ypffh") if commentbox != False: commentbox.click() commentbox = self.WaitForObject(By.CLASS_NAME, "Ypffh") if commentbox != False: commentbox.clear() commentbox.send_keys(self.mConfig.RandomComment()) commentbox.send_keys(Keys.ENTER) self.commented_posts_count += 1 self.mConfig.SaveCommentsPosted(link) def write_comment_on_post(self, link, comment): self.browser.get(link) commentbox = self.WaitForObject(By.CLASS_NAME, "Ypffh") if commentbox != False: commentbox.click() commentbox = self.WaitForObject(By.CLASS_NAME, "Ypffh") if commentbox != False: commentbox.clear() commentbox.send_keys(comment) commentbox.send_keys(Keys.ENTER) def AcceptFollowers(self): self.browser.get( "https://www.instagram.com/accounts/activity/?followRequests") anfragen = self.WaitForObjects(By.CLASS_NAME, "sqdOP.L3NKy.y3zKF") if anfragen != False: follow_buttons = [] #wir filtern die bestätigen schnell for x in anfragen: if x.text == "Bestätigen" or x.text == "Accept": follow_buttons.append(x) anfragen_count = 0 for anfrage in follow_buttons: if self.ClickObject(anfrage) != False: anfragen_count += 1 # Wait 1 Second between each Accept. time.sleep(1) print("{} neue Follower".format(anfragen_count)) def comment_my_feed(self): self.browser.get("https://www.instagram.com/") check_btn = self.WaitForObject(By.CLASS_NAME, "aOOlW.HoLwm") if check_btn != False: check_btn.click() #load already commented posts already_commented_posts = [] with open("settings/commentsfeed.json") as f: data = json.load(f) for x in data['feedcomment']: already_commented_posts.append(x) #scroll feed url_list = [] for x in range(0, 10): new_posts = self.WaitForObjects(By.CLASS_NAME, "c-Yi7") if new_posts != False: for post in new_posts: url = post.get_attribute('href') if url not in already_commented_posts: url_list.append(url) self.browser.execute_script("window.scrollTo(0, {})".format(4000 * x)) time.sleep(2) url_list = list(dict.fromkeys(url_list)) for url in url_list: self.write_comment_on_post(url, "Nice Job! :)") data['feedcomment'].append(url) with open("settings/commentsfeed.json", "w+") as newfile: json.dump(data, newfile, indent=4) time.sleep(2) ''' Not Finished .... ''' def follow_followers_of_user(self, user): self.browser.get( "https://www.instagram.com/{}/following/".format(user)) btn_abos = self.WaitForObjects(By.CLASS_NAME, "-nal3") if btn_abos != False: btn_abos[2].click() print("Sleep") time.sleep(2) self.browser.execute_script("window.scrollTo(0, 4000)") time.sleep(5) temp_buttons = self.WaitForObjects(By.CLASS_NAME, "sqdOP.L3NKy.y3zKF") print("buttons: ", len(temp_buttons)) follow_users = [] if temp_buttons != False: for button in temp_buttons: if button.text == "Folgen" or button.text == "Follow": follow_users.append(button) for user in follow_users: user.click() time.sleep(0.5)
class MainGui(): def __init__(self,BotHandle=None): super().__init__() self.botHandle = BotHandle self.config = ConfigLoader() self.config.ReadConfig() self.handle = Tk() self.handle.protocol('WM_DELETE_WINDOW', self.withdraw_window) self.handle.geometry('500x350') self.handle.title("InstagramBot 2020") self.handle.resizable(False, False) self.tab_main = ttk.Notebook(self.handle) self.account_tab = AccountTab(self.tab_main) self.settings_tab = SettingsTab(self.tab_main) self.comments_tab = CommentsTab(self.tab_main,self.botHandle.getDatabaseHandle()) self.hashtag_tab = HashtagTab(self.tab_main,self.botHandle.getDatabaseHandle()) self.stats_tab = StatsTab(self.tab_main) self.log_tab = LogTab(self.tab_main) self.donate_tab = ttk.Frame(self.tab_main) self.tab_main.add(self.donate_tab, text="Donation") def openweb(): webbrowser.open("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=Q8EANTRLUBWZ6&source=url",new=1) photo = PhotoImage(file = "webdrivers/etc/paypal.png") Btn = Button(self.donate_tab, text = "Click me",image = photo,compound = BOTTOM, command=openweb) Btn.image = photo Btn.place(x=140,y=100) self.setupAccount() self.loadSettings() self.botHandle.getGuiHandle(self) self.temp_ban_text = tk.Label(self.account_tab.account_tab, text="Temp Ban: False") self.temp_ban_text.place(x=150,y=280) self.temp_ban_text.configure(font=Font(family="Consolas", size=11, weight="normal")) self.tab_main.pack(expand=1, fill='both') def withdraw_window(self,x = None): self.handle.destroy() os._exit(1) def AccountLogin(self): with open("settings.json") as oldfile: data = json.load(oldfile) data["username"] = self.account_tab.getUsername() data["password"] = self.account_tab.getPassword() with open("settings.json", "w+") as newfile: json.dump(data, newfile, indent=4) self.botHandle.Login() def AccountStartBot(self): self.botHandle.bot_running = True def AccountStopBot(self): self.botHandle.bot_running = False def setupAccount(self): login_button = tk.Button(self.account_tab.account_tab, text="Login",command=lambda: self.AccountLogin()) login_button.place(x=100,y=90) stop_button = tk.Button(self.account_tab.account_tab, text="Start",command=lambda: self.AccountStartBot()) stop_button.place(x=190,y=90) stop_button = tk.Button(self.account_tab.account_tab, text="Stop",command=lambda: self.AccountStopBot()) stop_button.place(x=280,y=90) browser_choice = IntVar(value=2) def loadSettings(self): self.account_tab.setUsername(self.config.getUsername()) self.account_tab.setPassword(self.config.getPassword()) self.settings_tab.like_settings.setMaxLikesToday(self.config.likestoday) self.settings_tab.like_settings.setLikeSleep(self.config.getLikeSleep()) self.settings_tab.comment_settings.setMaxCommentsToday(self.config.commentstoday) self.settings_tab.comment_settings.setCommentSleep(self.config.getCommentSleep()) self.settings_tab.follow_settings.setFollowSleep(self.config.getFollowSleep()) self.settings_tab.unfollow_settings.setUnfollowMinutes(self.config.getUnfollowTime()) self.settings_tab.acceptfollowers_settings.setAcceptfollowersSleepText(self.config.getAcceptFollowerTime()) self.settings_tab.commentfeed_settings.setCommentFeedSleep(self.config.getCommentMyFeedTime()) def start_gui(self): self.handle.mainloop()
def __init__(self): self.devconf = ConfigLoader('./res/models/sony_ericsson_w200.json') #with open('./res/models/sony_ericsson_w200.json') as f: # self.devconf = json.load(f) self.base = ShowBase() self.loader = self.base.loader self.model = self.loader.loadModel(self.devconf.model_path) self.model.reparentTo(self.base.render) self.base.disableMouse() self.base.camera.setPos( self.devconf.initial_position['x'], self.devconf.initial_position['y'], self.devconf.initial_position['z']) self.model.setHpr( self.devconf.model_transformation['x'], self.devconf.model_transformation['y'], self.devconf.model_transformation['z']) mat = Mat4(self.base.camera.getMat()) mat.invertInPlace() self.base.mouseInterfaceNode.setMat(mat) self.base.enableMouse() self.screen = self.model.find(self.devconf.model_texture_path) self.list_app = ListApp(self, self.devconf) #self.music_app = MusicApp(self) self.dial_app = DialApp(self, self.devconf) self.apps = {} self.events = EventDispatcher(self, self.devconf.device_name) self.apps["init"] = InitApp(self, self.devconf) self.apps["Dial"] = self.display_dial_screen self.apps["menu"] = MainMenu(self, self.devconf) #self.apps["Reproductor"] = self.play #self.apps["Reproductor de Audio"] = self.display_list #self.apps["Camara"] = CameraApp(self) #self.apps["Album Fotografico"] = PhotoApp(self) self.apps["Llamadas"] = self.display_list self.apps["Contactos"] = self.display_list self.apps["Mensajes"] = self.display_list self.apps["Juegos"] = self.display_list self.apps["Utileria"] = self.display_list #self.apps["Reproducir Todas"] = self.play #self.apps["Lista de Albums"] = self.list_albums #self.apps["Lista de Artistas"] = self.list_artists #self.apps["Lista de Contactos"] = self.list_contacts #self.apps["Dial Contact"] = self.dial_contact #self.apps["Llamadas Perdidas"] = self.list_lost_calls #self.apps["Llamadas Contestadas"] = self.list_answered_calls #self.apps["Llamadas Marcadas"] = self.list_done_calls self.launch("init")
def __init__(self,initPage:str = None): configLoader = ConfigLoader() self.url=configLoader.getUrl() self.driverPath=configLoader.getChromeDriverPath() self.initWebdriver(initPage)
#!/usr/bin/env python __author__ = 'jintao' import thread, threading, time from Packet import Packet, PacketManage from BinlogEvent import BinlogEventManage from MYSQLChannel import MYSQLChannel from BinlogDataManage import BinlogDataManage from ConfigLoader import ConfigLoader from BinlogHandle import HandlerThread, BinlogHandlerManage, BinlogHandler global_config = ConfigLoader() global_binlog_event_manage = BinlogEventManage() global_binlog_data_manage = BinlogDataManage() global_packet_manage = PacketManage(global_binlog_event_manage, global_binlog_data_manage) global_signal = threading.Event() def start_sync(): global global_config start_pos = global_config.pos() start_binlog = global_config.binlog() global_binlog_data_manage.set_filename(start_binlog) global_binlog_data_manage.set_position(start_pos) while True: mysql_channel = MYSQLChannel(global_config.host(), global_config.port(),
class KeyLocationLoader: """ Load all of the coordinates of the OSK keys into a dictionary key_locations. Loads from the directory specified in KEY_IMAGE_BASE_PATH. Looks for keys in the region of the OSK by first looking for a match for OSK_FILE_NAME. """ KEY_IMAGE_BASE_PATH = ConfigLoader.get('key.image.base.path') OSK_FILE_NAME = ConfigLoader.get('osk.file.name') script_path = pathlib.Path(__file__).parent.absolute() key_image_full_path = os.path.join(script_path, KEY_IMAGE_BASE_PATH) # maps the key name to the coordinates of it's location on screen # key name is loaded from the file name minus the extension key_locations: KeyLocation = {} maple_logger = Logger() def __init__(self): self.maple_logger.info("Initializing keys from path: {0}...", self.key_image_full_path) now = datetime.datetime.now() self.__getKeyboardRegion() self.__loadKeys() self.maple_logger.debug("Loaded keys in {0} seconds.", datetime.datetime.now() - now) def __getKeyboardRegion(self): keyboard_file_path = os.path.join(self.key_image_full_path, self.OSK_FILE_NAME) self.maple_logger.info("Loading keyboard at path: {0}", keyboard_file_path) self.keyboard_region = pyautogui.locateOnScreen(keyboard_file_path, confidence=0.9) if self.keyboard_region is None: self.maple_logger.warning( "Unable to find OSK keyboard. Ensure the OSK window is " "at the smallest size and screen resolution is at 1920x1080.") raise Exception("Unable to find OSK.") else: self.maple_logger.debug("Found keyboard at region: {0}", self.keyboard_region) def __loadKeys(self): """ Load all of the key locations on the currently open On-Screen Keyboard (OSK), since finding them is expensive since it needs to scan the entire screen for a match (or a specified location, but ... whatever) """ key_image_file_names = os.listdir(self.key_image_full_path) self.maple_logger.info("Loading {0} keys.", len(key_image_file_names)) for key_image_file_name in key_image_file_names: self.__loadKey(key_image_file_name) def __loadKey(self, key_image_file_name: str): """ Load key into our key_locations dictionary. :param key_image_file_name: the key image file name (should match the file name e.g. ${key_name}.png) """ # get the key name from the file name e.g. ${key_name}.png key_name = key_image_file_name.split('.')[0] self.maple_logger.debug("Loading key: {0}", key_name) self.key_locations[key_name] = self.__getKeyLocation( key_image_file_name) def __getKeyLocation(self, key_image_file_name: str) -> ScreenCoordinate: key_file_path = os.path.join(self.key_image_full_path, key_image_file_name) self.maple_logger.debug("Looking in path {0}", key_file_path) key_location = pyautogui.locateOnScreen(key_file_path, region=self.keyboard_region, confidence=0.9) if key_location is None: self.maple_logger.warning("Unable to find key {0}", key_image_file_name) else: self.maple_logger.debug("Found at coord: {0}", key_location) return key_location def getKeyLocation(self, key_name: str) -> ScreenCoordinate: return self.key_locations[key_name]
def set_smartcard_driver_path(self, path): ConfigLoader.set_smartcard_driver_path(self, path) self.config.set('library', 'smartcard_driver_path', path)
def set_engine_driver_path(self, path): ConfigLoader.set_engine_driver_path(self, path) self.config.set('library', 'engine_driver_path', path)
def make_IPython(argv=[''],user_ns=None,debug=0,rc_override=None): """This is a dump of IPython into a single function. Later it will have to be broken up in a sensible manner.""" if sys.version[0:3] < '2.1': print 'IPython requires Python Version 2.1 or above. Sorry.' sys.exit() #---------------------------------------------------------------------- # Defaults and initialization # __IP is the main global that lives throughout and represents the whole # application. If the user redefines it, all bets are off as to what # happens. # __IP is the name of he global which the caller will have accessible as # __IP.name. We set its name via the first parameter passed to # InteractiveShell: IP = InteractiveShell('__IP',user_ns=user_ns) # Put 'help' in the user namespace from pydoc import help IP.user_ns['help'] = help # IPython itself shouldn't crash. This will produce a detailed post-mortem # if it does if debug: import ultraTB sys.excepthook = ultraTB.VerboseTB(call_pdb=1) else: import CrashHandler sys.excepthook = CrashHandler.CrashHandler(IP) IP.BANNER_PARTS = ['Python %s\n' 'Type "copyright", "credits" or "license" ' 'for more information.\n' % (sys.version.split('\n')[0],), "IPython %s -- An enhanced Interactive Python." % (__version__,), """? -> Introduction to IPython's features. @magic -> Information about IPython's 'magic' @ functions. help -> Python's own help system. object? -> Details about 'object'. ?object also works, ?? prints more. """ ] IP.usage = interactive_usage # default directory for configuration ipythondir = os.path.abspath(os.environ.get('IPYTHONDIR', os.path.join(IP.home_dir,'.ipython') ) ) # suffix to use in all rc-files: if os.name == 'posix': rc_suffix = '' else: rc_suffix = '.ini' # we need the directory where IPython itself is installed import IPython IPython_dir = os.path.dirname(IPython.__file__) del IPython #------------------------------------------------------------------------- # Command line handling # Valid command line options (uses DPyGetOpt syntax, like Perl's # GetOpt::Long) # Any key not listed here gets deleted even if in the file (like session # or profile). That's deliberate, to maintain the rc namespace clean. # Each set of options appears twice: under _conv only the names are # listed, indicating which type they must be converted to when reading the # ipythonrc file. And under DPyGetOpt they are listed with the regular # DPyGetOpt syntax (=s,=i,:f,etc). # Make sure there's a space before each end of line (they get auto-joined!) cmdline_opts = ('automagic! banner! cache_size|cs=i classic|cl ' 'color_info! confirm_exit! ' 'debug! deep_reload! editor=s log|l messages! nosep pdb! ' 'pprint! prompt_in1|pi1=s prompt_in2|pi2=s prompt_out|po=s ' 'quick screen_length|sl=i ' 'colors|c=s logfile|lf=s logplay|lp=s profile|p=s ' 'readline! readline_omit__names! ' 'rcfile=s separate_in|si=s separate_out|so=s ' 'separate_out2|so2=s xmode=s ' 'magic_docstrings ') # Options that can *only* appear at the cmd line (not in rcfiles). # The "ignore" option is a kludge so that Emacs buffers don't crash, since # the 'C-c !' command in emacs automatically appends a -i option at the end. cmdline_only = 'help ignore|i ipythondir=s Version upgrade' # Build the actual name list to be used by DPyGetOpt opts_names = qw(cmdline_opts) + qw(cmdline_only) # Set sensible command line defaults. # This should have everything from cmdline_opts and cmdline_only opts_def = Struct(automagic = 1, banner = 1, cache_size = 1000, classic = 0, colors = 'NoColor', color_info = 0, confirm_exit = 1, debug = 0, deep_reload = 0, editor = '0', help = 0, ipythondir = ipythondir, log = 0, logfile = '', logplay = '', messages = 1, nosep = 0, pdb = 0, pprint = 0, profile = '', prompt_in1 = 'In [%n]:', prompt_in2 = ' .%n.:', prompt_out = 'Out[%n]:', quick = 0, readline = 1, readline_omit__names = 0, rcfile = 'ipythonrc' + rc_suffix, screen_length = 0, separate_in = '\n', separate_out = '\n', separate_out2 = '', upgrade = 0, Version = 0, xmode = 'Verbose', magic_docstrings = 0, # undocumented, for doc generation ) # Things that will *only* appear in rcfiles (not at the command line). # Make sure there's a space before each end of line (they get auto-joined!) rcfile_opts = { qwflat: 'include import_mod import_all execfile ', qw_lol: 'import_some ', # for things with embedded whitespace: list_strings:'execute alias readline_parse_and_bind ', # Regular strings need no conversion: None:'readline_remove_delims ', } # Default values for these rc_def = Struct(include = [], import_mod = [], import_all = [], import_some = [[]], execute = [], execfile = [], alias = [], readline_parse_and_bind = [], readline_remove_delims = '', ) # Build the type conversion dictionary from the above tables: typeconv = rcfile_opts.copy() typeconv.update(optstr2types(cmdline_opts)) # FIXME: the None key appears in both, put that back together by hand. Ugly! typeconv[None] += ' ' + rcfile_opts[None] # Remove quotes at ends of all strings (used to protect spaces) typeconv[unquote_ends] = typeconv[None] del typeconv[None] # Build the list we'll use to make all config decisions with defaults: opts_all = opts_def.copy() opts_all.update(rc_def) # Build conflict resolver for recursive loading of config files: # - preserve means the outermost file maintains the value, it is not # overwritten if an included file has the same key. # - add_flip applies + to the two values, so it better make sense to add # those types of keys. But it flips them first so that things loaded # deeper in the inclusion chain have lower precedence. conflict = {'preserve': ' '.join([ typeconv[int], typeconv[unquote_ends] ]), 'add_flip': ' '.join([ typeconv[qwflat], typeconv[qw_lol], typeconv[list_strings] ]) } # Now actually process the command line getopt = DPyGetOpt.DPyGetOpt() getopt.setIgnoreCase(0) getopt.parseConfiguration(opts_names) try: getopt.processArguments(argv) except: print cmd_line_usage warn('\nError in Arguments: ' + `sys.exc_value`) sys.exit() # convert the options dict to a struct for much lighter syntax later opts = Struct(getopt.optionValues) args = getopt.freeValues # this is the struct (which has default values at this point) with which # we make all decisions: opts_all.update(opts) # Options that force an immediate exit if opts_all.help: page(cmd_line_usage) sys.exit() if opts_all.Version: print __version__ sys.exit() if opts_all.magic_docstrings: IP.magic_magic('-latex') sys.exit() # Create user config directory if it doesn't exist. This must be done # *after* getting the cmd line options. if not os.path.isdir(opts_all.ipythondir): IP.user_setup(opts_all.ipythondir,rc_suffix,'install') # upgrade user config files while preserving a copy of the originals if opts_all.upgrade: IP.user_setup(opts_all.ipythondir,rc_suffix,'upgrade') # check mutually exclusive options in the *original* command line mutex_opts(opts,[qw('log logfile'),qw('rcfile profile'), qw('classic profile'),qw('classic rcfile')]) # default logfilename used when -log is called. IP.LOGDEF = 'ipython.log' # history file for saving commands in between sessions IP.histfile = os.path.join(opts_all.ipythondir,'history') #--------------------------------------------------------------------------- # Log replay # if -logplay, we need to 'become' the other session. That basically means # replacing the current command line environment with that of the old session # and moving on. # this is needed so that later we know we're in session reload mode, as # opts_all will get overwritten: load_logplay = 0 if opts_all.logplay: load_logplay = opts_all.logplay opts_debug_save = opts_all.debug try: logplay = open(opts_all.logplay) except IOError: if opts_all.debug: IP.InteractiveTB() warn('Could not open logplay file '+`opts_all.logplay`) # restore state as if nothing had happened and move on, but make # sure that later we don't try to actually load the session file logplay = None load_logplay = 0 del opts_all.logplay else: try: logplay.readline() logplay.readline(); # this reloads that session's command line cmd = logplay.readline()[6:] exec cmd # restore the true debug flag given so that the process of session # loading itself can be monitored. opts.debug = opts_debug_save # save the logplay flag so later we don't overwrite the log opts.logplay = load_logplay # now we must update our own structure with defaults opts_all.update(opts) # now load args cmd = logplay.readline()[6:] exec cmd logplay.close() except 'ha': logplay.close() if opts_all.debug: IP.InteractiveTB() warn("Logplay file lacking full configuration information.\n" "I'll try to read it, but some things may not work.") #------------------------------------------------------------------------- # set up output traps: catch all output from files, being run, modules # loaded, etc. Then give it to the user in a clean form at the end. msg_out = 'Output messages. ' msg_err = 'Error messages. ' msg_sep = '\n' msg = Struct(config = OutputTrap('Configuration Loader',msg_out, msg_err,msg_sep,debug, quiet_out=1), user_exec = OutputTrap('User File Execution',msg_out, msg_err,msg_sep,debug), logplay = OutputTrap('Log Loader',msg_out, msg_err,msg_sep,debug), summary = '' ) #------------------------------------------------------------------------- # Process user ipythonrc-type configuration files # turn on output trapping and log to msg.config # remember that with debug on, trapping is actually disabled msg.config.trap_all() # look for rcfile in current or default directory try: opts_all.rcfile = filefind(opts_all.rcfile,opts_all.ipythondir) except IOError: if opts_all.debug: IP.InteractiveTB() warn('Configuration file %s not found. Ignoring request.' % (opts_all.rcfile) ) # 'profiles' are a shorthand notation for config filenames if opts_all.profile: try: opts_all.rcfile = filefind('ipythonrc-' + opts_all.profile + rc_suffix, opts_all.ipythondir) except IOError: if opts_all.debug: IP.InteractiveTB() opts.profile = '' # remove profile from options if invalid warn('Profile configuration file %s not found. Ignoring request.' % (opts_all.profile) ) # load the config file rcfiledata = None if opts_all.quick: print 'Launching IPython in quick mode. No config file read.' elif opts_all.classic: print 'Launching IPython in classic mode. No config file read.' elif opts_all.rcfile: try: cfg_loader = ConfigLoader(conflict) rcfiledata = cfg_loader.load(opts_all.rcfile,typeconv, 'include',opts_all.ipythondir, purge = 1, unique = conflict['preserve']) except: IP.InteractiveTB() warn('Problems loading configuration file '+ `opts_all.rcfile`+ '\nStarting with default -bare bones- configuration.') else: warn('No valid configuration file found in either currrent directory\n'+ 'or in the IPython config. directory: '+`opts_all.ipythondir`+ '\nProceeding with internal defaults.') #------------------------------------------------------------------------ # Set exception handlers in mode requested by user. otrap = OutputTrap(trap_out=1) # trap messages from magic_xmode IP.magic_xmode(opts_all.xmode) otrap.release_out() #------------------------------------------------------------------------ # Execute user config # first, create a valid config structure with the right precedence order: # defaults < rcfile < command line IP.rc = rc_def.copy() IP.rc.update(opts_def) if rcfiledata: # now we can update IP.rc.update(rcfiledata) IP.rc.update(opts) IP.rc.update(rc_override) # Store the original cmd line for reference: IP.rc.opts = opts IP.rc.args = args # create a *runtime* Struct like rc for holding parameters which may be # created and/or modified by runtime user extensions. IP.runtime_rc = Struct() # from this point on, all config should be handled through IP.rc, # opts* shouldn't be used anymore. # add personal .ipython dir to sys.path so that users can put things in # there for customization sys.path.append(IP.rc.ipythondir) sys.path.insert(0, '') # add . to sys.path. Fix from Prabhu Ramachandran # update IP.rc with some special things that need manual # tweaks. Basically options which affect other options. I guess this # should just be written so that options are fully orthogonal and we # wouldn't worry about this stuff! if IP.rc.classic: IP.rc.quick = 1 IP.rc.cache_size = 0 IP.rc.pprint = 0 IP.rc.prompt_in1 = '>>> ' IP.rc.prompt_in2 = '... ' IP.rc.prompt_out = '' IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0' IP.rc.colors = 'NoColor' IP.rc.xmode = 'Plain' # configure readline if IP.rc.readline: IP.init_readline() # update exception handlers with rc file status otrap.trap_out() # I don't want these messages ever. IP.magic_xmode(IP.rc.xmode) otrap.release_out() # activate logging if requested and not reloading a log if IP.rc.logplay: IP.magic_logstart(IP.rc.logplay + ' append') elif IP.rc.logfile: IP.magic_logstart(IP.rc.logfile) elif IP.rc.log: IP.magic_logstart() # find user editor so that it we don't have to look it up constantly if IP.rc.editor.strip()=='0': try: ed = os.environ['EDITOR'] except KeyError: if os.name == 'posix': ed = 'vi' # the only one guaranteed to be there! else: ed = 'notepad' # same in Windows! IP.rc.editor = ed # Recursive reload try: import deep_reload if IP.rc.deep_reload: __builtin__.reload = deep_reload.reload else: __builtin__.dreload = deep_reload.reload del deep_reload except ImportError: pass # Save the current state of our namespace so that the interactive shell # can later know which variables have been created by us from config files # and loading. This way, loading a file (in any way) is treated just like # defining things on the command line, and @who works as expected. # DON'T do anything that affects the namespace beyond this point! IP.internal_ns = __main__.__dict__.copy() #IP.internal_ns.update(locals()) # so our stuff doesn't show up in @who # Now run through the different sections of the users's config if IP.rc.debug: print 'Trying to execute the following configuration structure:' print '(Things listed first are deeper in the inclusion tree and get' print 'loaded first).\n' pprint(IP.rc.__dict__) for mod in IP.rc.import_mod: try: exec 'import '+mod in IP.user_ns except : IP.InteractiveTB() import_fail_info(mod) for mod_fn in IP.rc.import_some: if mod_fn == []: break mod,fn = mod_fn[0],' '.join(mod_fn[1:]) try: exec 'from '+mod+' import '+fn in IP.user_ns except : IP.InteractiveTB() import_fail_info(mod,fn) for mod in IP.rc.import_all: try: exec 'from '+mod+' import *' in IP.user_ns except : IP.InteractiveTB() import_fail_info(mod) for code in IP.rc.execute: try: exec code in IP.user_ns except: IP.InteractiveTB() warn('Failure executing code: ' + `code`) # Execute the files the user wants in ipythonrc for file in IP.rc.execfile: try: file = filefind(file,sys.path+[IPython_dir]) except IOError: warn(itpl('File $file not found. Skipping it.')) else: IP.safe_execfile(os.path.expanduser(file),IP.user_ns) # Load user aliases for alias in IP.rc.alias: IP.magic_alias(alias) # release stdout and stderr and save config log into a global summary msg.config.release_all() if IP.rc.messages: msg.summary += msg.config.summary_all() #------------------------------------------------------------------------ # Setup interactive session # Now we should be fully configured. We can then execute files or load # things only needed for interactive use. Then we'll open the shell. # Take a snapshot of the user namespace before opening the shell. That way # we'll be able to identify which things were interactively defined and # which were defined through config files. IP.user_config_ns = IP.user_ns.copy() # Force reading a file as if it were a session log. Slower but safer. if load_logplay: print 'Replaying log...' try: if IP.rc.debug: logplay_quiet = 0 else: logplay_quiet = 1 msg.logplay.trap_all() IP.safe_execfile(load_logplay,IP.user_ns, islog = 1, quiet = logplay_quiet) msg.logplay.release_all() if IP.rc.messages: msg.summary += msg.logplay.summary_all() except: warn('Problems replaying logfile %s.' % load_logplay) IP.InteractiveTB() # Load remaining files in command line msg.user_exec.trap_all() if IP.rc.args: name_save = IP.user_ns['__name__'] IP.user_ns['__name__'] = '__main__' for run in args: IP.safe_execfile(run,IP.user_ns) IP.user_ns['__name__'] = name_save msg.user_exec.release_all() if IP.rc.messages: msg.summary += msg.user_exec.summary_all() # since we can't specify a null string on the cmd line, 0 is the equivalent: if IP.rc.nosep: IP.rc.separate_in = IP.rc.separate_out = IP.rc.separate_out2 = '0' if IP.rc.separate_in == '0': IP.rc.separate_in = '' if IP.rc.separate_out == '0': IP.rc.separate_out = '' if IP.rc.separate_out2 == '0': IP.rc.separate_out2 = '' IP.rc.separate_in = IP.rc.separate_in.replace('\\n','\n') IP.rc.separate_out = IP.rc.separate_out.replace('\\n','\n') IP.rc.separate_out2 = IP.rc.separate_out2.replace('\\n','\n') # Determine how many lines at the bottom of the screen are needed for # showing prompts, so we can know wheter long strings are to be printed or # paged: num_lines_bot = IP.rc.separate_in.count('\n')+1 IP.rc.screen_length = IP.rc.screen_length - num_lines_bot # Initialize cache, set in/out prompts and printing system IP.outputcache = CachedOutput(IP.rc.cache_size, IP.rc.pprint, colors = IP.rc.colors, input_sep = IP.rc.separate_in, output_sep = IP.rc.separate_out, output_sep2 = IP.rc.separate_out2, ps1 = IP.rc.prompt_in1, ps2 = IP.rc.prompt_in2, ps_out = IP.rc.prompt_out, user_ns = IP.user_ns, input_hist = IP.input_hist) IP.magic_colors(IP.rc.colors) # user may have over-ridden the default print hook: try: IP.outputcache.__class__.display = IP.hooks.display except AttributeError: pass # Set calling of pdb on exceptions IP.InteractiveTB.call_pdb = IP.rc.pdb # I don't like assigning globally to sys, because it means when embedding # instances, each embedded instance overrides the previous choice. But # sys.displayhook seems to be called internally by exec, so I don't see a # way around it. sys.displayhook = IP.outputcache # we need to know globally if we're caching i/o or not IP.do_full_cache = IP.outputcache.do_full_cache # configure startup banner if IP.rc.banner: IP.BANNER = '\n'.join(IP.BANNER_PARTS) else: IP.BANNER = '' if IP.rc.profile: IP.BANNER += '\nIPython profile: '+IP.rc.profile+'\n' # add message log (possibly empty) IP.BANNER += msg.summary return IP
def loadConfig(self, configName): configLoader = ConfigLoader() config = configLoader.getConfig(configName) return config
queue_alarm = deque() lock_alarm = threading.Lock() queue_sensors = deque() lock_sensors = threading.Lock() queue_nfc = deque() lock_nfc = threading.Lock() queue_buttons = deque() lock_buttons = threading.Lock() running = True #ConfigParser config = ConfigLoader() validUid = config.getValidUid() service = AlarmService() service.setClassName("Main") def main_loop(): lcdControl.displayState(alarm.currentStatus()) while True: if queue_buttons: with lock_buttons: button = queue_buttons.popleft() if button == "MENU:exit": service.debug("Exit from menu") lcdControl.displayStateForced(alarm.currentStatus())