示例#1
0
    def window_activate(self,
                        window='Hotel Service Optimization System - HotSOS',
                        wait=0):
        """ Activate window before continuing

        Activate Window using autoit. Default search window is hotSOS,
        due to frequency of use througout application.

        Noteable Variables
        ------------------------------
        window - string
        Name of window to find, using pyautoit. Pyautoit allows for
        semi matching strings and wild cards.

        wait - int
        Time in seconds to wait after input command to allow for delay
        after entering information.


        Returns
        ------------------------------
        Success - Boolean
        Return if window was either found successfully or otherwise.
        """
        print(f'Locating window: {window}')
        try:
            autoit.win_activate(window)
            print('Found!')
            sleep(wait)
            return True
        # Bare accept because autoit won't tell me what the error actually is.
        except:
            print('Unable to locate')
            sleep(wait)
            return False
示例#2
0
 def grab_frame(self):
     autoit.win_activate("View #")
     autoit.send("^s")
     sleep(0.05)
     autoit.send("{ALT}")
     sleep(0.05)
     autoit.send("{ENTER}")
     sleep(0.05)
     autoit.send("{ENTER}")
     sleep(1)
     autoit.send("{TAB}")
     sleep(0.05)
     autoit.send("{ENTER}")
     sleep(0.5)
     for i in range(0, 10, 1):
         autoit.send("{TAB}")
         sleep(0.05)
     autoit.send(self._work_dir + self._filename)
     for i in range(0, 6, 1):
         autoit.send("{TAB}")
         sleep(0.05)
     autoit.send("{ENTER}")
     self._img = wx.Image(self._work_dir + self._filename,
                          wx.BITMAP_TYPE_ANY)
     self._img = self._img.ConvertToBitmap()
     self._display.SetBitmap(self._img)
     autoit.win_activate(self._gui_title)
示例#3
0
def make_active_window(process, win):  # Сделать окно активным
    if autoit.process_exists(process):
        autoit.win_activate(win)
        print("Сделано!")
        return 1
    print("Окно не найдено!")
    return 0
示例#4
0
    def test_pcLogin(self):
        fp = webdriver.FirefoxProfile(r"C:\Users\mhf\AppData\Roaming\Mozilla\Firefox\Profiles\cv6txwo2.default")
        driver = webdriver.Firefox(fp)
        # driver = webdriver.Firefox ()
        driver.get ("https://www.hongkunjinfu.com")
        WebDriverWait (driver, 10).until (EC.presence_of_element_located ((By.ID, 'login')))
        driver.find_element_by_id ('login').send_keys ('14510000051')
        driver.find_element_by_xpath("html/body/div[2]/div[2]/div/ul/li[1]/a").click()

        autoit.win_activate('鸿坤金服——社区金融超市 - Mozilla Firefox')
        print("1111")
        autoit.send('{LCTRL down}'+'{LSHIFT down}'+'{! down}')
        # autoit.send('{LCTRL down}' + '{LALT down}' + '{a down}')
        # driver.find_element_by_id('login').send_keys(Keys.CONTROL + Keys.SHIFT + '!')
        time.sleep(2)
        autoit.win_wait('截取的图片另存为...')
        print("2222")
        autoit.control_focus('截取的图片另存为...','1001')
        print("3333")
        autoit.win_wait("[Class:#32770]",10)
        t = datetime.now().strftime('%Y%m%d%H%M%S')
        name='金服首页'+t
        # autoit.control_set_text('截取的图片另存为...','Edit1','金服网页102')
        autoit.control_set_text('截取的图片另存为...','Edit1',name)
        autoit.control_click('截取的图片另存为...','Button2')
        driver.close()
 def get_value_from_dropdown_list(self, control_id):
     """ 
     Returns a list containing all values of the specified dropdown.
     The default dropdown value is retained.
     """
     dropdown_list = []
     autoit.win_activate('Power Express')
     autoit.control_focus('Power Express', control_id)
     original_value = autoit.control_get_text('Power Express', control_id)
     autoit.send('{BACKSPACE}')
     autoit.send('{HOME}')
     while 1:
         item_combo_value = autoit.control_get_text('Power Express',
                                                    control_id)
         dropdown_list.append(item_combo_value)
         autoit.send('{DOWN}')
         if autoit.control_get_text('Power Express',
                                    control_id) == item_combo_value:
             break
     autoit.send('{BACKSPACE}')
     autoit.send('{HOME}')
     for item in dropdown_list:
         if original_value == autoit.control_get_text(
                 'Power Express', control_id):
             break
         else:
             autoit.send('{DOWN}')
     return dropdown_list
 def select_value_from_dropdown_list(self, control_id, value_to_select):
     """ 
     Example:
     Select Value From Dropdown List | [NAME:ccboClass_1] | Class Code Sample
     """
     autoit.win_activate('Power Express')
     autoit.control_click('Power Express', control_id)
     autoit.send('{BACKSPACE}')
     autoit.send('{HOME}')
     while 1:
         item_combo_value = autoit.control_get_text('Power Express',
                                                    control_id)
         if item_combo_value == value_to_select:
             autoit.control_focus('Power Express', control_id)
             autoit.send('{ENTER}')
             autoit.send('{TAB}')
             break
         else:
             autoit.control_focus('Power Express', control_id)
             autoit.send('{DOWN}')
         if autoit.control_get_text('Power Express',
                                    control_id) == item_combo_value:
             BuiltIn().fail("Dropdown '" + value_to_select +
                            "' value is not found")
             break
示例#7
0
def command_thor_test(command):
    try:
        ai.win_activate('[title:Control a Device]')
    except ai.AutoItError:
        print('AutoItError happened, returned')
        return
    time.sleep(0.1)
    ai.control_focus('[title:Control a Device]','Edit8')
    time.sleep(0.1)
    ai.control_set_text('[title:Control a Device]','Edit8',command)
    time.sleep(1)
    ai.control_click('[title:Control a Device]','Button15')  #clear the command window
    time.sleep(0.5)
    ai.control_click('[title:Control a Device]','Button13')  #send the command work
    time.sleep(2)
    ai.win_activate('[title:NetLinx Studio]')
    time.sleep(1)
    count = 0
    while True:
        count+=1
        print('try '+str(count)+' time')
        out = get_comeback_message()
        if out!='':
            print('congratulations! the output is not empty')
            break
        elif count<=3:
            time.sleep(3)
        else:
            print('even tried 4 times, the output is still empty')
            break
    return out
#%% test the function
#haha=command_thor_test('get status')        
#print(haha)
示例#8
0
    def _cancel_all(self):
        ret_code = -1
        ret_value = tools.get_timestamp()
        error_msg = ''

        try:
            autoit.win_activate(self.wid_main)
            self.clean_dlg()
            autoit.control_click(self.wid_main, self.cid_cancel_refresh)
            autoit.control_click(self.wid_main, self.cid_cancel_refresh)
            ret_code = 1
            time.sleep(5)
            autoit.control_click(self.wid_main, self.cid_cancel_selectall)
            ret_code = 2
            time.sleep(0.5)
            autoit.control_click(self.wid_main, self.cid_cancel_do)
            ret_code = 3

            if autoit.win_wait(self.wid_prompt, timeout=5) == 1:
                #autoit.win_activate(self.wid_prompt)
                autoit.control_click(self.wid_prompt, self.cid_prompt_ok)
                ret_code = 4

                if autoit.win_wait(self.wid_prompt, timeout=20) == 1:
                    #autoit.win_activate(self.wid_prompt)
                    autoit.control_click(self.wid_prompt, self.cid_prompt_ok)
                    ret_code = 0
        except:
            error_msg = traceback.format_exc()

        return (ret_code, ret_value, error_msg, self.local_log_path)


#==================================================================
示例#9
0
def focus_bdo():
    hwnd, title = _get_bdo()
    _focus_window(hwnd)
    autoit.win_activate(title)
    autoit.mouse_move(962, 526, speed=20)

    return title
示例#10
0
 def clean_dlg(self):
     try:
         if autoit.win_exists(self.wid_prompt):
             autoit.win_activate(self.wid_prompt)
             autoit.control_click(self.wid_prompt, self.cid_prompt_ok)
     except autoit.AutoItError:
         pass
示例#11
0
    def test_pcLogin(self):
        fp = webdriver.FirefoxProfile(r"C:\Users\mhf\AppData\Roaming\Mozilla\Firefox\Profiles\cv6txwo2.default")
        driver = webdriver.Firefox(fp)
        # driver = webdriver.Firefox ()
        driver.get ("https://www.hongkunjinfu.com")
        WebDriverWait (driver, 10).until (EC.presence_of_element_located ((By.ID, 'login')))
        driver.find_element_by_id ('login').send_keys ('14510000051')
        #保存网页弹出框
        driver.find_element_by_id('login').send_keys(Keys.CONTROL+'s')
        time.sleep(2)
        # autoit.run("notepad.exe")
        # autoit.win_wait_active("[CLASS:Notepad]", 3)
        # autoit.control_send("[CLASS:Notepad]", "Edit1", "hello world{!}")
        # autoit.win_close("[CLASS:Notepad]")
        # autoit.control_click("[Class:#32770]", "Button2")
        # autoit.win_wait
        # autoit.win_wait_active("[CLASS:#32770]",3)
        autoit.win_activate('另存为')
        print("111111")
        autoit.control_focus('另存为','1001')
        print("22222222")
        autoit.win_wait("[Class:#32770]",10)

        autoit.control_set_text('另存为','Edit1','金服网页2')

        # autoit.control_send("[CLASS:#32770]", "Edit1", "hello world{!}")
        # autoit.control_click("[CLASS:#32770]", "Button2")
        autoit.control_click('另存为','Button2')
        driver.close()
示例#12
0
    def _entrust_0(self, direction, code, price, volume):
        ret_code = -1
        ret_value = tools.get_timestamp()
        error_msg = ''

        if direction == 'b':
            cid_code = self.cid_buy_code
            cid_price = self.cid_buy_price
            cid_volume = self.cid_buy_volume
            cid_able = self.cid_buy_able
            cid_entrust = self.cid_buy_entrust
            wait_flag = True
        elif direction == 's':
            cid_code = self.cid_sell_code
            cid_price = self.cid_sell_price
            cid_volume = self.cid_sell_volume
            cid_able = self.cid_sell_able
            cid_entrust = self.cid_sell_entrust
            wait_flag = False
        else:
            error_msg = 'unexpected direction'
            return (ret_code, ret_value, error_msg, self.local_log_path)

        ret_code = 1

        try:
            autoit.win_activate(self.wid_main)
            self.clean_dlg()
            autoit.control_set_text(self.wid_main, cid_code, code)
            if wait_flag:
                for count in range(30):
                    if autoit.control_get_text(self.wid_main, cid_able) != '':
                        ret_code = 2
                        break
                    else:
                        time.sleep(0.1)
                if ret_code != 2:
                    error_msg = 'code response timeout'
                    return (ret_code, ret_value, error_msg,
                            self.local_log_path)

            ret_code = 3

            autoit.control_set_text(self.wid_main, cid_price, price)
            autoit.control_set_text(self.wid_main, cid_volume, volume)
            #autoit.win_activate(self.wid_main)
            autoit.control_click(self.wid_main, cid_entrust)

            ret_code = 4

            if autoit.win_wait(self.wid_prompt, timeout=3) == 1:
                #autoit.win_activate(self.wid_prompt)
                autoit.control_click(self.wid_prompt, self.cid_prompt_ok)
                ret_code = 0

        except autoit.AutoItError:
            error_msg = traceback.format_exc()

        return (ret_code, ret_value, error_msg, self.local_log_path)
 def get_team_index_value(self, team):
     autoit.win_wait('[REGEXPTITLE:lection|Teamauswahl]')
     autoit.win_activate('[REGEXPTITLE:lection|Teamauswahl]')
     team_selection_list = self._create_power_express_app_instance().ListBox
     team_list = team_selection_list.ItemTexts()
     if team in team_list:
         return team_list.index(team)
     else:
         BuiltIn().fail("Team '" + team + "' is not found on team list")
示例#14
0
 def file_upload(window_name, file_name):
     autoit.win_wait(window_name, 30)
     if not autoit.win_exists(window_name):
         raise Exception("No File Upload Window is found")
     else:
         autoit.win_activate(window_name)
         autoit.control_focus(window_name, "[ID:1148]")
         autoit.control_set_text(window_name, "[ID:1148]", file_name)
         autoit.control_click(window_name, "[ID:1]")
示例#15
0
def click_ClearList():
    try:
        ai.win_activate('[title:ICSPMonitor - V7.2.115]')
    except ai.AutoItError:
        #print('AutoItError happened, returned')
        logger.prt.debug('AutoItError happened,could not detect ICSPMonitor Window, returned')
        return
    time.sleep(0.1)
    ai.control_click('[title:ICSPMonitor - V7.2.115]','Button4')
示例#16
0
 def activate_window(self, locator):
     """
     Activates a window identified by locator
     :param locator: user defined name from map files
     Ex: activate_window("locator_name")
     """
     locator = self.__get_locator_for_tool(locator)
     window_identifier = mapMgr.__getitem__(locator)["IDENTIFIERS"].strip(
         "'").split(",")[0]
     autoit.win_activate(window_identifier)
示例#17
0
def write_notepad(text):
    command('notepad.exe')
    try:
        autoit.win_wait('[CLASS:Notepad]', timeout=3)
        autoit.win_activate('[CLASS:Notepad]')
    except autoit.autoit.AutoItError as e:
        print(e)
    for i in text.split('*'):
        autoit.send(i)
        autoit.send('{enter}')
示例#18
0
 def open_xcap(self):
     xcap = "C:\\Program Files\\EPIX\\XCAP"
     xcap += "\\program\\xcapwxx.exe -Xmx128M -myjava"
     autoit.run(xcap, "C:\\Users\\Public\\Documents\\EPIX\\XCAP")
     autoit.win_wait_active("EPIX")
     autoit.send("{TAB}")
     sleep(0.05)
     autoit.send("{ENTER}")
     sleep(0.05)
     autoit.win_wait_active("View #")
     autoit.win_activate(self._gui_title)
示例#19
0
def log_in(user):
    os.system('taskkill /f /im Steam.exe')
    os.system('start "" "C:\Program Files (x86)\Steam\Steam.exe" -login {} {}'.format(
        batch_sanitized(user.get_username()),
        batch_sanitized(user.get_password())
    ))
    if user.get_shared_secret() is not None:
        autoit.win_wait("Steam Guard")
        autoit.win_activate("Steam Guard")
        autoit.win_wait_active("Steam Guard")
        autoit.send(generate_auth_code(user.get_shared_secret()))
        autoit.send('{ENTER}')
def test_new_download(browser):
    driver = browser
    download_name = "1Test name"

    # Количесто записей в таблице. Можно и без базы через gui парсить.
    with allure.step(f'count downloads'):
        db_items_default = len(connect("SELECT * FROM oc_download"))
    with allure.step(f'login auth'):
        AuthPage(driver).login(username='******', password='******')
    with allure.step(f'go to Downloads page'
                     ):  # TODO Вынести переход до нужного блока в Base.
        DashboardPage(driver).navigate_to(dashboard_menu='Catalog',
                                          submenu='Downloads')
    with allure.step(f'go to Add download'):
        DownloadsPage(driver).goto_new_download_page()
    with allure.step(f'input download name'):
        DownloadsPage(driver).name_input_fill(download_name)
        # ActionChains(driver).move_to_element(download_name_input).click().send_keys(download_file_name).perform()
    with allure.step(f"Download file with autoIt"):
        DownloadsPage(driver).upload_btn_click()

        # TODO: уйти от autoit, потому что в headless режиме не заработает.
        # Для добавления файла через JavaScript или базу
        # файл с совпадающим именем должен лежать в папке Storage веб-сервера. Либо добавлять через GUI

        time.sleep(1)
        autoit.win_activate("Открытие")
        autoit.control_focus("Открытие", "Edit1")
        autoit.control_set_text(
            "Открытие", "Edit1",
            "G:\\Projects\\SeleniumOpenCart\\page_objects\\admin\\catalog\\test.jpg"
        )
        time.sleep(1)
        autoit.control_click("Открытие", "Button1")
        time.sleep(1)

    with allure.step(f'accept and save download'):
        driver.switch_to.alert.accept()
        DownloadsPage(driver).save_btn_click()
    with allure.step(f'delete created download form database '):
        # Удаление созданной записи из базы
        db_items_new = len(connect("SELECT * FROM oc_download"))
        last_item_id = connect(
            "SELECT download_id FROM oc_download WHERE download_id=(SELECT max(download_id) FROM oc_download)"
        )
        parsed_id = re.findall("\\d+", str(last_item_id))
        row = ("DELETE FROM oc_download WHERE download_id=%s" % parsed_id[0])
        delete_row(row)
        row_desc = "DELETE FROM oc_download_description WHERE download_id=%s" % parsed_id[
            0]
        delete_row(row_desc)
    assert db_items_default + 1 == db_items_new
示例#21
0
 def login(window_name, username, password):
     print "Waiting for window with name: " + window_name
     autoit.win_wait(window_name, 30)
     if not autoit.win_exists(window_name):
         raise Exception("No Browser Login Window is found")
     else:
         print "Activating window"
         autoit.win_activate(window_name)
         sleep(1)
         print "Sending username & password"
         autoit.send(username)
         autoit.send("{tab}")
         autoit.send(password)
         autoit.send("{enter}")
示例#22
0
    def activate_window(self, *, timeout=15):
        # Retorno 0   --Tela encontrada
        # Retorno -1  --Timeout

        timer = Timer(timeout)
        while timer.not_expired:
            try:
                autoit.win_activate(self.title)
                return 0
            except Exception as e:
                #print(f"[Exception]--> {e}")
                pass
        if timer.expired:
            return -1
示例#23
0
 def close_xcap(self):
     autoit.win_activate("EPIX")
     autoit.win_close("EPIX")
     sleep(0.2)
     autoit.win_activate("EPIX")
     autoit.win_close("EPIX")
     sleep(0.2)
     autoit.win_activate("EPIX")
     autoit.win_close("EPIX")
     sleep(0.2)
     autoit.win_activate("EPIX")
     autoit.win_close("EPIX")
     autoit.win_activate(self._gui_title)
     sleep(5)
示例#24
0
def ns_refresh_system():
    # ai.win_activate("[CLASS:Afx:00D80000:8:00010003:00000000:014702D7]")
    #ai.win_activate('[CLASSNAMENN:SysTreeView322]')
    try:
        ai.win_activate('[title:NetLinx Studio]')
    except ai.AutoItError:
        print('AutoItError happened, returned')
        return
    #ai.control_focus('[title:NetLinx Studio]','SysTreeView322')

    ai.opt("MouseCoordMode", 2)
    ai.mouse_click("right", 20, 200)
    time.sleep(0.5)
    ai.mouse_click("left", 40, 130)
    print('refresh sucess')
示例#25
0
 def win_activate(cls, title, **kwargs):
     """
     call autoit.win_activate
     激活指定的窗口(设置焦点到该窗口,使其成为活动窗口).
     timeout 单位为秒.
     :return PID:窗口存在; 0:窗口不存在.
     """
     return autoit.win_activate(title, **kwargs)
def main2():
    try:
        global x, y
        print("Press enter to inspect")
        # time.sleep(5)
        start = time.time()
        Root = node(AutomationElement.RootElement)
        all_windows = AutomationElement.RootElement.FindAll(
            TreeScope.Children, Condition.TrueCondition)
        if all_windows.Count == 0:
            return
        print("Enter between 1-%s to select a window" % all_windows.Count)
        for i in range(len(all_windows)):
            print("%s. %s" % (i + 1, all_windows[i].Current.Name))
        dur = time.time() - start
        idx = input()
        start = time.time()
        try:
            idx = int(idx.strip())
        except:
            return Exception_Handler(sys.exc_info())
        window = all_windows[idx - 1]
        window_name = window.Current.Name
        Root.children.append(node(window))
        all_elements = window.FindAll(TreeScope.Children,
                                      Condition.TrueCondition)
        if all_elements.Count != 0:
            for each_child in all_elements:
                copy_tree(Root.children[0].children, each_child)
        print("time taken for copy = %s" % (time.time() - start + dur))
        autoit.win_activate(window_name)
        time.sleep(0.5)
        ImageName = "ss.png"
        image = ImageGrab_Mac_Win.grab()
        autoit.win_activate(screen_title)
        # image.save(ImageName, format="PNG")
        # image = Image.open(ImageName)
        showPIL(image)
        print("tkinter close")
        print("************ YOUR Exact Path *************")
        if x >= 0 and y >= 0:
            res = _child_search(Root)[:-2] + "\n"
            print(res)
    except:
        Exception_Handler(sys.exc_info())
 def select_profile(self, user_profile):
     autoit.win_wait('[REGEXPTITLE:rofil]')
     autoit.win_activate('[REGEXPTITLE:rofil]')
     select_profile_app = Application().Connect(path='PowerExpress.exe')
     select_profile_window = select_profile_app.window_(title_re=u'.*rofil')
     # select_profile_window = select_profile_app.top_window_()
     select_profile_window_list_box = select_profile_window.ListBox
     select_profile_window_list_box.Select(user_profile)
     select_profile_ok_button = select_profile_window.OK
     select_profile_ok_button.Click()
     BuiltIn().set_suite_variable('${user_profile}', user_profile)
     time.sleep(2)
     try:
         if autoit.control_command('Power Express', '[NAME:YesBtn]',
                                   'IsVisible'):
             autoit.control_click('Power Express', '[NAME:YesBtn]')
     except Exception:
         pass
def main():
    data = request.data.decode('UTF-8')

    json_data = json.loads(data) # get the json from the client

    # loop five times to check all the weapon slots to detect a change
    for i in range(0,5):
        try:
            weapon_clip = json_data['player']['weapons']['weapon_'+str(i)]['ammo_clip']
            previous_weapon_clip = json_data['previously']['player']['weapons']['weapon_'+str(i)]['ammo_clip']
            if weapon_clip < previous_weapon_clip: #if the weapon was fired
                print('Shot detected!')
                autoit.win_activate('Counter-Strike: Global Offensive') # prepare by forcing us to focus on CS:GO (so the keybinds trigger)
                autoit.send(HOTKEY_AUTOIT) # send hotkey
        except:
            pass

    return 'hello world'
 def upload_photo_by_autoit(self, path: str):
     '''Uploads photo'''
     import autoit as ai
     print("Uploading by autoit")
     #print(path)
     time.sleep(3)
     while True:
         try:
             ai.win_activate('Otwieranie')
             ai.control_send('Otwieranie', 'Edit1',
                             os.path.join(os.path.dirname(__file__), path))
             ai.control_click('Otwieranie', 'Button1')
             time.sleep(2)
             print('Powinno być wgrane')
             break
         except:
             print("By AutoIt: Nie wiem co się stało")
             os.system('Pause')
             break
def serverShutdown():
	ret = False
	if autoit.win_exists("C:\Windows\system32\cmd.exe"):	#Checks if the window Minecraft would be in is currently running
		print("The Minecraft server was found and will be shut down in 30 seconds.")
		#Note: The following command brings the Minecraft command prompt to the front.
		#It will be run after any pause just in case a user activates another screen some point
		#during that pause.
		autoit.win_activate("C:\Windows\system32\cmd.exe")
		autoit.send("say The server will be shutting down in 30 seconds.")
		autoit.send("{Enter}")
		for s in range(30,-1,-1):
			time.sleep(1)
			if(s == 15 or s == 10 or (s <= 5 and s >= 3)):
				autoit.win_activate("C:\Windows\system32\cmd.exe")
				autoit.send("say " + str(s) + " seconds till shutdown{!}")
				autoit.send("{Enter}")
			elif(s == 2):
				autoit.win_activate("C:\Windows\system32\cmd.exe")
				autoit.send("say " + str(s) + " seconds till shutdown{!}{!}{!}")
				autoit.send("{Enter}")
			elif(s == 1):
				autoit.win_activate("C:\Windows\system32\cmd.exe")
				autoit.send("say " + str(s) + " SECOND TILL SHUTDOWN{!}{!}{!}{!}{!}")
				autoit.send("{Enter}")
		print("Server is shutting down.")			
		autoit.win_activate("C:\Windows\system32\cmd.exe")
		autoit.send("say Server is shutting down now{!}")
		autoit.send("{Enter}")
		autoit.send("stop")
		autoit.send("{Enter}")
		#sleep to give the server time to shutdown
		time.sleep(5)
		#Log to console whether server is stopped
		if autoit.win_exists("C:\Windows\system32\cmd.exe") == False:
			print("The Minecraft server was successfully shutdown!")
			ret = True
		else:
			print("Error: The stop command was sent but the server is still found!")
			ret = False
	else:	#Minecraft instance was not found
		print("The server was not found.")
		ret = True		#Return true because this function only needs to make sure the server is off
	return ret
示例#31
0
def run():
    window = bring_bdo_top(refresh_wins())
    print(window)
    some_var = autoit.win_active(window)
    print(some_var)
    some_var_2 = autoit.win_activate(window)
    print(some_var_2)
    some_var = autoit.win_active(window)
    print(some_var)
    some_var = autoit.win_get_handle(window)
    time.sleep(2)
    autoit.control_send(window, "", "r")
示例#32
0
def main():

    user_dir = get_users_main_directory()
    check_lp_power_data_folder_exists(user_dir)
    check_database_file_exists(user_dir)
    trial = {}
    trial = prompt_setup(trial, user_dir)

    # stopgap for pre-class variables
    walk_speed = trial["Speed [MPH]"]
    walk_style = trial["Walk Style [Normal/LP]"]
    pack_number = trial["Pack Number [XXX]"]

    # MAKE FOLDERS FOR TRIAL BASED ON PREVIOUSLY-ENTERED INPUTS
    make_pack_folder(pack_number, walk_speed, walk_style, user_dir)

    print('.....')
    print("..........Launching.....")

    # SET UP BASIC AUTO-IT SETTINGS TO USE WINDOW-RELATIVE COORDINATES
    autoit.auto_it_set_option('MouseCoordMode', 0)
    autoit.auto_it_set_option('SendKeyDelay', 10)

    # OPEN PICOSCOPE USING OUR DEFAULT WINDOW LAYOUT WITH TWO PANELS AND POWER UP TOP
    default_pico = os.path.join(user_dir, "electrical_power.psdata")
    click_on_file(default_pico)

    # PREPARE TO RUN THE RECORD DATA MACRO
    autoit.win_wait('PicoScope 6 - [electrical_power.psdata]')
    autoit.win_activate('PicoScope 6 - [electrical_power.psdata]')
    time.sleep(0.5)
    autoit.send('{ALT}{TAB}{TAB}{TAB}{TAB}{ENTER}{END}{UP}{ENTER}')
    autoit.win_wait('Macro Recorder')
    autoit.control_click('Macro Recorder', "[Name:_buttonImport]")
    time.sleep(1)
    macro_text = os.path.abspath(os.path.join(user_dir, "record_20sec.psmacro"))
    autoit.clip_put(macro_text)
    autoit.win_wait("Open")
    autoit.send('^V', 0)
    autoit.send('{ENTER}')
    msgbox("Ready to go?")

    # RUN THE MACRO
    autoit.win_activate('Macro Recorder')
    autoit.win_wait('Macro Recorder')
    autoit.control_click('Macro Recorder', "[Name:_buttonExecute]")
    time.sleep(22)
    autoit.win_activate('Macro Recorder')
    autoit.send('{ESCAPE}')

    # BEGIN SAVING THE DATA
    i = datetime.now()
    save_text = os.path.abspath(os.path.join(user_dir, 'LP Power Data', "{}".format("LP-{0}".format(pack_number)), "{0}MPH-{1} Walk".format(walk_speed, walk_style),
                             "{0}MPH-{1} Walk_".format(walk_speed, walk_style) + i.strftime('%Y-%m-%d %Hh%Mm%Ss')+ ".psdata"))
    autoit.clip_put(save_text)

    # SAVE ALL CAPTURED WAVEFORMS IN PICO FORMAT
    autoit.win_activate('PicoScope 6')
    autoit.win_wait("PicoScope 6")
    autoit.send('{ALT}{f}{a}')
    time.sleep(.5)
    autoit.win_wait("Save As")
    autoit.control_send('Save As', "[Class:Edit;INSTANCE:1]", '^V', 0)
    autoit.send('{ENTER}')

    # BEGIN SAVE SEQUENCE FOR CSV FORMAT
    autoit.win_activate('PicoScope 6')
    autoit.win_wait("PicoScope 6")
    autoit.mouse_click("primary", 433, 67, 2, 1)
    # MUST CLICK ON SECTION OF WINDOW CONTAINING POWER TRACE OR ALL AVERAGES CALCULATED WILL BE MESSED UP
    autoit.win_activate('PicoScope 6')
    autoit.win_wait("PicoScope 6")
    autoit.mouse_click("primary", 230, 260, 1, 0)
    # autoit.control_click('PicoScope 6', "[CLASS:WindowsForms10.Window.8.app.0.1114f81_r13_ad1; INSTANCE:55]")
    autoit.send('{ALT}{f}{a}')
    time.sleep(.5)
    autoit.win_wait("Save As")
    autoit.control_send('Save As', "[Class:Edit;INSTANCE:1]", '^V', 0)

    # SAVE ALL CAPTURED 5SEC INTERVALS
    autoit.control_click('Save As', "[CLASS:ComboBox;INSTANCE:3]")
    autoit.send("{HOME}{DOWN}{DOWN}{ENTER}")
    # autoit.control_click("Save As", "[NAME:_currentBufferRadio]")
    time.sleep(0.5)
    autoit.send('{ENTER}')
    time.sleep(4.5)
    autoit.process_close('PicoScope.exe')
    # BOTH SAVE OPERATIONS NOW COMPLETE. THERE IS A CSV FOR EACH 5SEC INTERVAL IN A NEW SUBDIRECTORY OF THIS TRIAL.

    print("")
    print("Sit tight, I'm still doing some thinking....")

    # UPDATE ALL CSV FILES TO BE XLSX AND CALCULATE THEIR 5SEC AVERAGES
    run_avgs = recursively_repair_all_csv_files(save_text, user_dir, walk_speed)

    # ADD ALL INFORMATION COLLECTED TO THE EXPERIMENTS SPREADSHEET
    patch_experiments_database(trial, run_avgs, user_dir)
    print("")

    # WRITE THE METADATA SETTINGS TO A FILE FOR FUTURE RECORD
    with open('{}'.format(save_text.replace(".psdata", ".LPmeta")), 'w') as outfile:
        json.dump(trial, outfile, indent=4, separators=(',', ': '))
    print("")
    print("LP Metadata file successfully saved for the future with all info the state of the pack as you have just tested it.")

    print("")
    # print_average_power(dest_filename)
    print(".................................. Testing Complete.")
示例#33
0
 def launch_application(self):
     if not autoit.win_exists(WINDOW_START):
         autoit.run(self.config.get('exe', 'tmpgencvmw'))
         autoit.win_wait_active(WINDOW_START)
     autoit.win_activate(WINDOW_START)