def init(): global __dht22__, __ds18x20__ if config.exists('sensors.dht22'): pin = Pin(int(config.get('sensors.dht22'))) __dht22__ = dht.DHT22(pin) if config.exists('sensors.ds18x20'): pin = Pin(int(config.get('sensors.ds18x20'))) ow = onewire.OneWire(pin) __ds18x20__ = ds18x20.DS18X20(ow)
def test_remove_desktop(): prog_manage.create_desktop("package", "Name", "test.sh", "Comment here", "False") try: assert config.exists( "~/.local/share/applications/test.sh-package.desktop") except AssertionError: print("create_desktop() failure, remove_desktop() might be okay.") prog_manage.remove_desktop("package", "test.sh-package") assert not config.exists( "~/.local/share/applications/test.sh-package.desktop")
def erase(): """Remove hamstall.""" if not (config.exists(config.full("~/.hamstall/hamstall.py"))): print("hamstall not detected so not removed!") generic.leave() config.vprint('Removing source line from bashrc') config.remove_line("~/.hamstall/.bashrc", "~/{}".format(config.read_config("ShellFile")), "word") config.vprint("Removing .desktop files") for prog in config.db["programs"]: if config.db["programs"][prog]["desktops"]: for d in config.db["programs"][prog]["desktops"]: try: os.remove(config.full("~/.local/share/applications/{}.desktop".format(d))) except FileNotFoundError: pass config.vprint('Removing hamstall directory') rmtree(config.full('~/.hamstall')) try: rmtree("/tmp/hamstall-temp") except FileNotFoundError: pass print("Hamstall has been removed from your system.") print('Please restart your terminal.') config.unlock() sys.exit(0)
def ask_file(question): """Get User Input for File. Get user input for a file Args: question (str): Question to ask user Returns: str: Path to file """ if config.mode == "cli": f = "asdf" while not config.exists(config.full(f)): f = input(question) return config.full(f) elif config.mode == "gui": layout = [ [sg.Text(question)], [sg.InputText(key="answer"), sg.FileBrowse()], [sg.Button("Submit")] ] window = sg.Window("tarstall-gui", layout, disable_close=True) while True: event, values = window.read() if event == "Submit": window.Close() return values["answer"]
def load_data(description, network): games_played = config.load_pickle("games_played") scores = config.load_pickle("scores") if games_played is None or scores is None: print("Starting from scratch") games_played = 1 scores = [] return games_played, scores, network weights_file = config.get_full_path("weights.hdf5") if config.exists(weights_file): network.model.load_weights(weights_file) print("Weights loaded") memory_file = config.get_full_path("memory_states") if config.exists(memory_file): network.memory = config.load_pickle("memory_states") print("Memory loaded") memory_file = config.get_full_path("outcomes") if config.exists(memory_file): network.memory = config.load_pickle("outcomes") print("Outcomes loaded") return games_played, scores, network
def first_time_setup(sym): """First Time Setup. Sets up hamstall for the first time. Args: sym (bool): Used for testing. If True, installed py's will be symlinked to originals, not copied. False means it will be copied and not symlinked. """ if config.exists(config.full('~/.hamstall/hamstall.py')): print('Please don\'t run first time setup on an already installed system!') generic.leave() print('Installing hamstall to your system...') try: os.mkdir(config.full("~/.hamstall")) except FileExistsError: rmtree(config.full("~/.hamstall")) os.mkdir(config.full("~/.hamstall")) try: os.mkdir(config.full("/tmp/hamstall-temp/")) except FileExistsError: rmtree(config.full("/tmp/hamstall-temp")) os.mkdir(config.full("/tmp/hamstall-temp/")) os.mkdir(config.full("~/.hamstall/bin")) config.create("~/.hamstall/database") create_db() config.create("~/.hamstall/.bashrc") # Create directories and files files = os.listdir() for i in files: i_num = len(i) - 3 if i[i_num:len(i)] == '.py': if sym: os.symlink(os.getcwd() + "/" + i, config.full("~/.hamstall/" + i)) else: try: copyfile(i, config.full('~/.hamstall/' + i)) except FileNotFoundError: print("A file is missing that was attempted to be copied! Install halted!") generic.leave(1) config.add_line("source ~/.hamstall/.bashrc\n", "~/{}".format(config.read_config("ShellFile"))) config.add_line("alias hamstall='python3 ~/.hamstall/hamstall.py'\n", "~/.hamstall/.bashrc") # Add bashrc line print('First time setup complete!') print('Please run the command "source ~/{}" or restart your terminal.'.format(config.read_config("ShellFile"))) print('Afterwards, you may begin using hamstall with the hamstall command!') generic.leave()
def create_desktop(program_internal_name): """Create Desktop. Walks the user through creating a .desktop file for a program Args: program_internal_name (str): Name of program as stored in the database """ files = os.listdir(config.full('~/.hamstall/bin/' + program_internal_name + '/')) print(' '.join(files)) program_file = '/Placeholder/' config.vprint("Getting user inputs") while program_file not in files: # Get file to binlink from user program_file = input('Please enter a file listed above. If you would like to cancel, type exit: ') if program_file == "exit": return desktop_name = "{}-{}".format(program_file, program_internal_name) if config.exists("~/.local/share/applications/{}.desktop".format(desktop_name)): print("Desktop file already exists!") return exec_path = config.full("~/.hamstall/bin/{}/{}".format(program_internal_name, program_file)) path = config.full("~/.hamstall/bin/{}/".format(program_internal_name)) comment = "/" while not comment.replace(" ", "").isalnum() and comment != "": comment = input("Please input a comment for the application: ") if comment == "": comment = program_internal_name icon = ";" while not icon.replace("-", "").replace("_", "").replace("/", "").isalnum() and icon != "": icon = input("Enter the path to an icon, the name of the icon, or press ENTER for no icon! ") if icon != "": icon = "Icon=" + icon terminal = generic.get_input("Should this program launch a terminal to run it in? [y/N]", ['y', 'n'], 'n') if terminal.lower() == 'y': should_terminal = "True" else: should_terminal = "False" name = "/" while not name.replace(" ", "").isalnum() and name != "": name = input("Please enter a name: ") if name == "": name = program_internal_name ans = " " chosen_categories = [] categories = ["audio", "video", "development", "education", "game", "graphics", "network", "office", "science", "settings", "system", "utility", "end"] while ans.lower() != "end": print("Please enter categories, one at a time, from the list of .desktop categories below (defaults to " "Utility). Type \"end\" to end category selection. \n") print(", ".join(categories)) ans = generic.get_input("", categories, "Utility") if ans.capitalize() in chosen_categories or ans == "end": pass else: ans = ans.capitalize() chosen_categories.append(ans) if ans in ["Audio", "Video"] and not ("AudioVideo" in chosen_categories): chosen_categories.append("AudioVideo") if not chosen_categories: chosen_categories = ["Utility"] cats = ";".join(chosen_categories) + ";" # Get categories for the .desktop to_write = """ [Desktop Entry] Name={name} Comment={comment} Path={path} Exec={exec_path} {icon} Terminal={should_terminal} Type=Application Categories={categories} """.format(name=name, comment=comment, exec_path=exec_path, should_terminal=should_terminal, categories=cats, icon=icon, path=path) os.chdir(config.full("~/.local/share/applications/")) config.create("./{}.desktop".format(desktop_name)) with open(config.full("./{}.desktop".format(desktop_name)), 'w') as f: f.write(to_write) config.db["programs"][program_internal_name]["desktops"].append(desktop_name) print("\nDesktop file created!")
def handle(self): i=0 while 1: login=config.login() loginfo = self.request.recv(1024).strip().split('\t')[:2]#接收客户端的用户信息 user=loginfo[0] passwd=loginfo[1] log_statu=login.login(user,passwd)#获取登陆的状态发送给客户端 由客户端来判断是否登陆成功 if i>=2: u_id=config.exists(user) config.con.update('user_info','lockedtime',int(time.time()),u_id) break i+=1 if log_statu=='passwrong': self.request.sendall('passwrong') elif log_statu=='nouser': self.request.sendall('nouser') elif log_statu=='locked': self.request.sendall('locked') elif log_statu==True: home_dir=login.home if os.path.exists(home_dir)==False: os.system('mkdir -p %s'%home_dir) self.request.sendall('true') while 1: print "等待命令----------" get_data = self.request.recv(1024).strip().split()#等待命令接收 print get_data,'从客户端接收的参数。。。' if len(get_data)>=2: cmd, filename = get_data[:2]#取前两个列表的元素 target_file='%s/%s'%(home_dir,filename)#目标文件名 if cmd == 'get': len_buf=0 if os.path.exists(target_file)==True and os.path.getsize(target_file)!=0: size=os.path.getsize(target_file)#文件的总大小 print '正在发送 大小%s的文件'%size self.request.send(str(size))#将要下载的文件大小传值过去 time.sleep(0.05) with open(target_file,'rb')as f: while 1: #if not f.readline():break a=f.read(819600)#一次读16392byte if len(a)==0: g=self.request.recv(1024) self.request.sendall(md5sum(target_file)) break else: self.request.sendall(a) else: self.request.sendall('no') elif cmd == 'put': len_data=0#标记 while 1: str_tmp = self.request.recv(819600)#本地有一个缓冲区接收文件块 if str_tmp=='ok': self.request.sendall('down') get_md5=self.request.recv(1024)#接shou client MD5 locmd5=md5sum(target_file) print "server:%s client:%s"%(locmd5,get_md5) if locmd5==get_md5: self.request.sendall('ok') else: self.request.sendall('no') break if not len_data:#如果不存在len_data则创建文件并且赋值 ofh=open(target_file, 'wb+') ofh.writelines(str_tmp) len_data=1 ofh.close() size=os.path.getsize(target_file) self.request.send(str(size)) else: ofh=open(target_file, 'ab+') ofh.writelines(str_tmp) ofh.close() size=os.path.getsize(target_file) self.request.send(str(size))#文件现在的大小 elif cmd == 'del': statu=commands.getstatusoutput('rm -rf %s'%target_file) if statu[0]==0: self.request.sendall('删除%s成功'%get_data[1]) else: self.request.sendall("操作错误") else: statu=commands.getstatusoutput(get_data[0]) if statu[0]==0: self.request.sendall(statu[1]) else: self.request.sendall("操作错误") elif len(get_data)<2: print '%s %s'%(get_data[0],home_dir) statu=commands.getstatusoutput('%s %s'%(get_data[0],home_dir)) if statu[0]==0 and len(statu[1])!=0: self.request.sendall(statu[1]) print statu[1],'命令执行成功.' continue elif len(statu[1])==0: self.request.sendall("NUll") else: self.request.sendall("false") print '命令执行失败.' continue
def handle(self): i = 0 while 1: login = config.login() loginfo = self.request.recv(1024).strip().split( '\t')[:2] #接收客户端的用户信息 user = loginfo[0] passwd = loginfo[1] log_statu = login.login(user, passwd) #获取登陆的状态发送给客户端 由客户端来判断是否登陆成功 if i >= 2: u_id = config.exists(user) config.con.update('user_info', 'lockedtime', int(time.time()), u_id) break i += 1 if log_statu == 'passwrong': self.request.sendall('passwrong') elif log_statu == 'nouser': self.request.sendall('nouser') elif log_statu == 'locked': self.request.sendall('locked') elif log_statu == True: home_dir = login.home if os.path.exists(home_dir) == False: os.system('mkdir -p %s' % home_dir) self.request.sendall('true') while 1: print "等待命令----------" get_data = self.request.recv(1024).strip().split() #等待命令接收 print get_data, '从客户端接收的参数。。。' if len(get_data) >= 2: cmd, filename = get_data[:2] #取前两个列表的元素 target_file = '%s/%s' % (home_dir, filename) #目标文件名 if cmd == 'get': len_buf = 0 if os.path.exists( target_file ) == True and os.path.getsize(target_file) != 0: size = os.path.getsize(target_file) #文件的总大小 print '正在发送 大小%s的文件' % size self.request.send(str(size)) #将要下载的文件大小传值过去 time.sleep(0.05) with open(target_file, 'rb') as f: while 1: #if not f.readline():break a = f.read(819600) #一次读16392byte if len(a) == 0: g = self.request.recv(1024) self.request.sendall( md5sum(target_file)) break else: self.request.sendall(a) else: self.request.sendall('no') elif cmd == 'put': len_data = 0 #标记 while 1: str_tmp = self.request.recv( 819600) #本地有一个缓冲区接收文件块 if str_tmp == 'ok': self.request.sendall('down') get_md5 = self.request.recv( 1024) #接shou client MD5 locmd5 = md5sum(target_file) print "server:%s client:%s" % (locmd5, get_md5) if locmd5 == get_md5: self.request.sendall('ok') else: self.request.sendall('no') break if not len_data: #如果不存在len_data则创建文件并且赋值 ofh = open(target_file, 'wb+') ofh.writelines(str_tmp) len_data = 1 ofh.close() size = os.path.getsize(target_file) self.request.send(str(size)) else: ofh = open(target_file, 'ab+') ofh.writelines(str_tmp) ofh.close() size = os.path.getsize(target_file) self.request.send(str(size)) #文件现在的大小 elif cmd == 'del': statu = commands.getstatusoutput('rm -rf %s' % target_file) if statu[0] == 0: self.request.sendall('删除%s成功' % get_data[1]) else: self.request.sendall("操作错误") else: statu = commands.getstatusoutput(get_data[0]) if statu[0] == 0: self.request.sendall(statu[1]) else: self.request.sendall("操作错误") elif len(get_data) < 2: print '%s %s' % (get_data[0], home_dir) statu = commands.getstatusoutput( '%s %s' % (get_data[0], home_dir)) if statu[0] == 0 and len(statu[1]) != 0: self.request.sendall(statu[1]) print statu[1], '命令执行成功.' continue elif len(statu[1]) == 0: self.request.sendall("NUll") else: self.request.sendall("false") print '命令执行失败.' continue
print( 'Note: Running as root user will install programs for the root user to use!' ) if config.db == {"refresh": True}: # Downgrade check print("Hang tight! We're finishing up your downgrade...") config.create("~/.hamstall/database") prog_manage.create_db() config.db = config.get_db() config.write_db() print("We're done! Continuing hamstall execution...") if args.first: # Check if -f or --first is supplied prog_manage.first_time_setup(False) if not (config.exists('~/.hamstall/hamstall.py') ): # Make sure hamstall is installed """Install hamstall if it doesn't exist""" yn = generic.get_input( 'hamstall is not installed on your system. Would you like to install it? [Y/n]', ['y', 'n', 'debug'], 'y') if yn == 'y': prog_manage.first_time_setup(False) elif yn == 'debug': prog_manage.first_time_setup(True) else: print('hamstall not installed.') config.unlock() sys.exit(0) generic.leave()
def test_remove_desktop(monkeypatch): monkeypatch.setattr("sys.stdin", StringIO("test.sh-package")) prog_manage.remove_desktop("package") assert not config.exists("~/.local/share/applications/test.sh-package.desktop")
def test_create_desktop(monkeypatch): monkeypatch.setattr("sys.stdin", StringIO("test.sh\nComment here\n\nn\nName Here\n\nend\n")) prog_manage.create_desktop("package") assert config.exists("~/.local/share/applications/test.sh-package.desktop")
def run(): # Sets path of QML files qml_path = "" if os.path.isdir(sys.path[0] + "/qml"): qml_path = sys.path[0] + "/qml" else: qml_path = sys.path[0] + "/../qml" # Create a Qt Application object from the system arguments app = QtWidgets.QApplication(sys.argv) # Set the application icon app.setWindowIcon(QtGui.QIcon("assets/img/icon.png")) # Enable material design in the app os.environ["QT_QUICK_CONTROLS_STYLE"] = "Material" # When the SIGINT signal is received, exit signal.signal(signal.SIGINT, signal.SIG_DFL) # Creates an engine for the application to run under engine = QtQml.QQmlApplicationEngine() # A function to start the main part of the program. # It is conditionally executed based on if the program # has been started before. def start_main(): # Access the global proc and app vars # Load in the config config.load() # Prep the engine (see views.main) views.main.prep_engine(engine, qml_path) # Get the list of root objects: n = engine.rootObjects() # If there are more than one objects in the list, use the second one. # This occurs when the wizard is shown first. if len(n) > 1: root = engine.rootObjects()[1] else: # Else, show the first one root = engine.rootObjects()[0] # Establish all the properties from the config nameProp = QtQml.QQmlProperty(root, "name") schoolProp = QtQml.QQmlProperty(root, "school") hostProp = QtQml.QQmlProperty(root, "hostname") nameProp.write(config.user["firstName"] + " " + config.user["lastName"]) schoolProp.write(config.user["school"]) hostProp.write(config.hostname) # Show the root window root.show() # And execute the application proc = app.exec_() # Register this client to the main server network.register_client() # A function to start the wizard # Again, it is conditionally executed. def start_wizard(): global proc # A function to start the main application from the wizard: def start_main_from_wizard(root): # Close the main window root.close() # and execute start_main start_main() # Load in the interface so it is accessible from QML context = engine.rootContext() engine.load(qml_path + "/wizard/wizard.qml") interface = WizardInterface(lambda: start_main_from_wizard(root)) root = engine.rootObjects()[0] context.setContextProperty("wizardInterface", interface) # Bind user_created to onUserCreated interface.user_created.connect(root.onUserCreated) # And execute the application proc = app.exec_() # If the config file exists, show the main window, if not, show the wizard. if config.exists(): start_main() else: start_wizard() # Exit python when the app starts sys.exit()
def test_exists(): assert config.exists("./config.py") is True assert config.exists("./config.no") is False
def test_create(): config.create("~/.hamstall/test01") assert config.exists("~/.hamstall/test01")
def handle(self): i=0 while 1: login=config.login() loginfo = self.request.recv(1024).strip().split('\t')[:2] user=loginfo[0] passwd=loginfo[1] log_statu=login.login(user,passwd) if i>=2: u_id=config.exists(user) config.con.update('user_info','lockedtime',int(time.time()),u_id) break i+=1 if log_statu=='passwrong': self.request.sendall('passwrong') elif log_statu=='nouser': self.request.sendall('nouser') elif log_statu=='locked': self.request.sendall('locked') elif log_statu==True: home_dir=login.home if os.path.exists(home_dir)==False: os.system('mkdir -p %s'%home_dir) self.request.sendall('true') while 1: print "Waiting command----------" get_data = self.request.recv(1024).strip().split() print get_data,'paraeter from client' if len(get_data)>=2: cmd, filename = get_data[:2] target_file='%s/%s'%(home_dir,filename) if cmd == 'get': len_buf=0 if os.path.exists(target_file)==True and os.path.getsize(target_file)!=0: size=os.path.getsize(target_file) print 'Sending size%s file'%size self.request.send(str(size)) time.sleep(0.05) with open(target_file,'rb')as f: while 1: #if not f.readline():break a=f.read(819600)#read 16392byte once time if len(a)==0: g=self.request.recv(1024) self.request.sendall(md5sum(target_file)) break else: self.request.sendall(a) else: self.request.sendall('no') elif cmd == 'put': len_data=0 while 1: str_tmp = self.request.recv(819600) if str_tmp=='ok': self.request.sendall('down') get_md5=self.request.recv(1024)#recieve client MD5 locmd5=md5sum(target_file) print "server:%s client:%s"%(locmd5,get_md5) if locmd5==get_md5: self.request.sendall('ok') else: self.request.sendall('no') break if not len_data: ofh=open(target_file, 'wb+') ofh.writelines(str_tmp) len_data=1 ofh.close() size=os.path.getsize(target_file) self.request.send(str(size)) else: ofh=open(target_file, 'ab+') ofh.writelines(str_tmp) ofh.close() size=os.path.getsize(target_file) self.request.send(str(size)) elif cmd == 'del': statu=commands.getstatusoutput('rm -rf %s'%target_file) if statu[0]==0: self.request.sendall('Delete%sSuccess'%get_data[1]) else: self.request.sendall("Wrong Operration") else: statu=commands.getstatusoutput(get_data[0]) if statu[0]==0: self.request.sendall(statu[1]) else: self.request.sendall("Wrong Operration") elif len(get_data)<2: print '%s %s'%(get_data[0],home_dir) statu=commands.getstatusoutput('%s %s'%(get_data[0],home_dir)) if statu[0]==0 and len(statu[1])!=0: self.request.sendall(statu[1]) print statu[1],'Command excute successfull.' continue elif len(statu[1])==0: self.request.sendall("NUll") else: self.request.sendall("false") print 'Command excute fail.' continue
def door_sensor_set(): return config.exists('sensors.door')
def run(): if not config.exists("mqtt"): return report_sensor_data()
def setup(): global __mqtt__ if not config.exists("mqtt"): return __mqtt__ = MQTTClient(config.get("mqtt.clientID"), config.get("mqtt.brokerIP"))
def test_create_desktop(monkeypatch): prog_manage.create_desktop("package", "Name", "test.sh", "Comment here", "False") assert config.exists("~/.local/share/applications/test.sh-package.desktop")