Exemplo n.º 1
0
 def entity_to_modify_time(unit):
     return Menu.Entity(text=unit, action={
         "title": time_datetime2string,
         "shutter":  menu.entity_back_no_text,
         "top": Menu.Entity(text="Up", action=(time_modify_rtc, {"modify_amount":1, "modify_unit": unit})),
         "middle": Menu.Entity(text="Finish adjusting %s" % unit, action=menu.back),
         "bottom": Menu.Entity(text="Down", action=(time_modify_rtc, {"modify_amount":-1, "modify_unit": unit})),
     })
Exemplo n.º 2
0
def main():
  """
  Consists of the main functionality of the script.
  """
  # Set variables
  option_list = ['Angle', 'Frequency', 'Length', 'Temperature', 'Volume', 'Weight']
  m = Menu()

  # Run the menu    
  conversion_type = m.type_list(option_list) # Conversion type
  convert_from, convert_to = m.convert_list(conversion_type)
  num = m.get_value(convert_from, convert_to)

  # Run the calculations
  c = Calculations(num)
  data = c.read_csv('utils/formulas.csv')
  c.run_conversion(data, convert_from, convert_to)
Exemplo n.º 3
0
def main():
  """
  Consists of the main functionality of the script.
  """
  # Set variables
  clear = lambda: os.system('cls')
  m, e, f = Menu(), Extraction(), FileManage()

  # Create directory if doesn't exist
  data_folder = f.check_directory()
  html_filenames = f.get_html_filenames(data_folder)

  # Get the CSV file name
  clear()
  print("Input the name of the CSV file you want to create.")
  csv = m.get_filename()

  # Get the HTML file to extract data from
  clear()
  print("Select the index of the HTML file to extract data from.")
  html_opts = m.display_menu(html_filenames)
  sel_html = 'data/' + m.get_num_user_input(html_opts)

  # Select information to extract
  print("Select the index of the tag type you want to extract data from.")
  tag_list = ['Paragraphs', 'Headings', 'Links', 'Img urls', 'All text (no links)', 'All links', 'All content']
  tag_opts = m.display_menu(tag_list)
  sel_tag = m.get_num_user_input(tag_opts)

  # Get contents of HTML and adds to CSV file
  e.get_content(sel_html, sel_tag, csv)
Exemplo n.º 4
0
 def remove_source(self, source_name):
     match = self.find_source(self.prefs.get_sources(), source_name)
     if match != -1 and match != -2:
         confirm_statement = "Remove " + match['name'] + " from followed sources?"
         if(Menu.confirm_change(confirm_statement) and
                                self.prefs.remove_source(match) and
                                self.save_changes()):
             print("No longer following " + match['name'] + ".")
         else:
             print("Cancelled. Preferences not changed.")
Exemplo n.º 5
0
class HomeMenuController:
    """
    Controller which displays the menu with different choices
    """
    def __init__(self):
        self.menu = Menu()
        self.view = HomeMenuView(self.menu)

    def __call__(self):
        self.menu.add("auto", "create a tournament",
                      CreateTournamentController())
        self.menu.add("auto", "write a match result", MatchResultController())
        self.menu.add("auto", "change player rank", ChangeRankController())
        self.menu.add("auto", "get a report", ReportController())
        self.menu.add("q", "quit", QuitController())

        user_choice = self.view.get_user_choice()

        return user_choice.handler
Exemplo n.º 6
0
def main():
    """
  Consists of the main functionality of the script.
  """
    m, e = Menu(), Editor()
    clear = lambda: os.system('cls')

    # Set command list
    command_list = [
        'info', 'display', 'create', 'add', 'remove', 'update', 'exit'
    ]
    commands = [("info", m.main_menu), ("display", e.display_data),
                ("create", e.create_file), ("add", e.add_data),
                ("remove", e.remove_data), ("update", e.update_data),
                ("exit", m.exit_program)]

    # Display menu
    clear()
    m.main_menu([])

    # Get the users input
    while True:
        # Ask for user input, args as follows: 0, 1 = ['command', 'filename']
        user_input = input("=> ").lower().split(" ")
        clear()

        # Error handle if only one argument
        if len(user_input) < 2:
            filename = ''
        else:
            filename = f'{user_input[1]}.csv'

        # Loop through each command
        for command in commands:
            # Run function based on command
            if user_input[0] == command[0]:
                command[1](filename)

        # Error if invalid command
        if user_input[0] not in command_list:
            print("Invalid command. Type 'info' for a list of commands => ")
Exemplo n.º 7
0
def create_menu_playback(time_settings, settings, menu, touch, control, camera_slave, screen, auxiliary_controller, **_):
    def save_fb_as_startup():
        control.to_save_fb_as_startup = True

    return {
        "state": CameraState.PLAYBACK,
        "page": "PHOTO_VIEW",
        "title": (lambda: "{} [{}]".format(control.playback_img_name, control.playback_index)),
        "shutter": menu.entity_reset_no_text,
        "top" : Menu.Entity(text=None, action=control.decrease_playback_index),
        "middle": Menu.Entity(text=None, action={
            "title": "OPTIONS",
            "page": "MENU",
            "shutter": menu.entity_back_no_text,
            "top": menu.entity_scroll_up,
            "bottom": menu.entity_scroll_down,
            "middle": menu.entity_scroll_selection,
            "items": [
                Menu.Entity(text="Analysis", action={
                    "page": "ANALYSIS",
                    "title": (lambda: "{} [{}]".format(control.playback_img_name, control.playback_index)),
                    "shutter": menu.entity_back_no_text,
                    "top": menu.entity_back_no_text,
                    "middle": menu.entity_back_no_text,
                    "bottom": menu.entity_back_no_text,
                }),
                menu.entity_back_action,
                Menu.Entity(text="Delete", action=[control.delete_playback_img_name, menu.back]),
                Menu.Entity(text="As Startup", action=[save_fb_as_startup, menu.back]),
            ],
        }),
        "bottom" : Menu.Entity(text=None, action=control.increase_playback_index),
    }
Exemplo n.º 8
0
 def addSource(self, source_name):
     params = {'apiKey': self.prefs.get_api_key()}
     source_list = Raab_Requests.make_request("top_sources", params)
     if source_list is None: return
     match = self.find_source(source_list['sources'], source_name)
     if match != -1 and match != -2:
         confirm_statement = "Add " + match['name'] + " to followed sources?"
         if Menu.confirm_change(confirm_statement):
             self.prefs.add_source({'name': match['name'], 'id': match['id'], 'description': match['description']})
             if(self.save_changes()):
                 print("Now following " + match['name'] + ".")
         else:
             print("Cancelled. Preferences not changed.")
Exemplo n.º 9
0
def load_menu(components):

    menu_preview = create_menu_preview(**components)
    menu_playback = create_menu_playback(**components)

    menu = components["menu"]
    control = components["control"]
    thermal = components["thermal"]
    settings = components["settings"]

    def save_img(control, **_):
        print("Snapshot...")
        control.to_save_img = True

    def next_preview():
        control.next_preview()
        save_control_settings(settings=settings, control=control)

    menu.structure = {
        "state": CameraState.PREVIEW,
        "page": "ROOT",
        "title": "", # (lambda: "{}".format(control.last_img_number)),
        "shutter": Menu.Entity(text=None, action=(save_img, components) ),
        "top" : Menu.Entity(text=None, action=next_preview),
        "middle": Menu.Entity(text=None, action={
            "state": CameraState.PREVIEW,
            "page": "INFO",
            "title": (lambda: control.preview_info() + thermal.get_thermal_statistics()),
            "shutter": Menu.Entity(text=None, action=(save_img, components) ),
            "top" : Menu.Entity(text="Views", action=next_preview),
            "middle": Menu.Entity(text="Menu", action=menu_preview),
            "bottom" :  Menu.Entity(text="Hide / Playback", action=menu.back),
            "postview": Menu.Entity(text=None, action={"state": CameraState.POSTVIEW, "title": "SNAPSHOT"}),
        }),
        "bottom" : Menu.Entity(text=None, action=menu_playback),
        "postview": Menu.Entity(text=None, action={"state": CameraState.POSTVIEW, "title": "SNAPSHOT"}),
    }

    menu.entity_order = ["top", "middle", "bottom"]
Exemplo n.º 10
0
 def find_source(self, source_list, source_name):
     matches = []
     for source in source_list:
         if(source_name in source['name']):
             matches.append(source)
     if len(matches) > 0:
         match = matches[0]
         if len(matches) > 1:
             match = Menu.numeric_menuf(Menu, matches, self.format_source)
     else:
         match = -2
     if match == -1:
         print("Cancelled. Preferences not changed.")
     elif match == -2:
         print("No matching source found for \"" + source_name + "\"")
     return match
Exemplo n.º 11
0
def main():
    """
  Consists of the main functionality of the script.
  """
    # Create menu class
    m = Menu()

    # Display the main menu
    m.main_menu()

    # Run the program
    while (True):
        m.get_command()
Exemplo n.º 12
0
Arquivo: frame.py Projeto: ehoac/wfund
class WFundFrame(wx.Frame):
    def __init__(self, parent, pid):
        self.user = None
        self.title = "WFund - Give me Five"
        wx.Frame.__init__(self, parent, pid, self.title, size=(800, 600))
        ico = EmbedImg(ICON).GetIcon()
        self.SetIcon(ico)
        self.filename = ''
        self.wildcard = "WFund files (*.WFund) | *.WFund|All files (* .*) | *.*"
        self.panel_list = []
        self.SetBackgroundColour('White')

        self.initStatusBar()
        self.login()
        self.splash()
        self.initMenu()
        self.initToolBar()
        self.createPanel()

    def initStatusBar(self):
        self.statusbar = self.CreateStatusBar()
        self.statusbar.SetFieldsCount(3)
        self.statusbar.SetStatusWidths([-1, -1, -1])
        self.timer = wx.PyTimer(self.Notify)
        self.timer.Start(1000, wx.TIMER_CONTINUOUS)
        self.Notify()

    def menuData(self):
        return [
            (
                "操作",
                (("新增申请\tCtrl+N", "新增申请", self.OnApplyFund, 'N'),
                 ("", "", "", ''), ("关闭\tCtrl+Q", "关闭", self.OnCloseWindow,
                                    'Q')),
            ),
            (
                "查看",
                (
                    ("经费详情\tCtrl+D", "经费详情", self.OnDetail, 'D'),
                    # ("个人统计\tCtrl+P", "", self.OnPerStat, 'P'),
                    ("个人统计", (
                        ("未报销\tCtrl+P", "个人统计-未报销", self.OnPerUnPay, 'O',
                         wx.ACCEL_CTRL | wx.ACCEL_ALT),
                        ("已报销\tCtrl+H", "个人统计-已报销", self.OnPerHadPay, 'H',
                         wx.ACCEL_CTRL | wx.ACCEL_ALT),
                    )),
                    ("组内统计\tCtrl+G", "组内统计", self.OnClsStat, 'G'),
                    ("个人信息\tCtrl+Alt+P", "个人信息", self.OnUserInfo, 'P'),
                    ("生成表单\tCtrl+Alt+G", "生成表单", self.OnGenSheet, 'P'),
                )),
            ('管理', (("添加用户\tCtrl+Alt+A", "添加用户", self.OnAddUser, 'A',
                     wx.ACCEL_CTRL | wx.ACCEL_ALT),
                    ("登录其他用户\tCtrl+Alt+U", "登录其他用户", self.OnLogOther, 'U',
                     wx.ACCEL_CTRL | wx.ACCEL_ALT), ("申请开关", (
                         ("开\tCtrl+Alt+O", "申请开关-开", self.OnApplySign, 'O',
                          wx.ACCEL_CTRL | wx.ACCEL_ALT, wx.ITEM_RADIO),
                         ("关\tCtrl+Alt+C", "申请开关-关", self.OnApplySign, 'C',
                          wx.ACCEL_CTRL | wx.ACCEL_ALT, wx.ITEM_RADIO),
                     )), ("维护\tCtrl+Alt+W", "维护", self.OnMaintain, 'W',
                          wx.ACCEL_CTRL | wx.ACCEL_ALT))),
            ("帮助", (("关于\tCtrl+Shift+A", "关于", self.OnAbout, 'A',
                     wx.ACCEL_CTRL | wx.ACCEL_SHIFT),
                    ("说明\tCtrl+E", "说明", self.OnExplain, 'E', wx.ACCEL_CTRL)))
        ]

    def initMenu(self):
        self.menu = Menu(self, self.menuData())
        self.initApplySign()

    def initToolBar(self):
        toolbar = self.CreateToolBar()
        bmp_add = EmbedImg(ADD).GetBitmap()
        add_tool = toolbar.AddTool(-1, "新增申请", bmp_add, "新增申请")
        bmp_all = EmbedImg(ALL_INFO).GetBitmap()
        self.Bind(wx.EVT_TOOL, self.OnApplyFund, add_tool)
        all_tool = toolbar.AddTool(-1, "组内统计", bmp_all, "组内经费情况统计")
        self.Bind(wx.EVT_TOOL, self.OnClsStat, all_tool)
        toolbar.Realize()
        pass

    def initApplySign(self):
        signs = Config.find(where='code=? and sign=\'Y\'', args='applySign')
        if signs:
            val = signs[0].value
            if val == 'N':
                id = self.menu.FindMenuItem('管理', '关')
                apply_menu = self.menu.FindItemById(id)
                if apply_menu.IsCheckable():
                    apply_menu.Check(True)
            elif val == 'Y':
                id = self.menu.FindMenuItem('管理', '开')
                apply_menu = self.menu.FindItemById(id)
                if apply_menu.IsCheckable():
                    apply_menu.Check(True)

    def createPanel(self):
        self.hbox = wx.BoxSizer(wx.HORIZONTAL)
        self.SetSizer(self.hbox)
        # self.OnPerStat(None)
        self.OnDetail(None)

    def OnApplyFund(self, event):
        sign = Config.get_value(APPLY_SIGN)
        if sign:
            self.form = Form(self, -1, user=self.user)
            if self.form.ShowModal() == wx.ID_OK:
                self.flush()
        else:
            wx.MessageBox('暂时不能申请!', '提示')

    def OnPerUnPay(self, event):
        self.SetStatusText('当前页面:个人统计-未报销', 1)
        self.up_pay = None
        self.changePanel('view.fund.per_stat',
                         'PerStatPanel',
                         self.up_pay,
                         state=False)

    def OnPerHadPay(self, event):
        self.SetStatusText('当前页面:个人统计-已报销', 1)
        self.had_pay = None
        self.changePanel('view.fund.per_stat',
                         'PerStatPanel',
                         self.had_pay,
                         state=True)

    def OnClsStat(self, event):
        self.SetStatusText('当前页面:组内统计', 1)
        self.per_cls_panel = None
        self.changePanel('view.fund.cls_stat', 'ClsStatPanel',
                         self.per_cls_panel)

    def OnUserInfo(self, event):
        self.SetStatusText('当前页面:个人信息', 1)
        self.user_info = None
        self.changePanel('view.component.user', 'UserInfo', self.user_info)

    def OnDetail(self, event):
        self.SetStatusText('当前页面:详情', 1)
        self.fund_detail_panel = None
        self.changePanel('view.fund.detail', 'FundDetail',
                         self.fund_detail_panel)

    def OnGenSheet(self, event):
        reg = GenSheet(self, -1, self.user)
        if reg.ShowModal() == wx.ID_OK:
            print('success')

    def OnAddUser(self, event):
        if not util.isAdmin(self.user):
            wx.MessageBox('权限需要提升!', 'Error')
            return
        reg = Register(self, -1)
        if reg.ShowModal() == wx.ID_OK:
            print('register success')

    def OnLogOther(self, event):
        if not util.isAdmin(self.user):
            wx.MessageBox('权限需要提升!', 'Error')
            return
        log = Login(self, -1)
        if log.ShowModal() == wx.ID_OK:
            self.user = log.log_user
        self.SetStatusText("登录用户:" + self.user.name, 0)
        self.flush()

    def OnApplySign(self, event):
        if not util.isAdmin(self.user):
            wx.MessageBox('权限需要提升!', 'Error')
            self.initApplySign()
        else:
            signs = Config.find(where='code=? and sign=\'Y\'', args=APPLY_SIGN)
            itemId = event.GetId()
            label = self.menu.FindItemById(itemId).GetLabel()
            if signs:
                sign = signs[0]
                if sign.value == 'Y' and label == '开' or sign.value == 'N' and label == '关':
                    pass
                elif label == '开':
                    sign.value = 'Y'
                    sign.update()
                elif label == '关':
                    sign.value = 'N'
                    sign.update()

    def OnMaintain(self, event):
        if not util.isAdmin(self.user):
            wx.MessageBox('权限需要提升!', 'Error')
            return
        self.SetStatusText('当前页面:维护', 1)
        self.maintain_panel = None
        self.changePanel('view.maintain', 'MaintainPanel', self.maintain_panel)

    def login(self):
        log = Login(self, -1)
        if log.log_user:
            self.user = log.log_user
        else:
            if log.ShowModal() == wx.ID_OK:
                self.user = log.log_user
        self.SetStatusText("登录用户:" + self.user.name, 0)

    def OnAbout(self, event):
        dlg = WFundAbout(self)
        dlg.ShowModal()
        dlg.Destroy()

    def OnExplain(self, event):
        dlg = WFundExplain(self)
        dlg.ShowModal()
        dlg.Destroy()

    def Notify(self):
        locale.setlocale(locale.LC_ALL, 'en')
        locale.setlocale(locale.LC_CTYPE, 'chinese')
        t = time.localtime()
        st = time.strftime('%Y年%m月%d日 %H时%M分%S秒', t)
        self.SetStatusText('当前时间:' + st, 2)

    def changePanel(self, module, panel_class, panel=None, **kw):
        for item in self.panel_list:
            self.hbox.Hide(item)
        if panel not in self.panel_list:
            model = importlib.import_module(module)
            obj_class_name = getattr(model, panel_class)
            panel = obj_class_name(self, -1, self.user, **kw)
            self.panel_list.append(panel)
            self.hbox.Add(panel, 1, wx.EXPAND)
        self.hbox.Show(panel)
        self.hbox.Layout()

    def OnCloseWindow(self, event):
        self.timer.Stop()
        self.Destroy()

    def flush(self):
        for panel in self.panel_list:
            panel.refresh(self.user)

    def splash(self):
        bmp = EmbedImg(SPLASH_PIC).GetBitmap()
        adv.SplashScreen(bmp, adv.SPLASH_CENTER_ON_SCREEN | adv.SPLASH_TIMEOUT,
                         1000, None, -1)
        wx.Yield()
Exemplo n.º 13
0
def create_menu_preview(logger, time_settings, settings, menu, touch, control, thermal, camera_slave, screen, auxiliary_controller, **_):

    def get_time_calibration_factor():
        return time_settings.dict.get("calibration_factor", 1.0)

    def time_save():
        time_rtc2dictionary(time_settings.dict)
        time_settings.dict["reference_seconds"] = auxiliary_controller.time()
        time_settings.write()
        uos.sync()
        logger.info("Time saved")
        sync_time(logger, screen, time_settings, auxiliary_controller)

    def time_settings_write():
        time_settings.write()

    def entity_to_modify_time(unit):
        return Menu.Entity(text=unit, action={
            "title": time_datetime2string,
            "shutter":  menu.entity_back_no_text,
            "top": Menu.Entity(text="Up", action=(time_modify_rtc, {"modify_amount":1, "modify_unit": unit})),
            "middle": Menu.Entity(text="Finish adjusting %s" % unit, action=menu.back),
            "bottom": Menu.Entity(text="Down", action=(time_modify_rtc, {"modify_amount":-1, "modify_unit": unit})),
        })


    def get_forward_seconds():
        auxiliary_controller.sync()
        absolute_seconds = auxiliary_controller.time()
        reference_seconds = time_settings.dict.get("reference_seconds", 581.4265)
        return (absolute_seconds - reference_seconds) * get_time_calibration_factor()


    def change_time_calibration_factor(modify_amount = 0.0001):
        time_settings.dict["calibration_factor"] = get_time_calibration_factor() + modify_amount
        sync_time(logger, screen, time_settings, auxiliary_controller)

    menu_time_change = {
        "title": time_datetime2string,
        "shutter": menu.entity_back_no_text,
        "top": menu.entity_scroll_up,
        "bottom": menu.entity_scroll_down,
        "middle": menu.entity_scroll_selection,
        "items": [
            entity_to_modify_time("year"),
            entity_to_modify_time("month"),
            entity_to_modify_time("day"),
            entity_to_modify_time("hour"),
            entity_to_modify_time("minute"),
            entity_to_modify_time("second"),
            Menu.Entity(text="Save date/time change", action=[time_save, menu.back]),
            Menu.Entity(text="Calibration", action={
                "title": (lambda: "Date {}\nSeconds: {}".format(time_datetime2string(), get_forward_seconds())) ,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=(change_time_calibration_factor, {"modify_amount":0.000005})),
                "middle": Menu.Entity(text=(lambda: "Finish adjusting factor {}".format(get_time_calibration_factor())), action=[menu.back, time_settings_write]),
                "bottom": Menu.Entity(text="Down", action=(change_time_calibration_factor, {"modify_amount":-0.000005})),
            }),
        ]
    }

    def column_factor():
        if camera_slave.control.column_zoom_denominator == 0:
            return 999
        return camera_slave.control.column_zoom_numerator/camera_slave.control.column_zoom_denominator

    def row_factor():
        if camera_slave.control.row_zoom_denominator == 0:
            return 999
        return camera_slave.control.row_zoom_numerator/camera_slave.control.row_zoom_denominator

    column_offset_print = (lambda: "col offset {}".format(camera_slave.control.column_offset))
    row_offset_print = (lambda: "row offset {}".format(camera_slave.control.row_offset))

    column_factor_print = (lambda: "col factor {:.2f} {}/{}".format(column_factor(), camera_slave.control.column_zoom_numerator, camera_slave.control.column_zoom_denominator))
    row_factor_print = (lambda: "row factor {:.2f} {}/{}".format(row_factor(), camera_slave.control.row_zoom_numerator, camera_slave.control.row_zoom_denominator))

    view_factor_print = (lambda: "factor {:.2f} {:.2f}".format(row_factor(), column_factor()))

    def full_field_of_view_camera_slave():
        camera_slave.control.column_offset = 0
        camera_slave.control.row_offset = 0
        camera_slave.control.column_zoom_numerator = 20
        camera_slave.control.column_zoom_denominator = 20
        camera_slave.control.row_zoom_numerator = 20
        camera_slave.control.row_zoom_denominator = 20


    menu_camera_slave_calibration = {
        "title": "Visual camera FIELD OF VIEW",
        "page": "CAMERA_SLAVE_CALIBRATION",
        "shutter": menu.entity_back_no_text,
        "top": menu.entity_scroll_up,
        "bottom": menu.entity_scroll_down,
        "middle": menu.entity_scroll_selection,
        "items": [
            Menu.Entity(text=column_offset_print, action={
                "title": column_offset_print,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=camera_slave.increase_column_offset),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=camera_slave.decrease_column_offset),
            }),
            Menu.Entity(text=row_offset_print, action={
                "title": row_offset_print,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=camera_slave.increase_row_offset),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=camera_slave.decrease_row_offset),
            }),
            Menu.Entity(text=view_factor_print, action={
                "title": view_factor_print,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=[camera_slave.increase_column_factor, camera_slave.increase_row_factor]),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=[camera_slave.decrease_column_factor, camera_slave.decrease_row_factor]),
            }),
            Menu.Entity(text=column_factor_print, action={
                "title": column_factor_print,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=camera_slave.increase_column_factor),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=camera_slave.decrease_column_factor),
            }),
            Menu.Entity(text=row_factor_print, action={
                "title": row_offset_print,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=camera_slave.increase_row_factor),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=camera_slave.decrease_row_factor),
            }),
            Menu.Entity(text="OK", action=[
                (save_camera_slave_calibration_settings, {"settings": settings, "camera_slave": camera_slave}),
                menu.back,
            ]),
            Menu.Entity(text="FULL Field of View", action=full_field_of_view_camera_slave),
        ]
    }

    def touch_calibration_title():
        xpoints = len(touch.x_calibration_points)
        if not xpoints:
            return "Drag the finger on screen"
        else:
            return "{} points saved".format(xpoints)

    menu_touch_calibration = {
        "title": touch_calibration_title,
        "page": "TOUCH_CALIBRATION",
        "shutter":  menu.entity_back_no_text,
        "top": Menu.Entity(text="OK", action=[
            touch.calibrate,
            (save_touch_calibration_settings, {"settings": settings, "touch": touch}),
            menu.back
        ]),
        "middle": menu.entity_back_action,
        "items": [
            Menu.Entity(text=(lambda: "x_offset {}".format(touch.x_offset)), action=None),
            Menu.Entity(text=(lambda: "y_offset {}".format(touch.y_offset)), action=None),
            Menu.Entity(text=(lambda: "x_factor {}".format(touch.x_factor)), action=None),
            Menu.Entity(text=(lambda: "y_factor {}".format(touch.y_factor)), action=None),
        ]
    }

    def emissivity_text():
        return "Emissivity. {:.1f}".format(thermal.emissivity)

    def emissivity_down():
        thermal.emissivity -= 1.0

    def emissivity_up():
        thermal.emissivity += 1.0

    def toggle_static_range():
        thermal.static_range = not thermal.static_range
        thermal.thermal_configure()

    def string_static_range_minimum():
        return "Static min Temp: {:.1f}".format(thermal.static_minimum)

    def static_range_minimum_down():
        thermal.static_minimum -= 1.0
        thermal.send_thermal_static_range()

    def static_range_minimum_up():
        thermal.static_minimum += 1.0
        thermal.send_thermal_static_range()

    def string_static_range_maximum():
        return "Static max Temp: {:.1f}".format(thermal.static_maximum)

    def static_range_maximum_down():
        thermal.static_maximum -= 1.0
        thermal.send_thermal_static_range()

    def static_range_maximum_up():
        thermal.static_maximum += 1.0
        thermal.send_thermal_static_range()

    menu_thermal_options = {
        "title": "THERMAL OPTIONS",
        "shutter": menu.entity_back_no_text,
        "top": menu.entity_scroll_up,
        "bottom": menu.entity_scroll_down,
        "middle": menu.entity_scroll_selection,
        "items": [
            Menu.Entity(text=(lambda: "Flat Field Corr. {}".format(thermal.get_thermal_statistics())), action=thermal.thermal_fcc),
            Menu.Entity(text=emissivity_text, action=
            {
                "title": emissivity_text,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=emissivity_up),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=emissivity_down),
            }),
            Menu.Entity(text=(lambda: "Gain: {}".format(thermal.string_gain_mode())), action=thermal.next_gain_mode),
            Menu.Entity(text=(lambda: "Static range: {}".format(thermal.static_range)), action=toggle_static_range),
            Menu.Entity(text=string_static_range_maximum, action=
            {
                "title": string_static_range_maximum,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=static_range_maximum_up),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=static_range_maximum_down),
            }),
            Menu.Entity(text=string_static_range_minimum, action=
            {
                "title": string_static_range_minimum,
                "shutter":  menu.entity_back_no_text,
                "top": Menu.Entity(text="Up", action=static_range_minimum_up),
                "middle": menu.entity_back_action,
                "bottom": Menu.Entity(text="Down", action=static_range_minimum_down),
            }),
            Menu.Entity(text="Save", action=[
                (save_thermal_settings, {"settings": settings, "thermal":thermal}),
                menu.back,
            ]),
            Menu.Entity(text="Restart", action=[thermal.initialize]),
        ],
    }

    def restore_backup():
        settings.read(from_backup=True)
        settings.write()

        load_camera_slave_calibration_settings(settings=settings, camera_slave=camera_slave)
        load_touch_calibration_settings(settings=settings, touch=touch)
        load_control_settings(settings=settings, control=control)
        load_thermal_settings(settings=settings, thermal=thermal)

    def save_backup():
        save_camera_slave_calibration_settings(settings=settings, camera_slave=camera_slave)
        save_touch_calibration_settings(settings=settings, touch=touch)
        save_control_settings(settings=settings, control=control)

        settings.write()  # First make sure the current settings were saved
        settings.write(to_backup=True)

    menu_manage_settings = {
        "title": "MANAGE SETTINGS",
        "shutter": menu.entity_back_no_text,
        "top": menu.entity_scroll_up,
        "bottom": menu.entity_scroll_down,
        "middle": menu.entity_scroll_selection,
        "items": [
            Menu.Entity(text="Restore Backup", action=[restore_backup, menu.back]),
            Menu.Entity(text="Save Backup", action=[save_backup, menu.back]),
        ],
    }

    def toggle_pixle_pointer():
        control.always_pixel_pointer = not control.always_pixel_pointer
        save_control_settings(settings=settings, control=control)

    menu_preview = {
        "title": "MAIN MENU",
        "shutter": menu.entity_reset_no_text,
        "top": menu.entity_scroll_up,
        "bottom": menu.entity_scroll_down,
        "middle": menu.entity_scroll_selection,
        "items": [
            Menu.Entity(text="Thermal options", action=menu_thermal_options),
            Menu.Entity(text=(lambda: "Always pointer: {}".format(control.always_pixel_pointer)), action=toggle_pixle_pointer),
            Menu.Entity(text="Calibrate Field Of View", action=menu_camera_slave_calibration),
            Menu.Entity(text="Calibrate Touch", action=menu_touch_calibration),
            Menu.Entity(text="Manage settings", action=menu_manage_settings),
            Menu.Entity(text="Set Time", action=menu_time_change),
            Menu.Entity(text=(lambda: "1 FPS {}".format(control.fps)), action=control.fps_reset),
        ],
    }
    return menu_preview
Exemplo n.º 14
0
def main():
    global camera

    # Game initialization
    pygame.init()
    screen = pygame.display.set_mode(map(int, SCREEN.size))

    # Game's objects initialization
    camera = Camera()
    game   = Game()             # Game object. This will handle all the game world
                                # and its components
    menu   = Menu(screen, game)

    # Game's menu
    while menu.update():
        menu.render()
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            if event.type == KEYUP and event.key == K_ESCAPE:
                return
        pygame.display.flip()

    screen = pygame.display.set_mode(map(int, SCREEN.size), HWSURFACE|OPENGL|DOUBLEBUF)
    OGLManager.resize(*(map(int, SCREEN.size)))
    OGLManager.init(*(map(int, SCREEN.size)))

    pygame.display.set_caption("¡A ti te va a caer el Axl!")
    # Game!
    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                return
            if event.type == KEYUP and event.key == K_ESCAPE:
                return

        # Set FPS
        game.clock.tick(FPS)

        # Updates camera position, if asked.
        camera.handle_keys()
        # Draw the camera
        glMatrixMode(GL_MODELVIEW)
        glLoadIdentity()
        glClearColor(0.0,0.0,0.0,0.0)
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
        gluLookAt(*camera.to_args())
#        print camera

        # Draw the game
        try:
            game.render()         # Renders all game's elements
            game.behave()         # Follows behaviors in game.characters
            game.extra()          # Loads extra content in the game, if needed
        except GameOverException:
            import sys, time
            # wait a few seconds to show the result of the game.
            time.sleep(4)
            # Continue? maybe later
            sys.exit()
        # Flip and display view.
        pygame.display.flip()
Exemplo n.º 15
0
 def __init__(self):
     self.menu = Menu()
     self.view = HomeMenuView(self.menu)
Exemplo n.º 16
0
def main():
    global proxy_client, proxy_server
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    log_filename = 'logs/test_' + time.strftime("%Y%m%d",
                                                time.localtime()) + '.log'
    logging.basicConfig(filename=log_filename,
                        level=logging.INFO,
                        format=LOG_FORMAT)

    # 当前脚本所在目录路径
    curpath = os.path.dirname(os.path.realpath(__file__))

    # 全局config文件
    global_config = {}
    global_config_file_path = curpath + "/config.yaml"
    if os.path.isfile(global_config_file_path):
        gf = open(global_config_file_path, 'r', encoding='utf-8')
        global_config = yaml.safe_load(gf.read())

    # 是否传入配置文件
    if len(sys.argv) > 1:
        test_filename = sys.argv[1]
        config_file = "/config/" + test_filename + ".yaml"
    else:
        test_filename = 'default'
        config_file = "/config/" + test_filename + '.yaml'

    # yaml配置文件是否存在
    config_file_path = curpath + config_file
    if not os.path.isfile(config_file_path):
        print("配置文件不存在 " + config_file_path)
        return 1

    f = open(config_file_path, 'r', encoding='utf-8')
    config = yaml.safe_load(f.read())

    # 合并配置
    config = Util.recursionMergeTwoDict(global_config, config)

    # 是否开启代理
    is_open_proxy = config.get('BROWSER').get('proxy')
    if is_open_proxy:
        from browsermobproxy import Server
        bmp_path = config.get('BROWSER').get('bmp_path')
        logging.info('开启代理 ' + bmp_path)
        proxy_server = Server(bmp_path)
        proxy_server.start()
        proxy_client = proxy_server.create_proxy()

    browser_type = config.get('BROWSER').get('type')
    if browser_type == 'Firefox':
        options = FirefoxOptions()
        options.page_load_strategy = 'normal'
        if is_open_proxy:
            options.add_argument('--proxy-server={0}'.format(
                proxy_client.proxy))
        browser = webdriver.Firefox(options=options)
    elif browser_type == 'Chrome':
        options = ChromeOptions()
        options.page_load_strategy = 'normal'
        if is_open_proxy:
            options.add_argument('--proxy-server={0}'.format(
                proxy_client.proxy))
        browser = webdriver.Chrome(options=options)
    else:
        print('浏览器' + browser_type + ':类型不支持')
        return False

    logging.info('开始使用 ' + browser_type + ' 浏览器进行自动化测试')

    if is_open_proxy:
        proxy_client.new_har("req",
                             options={
                                 'captureHeaders': True,
                                 'captureContent': True
                             })

    browser.maximize_window()
    # 浏览器等待时间
    # browser.implicitly_wait(10)

    url = config.get('WEBSITE').get('url')
    browser.get(url)
    if is_open_proxy:
        Http.logHar(proxy_client.har)

    # 执行配置的TEST对象
    test = config.get('TEST')
    suite = unittest.TestSuite()
    for key in test:
        menus = Menu.getMenuConfig(config, key)
        try:
            if is_open_proxy:
                test_data = [browser, menus, proxy_client]
            else:
                test_data = [browser, menus]
            suite.addTest(
                ParametrizedTestCase.parametrize(Action,
                                                 'test_menu',
                                                 param=test_data))
        except AssertExcetion:
            print(key + " 断言失败")

    report_file_name = 'reports/' + test_filename + "_" + time.strftime(
        "%Y%m%d", time.localtime()) + '.html'
    fp = open(report_file_name, 'w', encoding='utf-8')
    runner = HTMLTestRunner.HTMLTestRunner(stream=fp,
                                           title='你的测试报告',
                                           description='使用配置文件:' +
                                           config_file_path + '生成的测试报告')
    runner.run(suite)
    fp.close()

    sleep(5)
    browser.quit()

    if is_open_proxy:
        proxy_client.close()
        proxy_server.stop()
Exemplo n.º 17
0
Arquivo: frame.py Projeto: ehoac/wfund
 def initMenu(self):
     self.menu = Menu(self, self.menuData())
     self.initApplySign()
Exemplo n.º 18
0
def main():
    global proxy_client, proxy_server
    LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
    log_filename = 'logs/test_' + time.strftime("%Y%m%d",
                                                time.localtime()) + '.log'
    logging.basicConfig(filename=log_filename,
                        level=logging.INFO,
                        format=LOG_FORMAT)

    # 当前脚本所在目录路径
    path = os.path.dirname(os.path.realpath(__file__))

    test_config = TestConfig(path)

    if len(sys.argv) > 1:
        report_name = sys.argv[1]
        if 'ls' == sys.argv[1]:
            files = getFileName(path + '/config/')
            print(Util.pretty(files))
            return
    else:
        report_name = 'default'

    # 获取测试用例数据
    config = test_config.get_test_case(sys.argv)

    # 是否开启代理
    is_open_proxy = config.get('BROWSER').get('proxy')
    if is_open_proxy:
        from browsermobproxy import Server
        bmp_path = config.get('BROWSER').get('bmp_path')
        logging.info('开启代理 ' + bmp_path)
        proxy_server = Server(bmp_path)
        proxy_server.start()
        proxy_client = proxy_server.create_proxy()

    # 浏览器类型
    browser_type = config.get('BROWSER').get('type')

    # 是否使用H5测试,并指定移动设备名称
    h5 = config.get('BROWSER').get('H5', False)
    device_name = config.get('BROWSER').get('device_name', 'iPhone 7')

    # 是否开启无头模式
    headless = config.get('BROWSER').get('headless', False)

    if browser_type == 'Firefox':
        options = FirefoxOptions()
        if headless:
            options.add_argument("-headless")
        options.page_load_strategy = 'normal'
        if h5:
            user_agent = "Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_0 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7A341 Safari/528.16"
            options.set_preference("general.useragent.override", user_agent)

        if is_open_proxy:
            options.add_argument('--proxy-server={0}'.format(
                proxy_client.proxy))
        browser = webdriver.Firefox(options=options)
    elif browser_type == 'Chrome':
        options = ChromeOptions()
        if headless:
            options.add_argument("--window-size=1920,1080")  # 设置浏览器分辨率(窗口大小)
            options.add_argument(
                "--start-maximized")  # 最大化运行(全屏窗口),不设置,获取元素可能会报错
            options.add_argument("--disable-extensions")
            options.add_argument('--no-sandbox')  # 取消沙盒模式,浏览器的安全性会降低
            # 禁用GPU加速,降低资源损耗,only for Windows but not a valid configuration for Linux OS
            options.add_argument('--disable-gpu')
            options.add_argument('--disable-dev-shm-usage')  # 解决资源有限的问题
            options.add_argument('--lang=en_US')
            options.add_argument("--headless")
        options.page_load_strategy = 'normal'
        if h5:
            mobileEmulation = {'deviceName': device_name}
            options.add_experimental_option('mobileEmulation', mobileEmulation)

        if is_open_proxy:
            options.add_argument('--proxy-server={0}'.format(
                proxy_client.proxy))
        browser = webdriver.Chrome(options=options)
    else:
        print('浏览器' + browser_type + ':类型不支持')
        return False

    logging.info('开始使用 ' + browser_type + ' 浏览器进行自动化测试')

    if is_open_proxy:
        proxy_client.new_har("req",
                             options={
                                 'captureHeaders': True,
                                 'captureContent': True
                             })

    if browser_type == 'Firefox' and h5:
        browser.set_window_size(360, 640)
    else:
        browser.maximize_window()
    # 浏览器等待时间
    # browser.implicitly_wait(10)

    url = config.get('WEBSITE').get('url')
    browser.get(url)
    if is_open_proxy:
        Http.logHar(proxy_client.har)

    # 执行配置的TEST对象
    test = config.get('TEST')
    suite = unittest.TestSuite()
    m = Menu()
    for key in test:
        menus = m.getMenuConfig(config, key)
        try:
            if is_open_proxy:
                test_data = [browser, menus, proxy_client]
            else:
                test_data = [browser, menus]
            suite.addTest(
                ParametrizedTestCase.parametrize(Action,
                                                 'test_menu',
                                                 param=test_data))
        except AssertExcetion:
            print(key + " 断言失败")

    # 是否生成报告,默认开启调试模式,不生成报告
    debug = config.get('DEBUG', True)
    if debug:
        runner = unittest.TextTestRunner()
        runner.run(suite)
    else:
        # 报告是否含有截图,DEBUG为False且IMAGE设置为True时生效
        image = config.get('IMAGE', False)
        report_path = path + '/reports/'
        report_file = report_name + "_" + time.strftime(
            "%Y%m%d", time.localtime()) + '.html'
        fp = open(report_path + report_file, 'wb')
        report_title = '你的测试报告'
        report_desc = '使用配置:' + report_name + '生成的测试报告'
        runner = HTMLTestRunner(stream=fp,
                                verbosity=2,
                                images=image,
                                title=report_title,
                                description=report_desc,
                                tester='pystest')
        runner.run(suite)
        fp.close()

    sleep(5)
    browser.quit()

    # send mail or not
    mail = config.get('MAIL')
    if not debug and mail and mail.get('SEND'):
        email_title = report_title
        email_content = report_desc
        smtp = Mail(config.get('MAIL'), report_path)
        smtp.connect()
        smtp.login()
        smtp.send(email_title, email_content, report_file)
        smtp.quit()

    if is_open_proxy:
        proxy_client.close()
        proxy_server.stop()
Exemplo n.º 19
0
def main():

    utime.sleep_ms(1000)
    ##############################################################################
    # CREATE COMPONENTS
    logger.info("uname", uos.uname())

    led_red = LED(1) # red led
    led_red.off()


    screen = Screen(
        spi=DynamicSPI(
            baudrate=54000000, pin_cs=Pin.board.P3, polarity=0, phase=0,
        ),
        alloc_screen_buff=True,
        width=320,
        height=240,
        pin_dc=Pin.board.P9,
        framebuffer_swap_endianness=True,
        fast_byteswap=False,
    )

    control = Control(logger=logger)
    thermal = Thermal(logger=logger)

    # SPI at 40000000 or start_delay=100 would lead to data corruption
    camera_slave = CameraSlave(
        spi=DynamicSPI(
            baudrate=30000000, pin_cs=Pin.board.P4, polarity=0, phase=0, start_delay=500,
        ),
        pin_data_ready=Pin.board.P5,
        width=screen.width,
        height=screen.height,
        alloc_rx_buff=True
    )

    touch = Touch(
        spi=DynamicSPI(
            baudrate=2000000, pin_cs=Pin.board.P7, polarity=0, phase=0, start_delay=10, byte_delay=10,
        )
    )

    auxiliary_controller = AuxiliaryController(
        spi=DynamicSPI(
            baudrate=2500000, pin_cs=Pin.board.P6, polarity=1, phase=0, start_delay=10, byte_delay=100,
        )
    )


    menu = Menu()
    settings = Settings("camera.json")
    time_settings = Settings("time.json")

    input_handler = InterruptHandler(
        pin_interrupt=Pin.board.P8, trigger=ExtInt.IRQ_FALLING
    )

    components = {
        "logger": logger,
        "auxiliary_controller": auxiliary_controller,
        "touch": touch,
        "control": control,
        "thermal": thermal,
        "menu": menu,
        "screen": screen,
        "settings": settings,
        "time_settings": time_settings,
        "input_handler": input_handler,
        "camera_slave": camera_slave,
    }

    #testing_bug3(**components)
    ###########################
    DynamicSPI._verbose = False
    auxiliary_controller._verbose = False

    ##############################################################################
    # INITIALIZE COMPONENTS

    logger.info("Loading menu...")
    load_menu(components)

    logger.info("Initializing screen...")
    screen.initialize()
    screen.set_window(0, 0, screen.width, screen.height)

    screen.screen_buff.draw_rectangle(0, 0, screen.width, screen.height, color=(30,30,30), fill=True)
    screen.write_to_screen(screen.screen_buff)
    utime.sleep_ms(100)
    display_intro = False
    try:
        image.Image(control.startup_img_name, copy_to_fb=screen.screen_buff)
        display_intro = True
    except Exception as e:
        logger.info("Could not display startup image {}".format(e))

    if display_intro:
        logger.info("Displaying intro")
        screen.screen_buff.draw_rectangle(0, 0, screen.width, 20, color=(30,30,30), fill=True)
        screen.screen_buff.draw_string(10,0, """Shutter Button is "Back" button""", color=(0,200,30), scale=2.0, mono_space=False)

        screen.screen_buff.draw_rectangle(0, round(screen.height*3/4), screen.width, round(screen.height*4/4), color=(30,30,30), fill=True)
        startup_text = "by JONATAN ASENSIO PALAO. v" + camera_version
        screen.screen_buff.draw_string(round(screen.width/11), round(screen.height*3.1/4), startup_text, color=(0,200,30), scale=2.0, mono_space=False)

        screen.screen_buff.draw_string(round(screen.width/11), round(screen.height*3.6/4), "LOADING... WAIT", color=(200,0,0), scale=2.0, mono_space=False)

        screen.write_to_screen(screen.screen_buff)

    logger.info("Initializing auxiliar processor...")
    if auxiliary_controller.initialize(timeout_ms=5000):
        logger.info("Initializtion complete. Last package number: ", auxiliary_controller.number_package_received())
    else:
        screen.screen_buff.draw_rectangle(0, 0, screen.width, screen.height, color=(30,30,30), fill=True)
        screen.screen_buff.draw_string(10,0, "Aux processor error", color=(255,0,0), scale=2.0, mono_space=False)
        screen.write_to_screen(screen.screen_buff)
        utime.sleep_ms(10000)
    control.battery_millivolts = auxiliary_controller.battery_millivolts
    absolute_seconds = auxiliary_controller.time()
    logger.info("Battery:", control.battery_millivolts, "mV", " Absolute seconds:", absolute_seconds)


    logger.info("Initializing time...")
    sync_time(logger, screen, time_settings, auxiliary_controller)

    logger.info("Loading settings...")

    load_camera_slave_calibration_settings(settings=settings, camera_slave=camera_slave)
    load_touch_calibration_settings(settings=settings, touch=touch)
    load_control_settings(settings=settings, control=control)
    load_thermal_settings(settings=settings, thermal=thermal)

    logger.info("Initializing thermal camera...")
    thermal.initialize()

    logger.info("Enabling input interrupts...")
    input_handler.enable(
        callback=input_interrupt, **components
    )


    logger.info("Running main loop...")
    loop(**components)