def OnQuit(self,event,dbfile):
if _plat.startswith('linux'):
dlg = wx.MessageDialog(self, 'Really quit?','', wx.OK | wx.CANCEL | wx.ICON_ERROR)
val = dlg.ShowModal()
dlg.Show()
if val == wx.ID_CANCEL:
dlg.Destroy()
elif val == wx.ID_OK:
OKQuit = self.DBQuit(dbfile)
if OKQuit == 42:
self.Close()
elif _plat.startswith('darwin'):
pass
elif _plat.startswith('win'):
OKQuit = self.DBQuit(dbfile)
if OKQuit == 42:
self.Close()
sys.exit()#windows
self.Refresh()
python类CANCEL的实例源码
def __init__(self, parent, message, caption, choices=[]):
wx.Dialog.__init__(self, parent, -1)
self.SetTitle(caption)
sizer = wx.BoxSizer(wx.VERTICAL)
self.message = wx.StaticText(self, -1, message)
self.clb = wx.CheckListBox(self, -1, choices=choices)
self.chbox = wx.CheckBox(self, -1, 'Select all')
self.btns = self.CreateSeparatedButtonSizer(wx.OK | wx.CANCEL)
self.Bind(wx.EVT_CHECKBOX, self.EvtChBox, self.chbox)
sizer.Add(self.message, 0, wx.ALL | wx.EXPAND, 5)
sizer.Add(self.clb, 1, wx.ALL | wx.EXPAND, 5)
sizer.Add(self.chbox, 0, wx.ALL | wx.EXPAND, 5)
sizer.Add(self.btns, 0, wx.ALL | wx.EXPAND, 5)
self.SetSizer(sizer)
# self.Fit()
def onsoftreboot(self, event):
fila = self.listadoVM
for i in range(len(fila)):
if logger != None: logger.info(fila[i])
# El 9 elemento es el UUID
if logger != None: logger.info (fila[8])
#Pedimos confirmacion del reset de la mv con ventana dialogo
dlg_reset = wx.MessageDialog(self,
"Estas a punto de reiniciar \n " + fila[1] + " ",
"Confirm Exit", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
result = dlg_reset.ShowModal()
dlg_reset.Destroy()
if result == wx.ID_OK:
vm = conexion.searchIndex.FindByUuid(None,fila[8], True)
if vm is not None:
if logger != None: logger.info ("The current powerState is: {0}".format(vm.runtime.powerState))
TASK = vm.RebootGuest()
#Este da error tasks.wait_for_tasks(conexion, [TASK])
if logger != None: logger.info("Soft reboot its done.")
def onsoftPowerOff(self, event):
fila = self.listadoVM
for i in range(len(fila)):
if logger != None: logger.info(fila[i])
# El 9 elemento es el UUID
if logger != None: logger.info (fila[8])
#Pedimos confirmacion del reset de la mv con ventana dialogo
dlg_reset = wx.MessageDialog(self,
"Estas a punto de Soft Apagar \n " + fila[1] + " ",
"Confirm Exit", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
result = dlg_reset.ShowModal()
dlg_reset.Destroy()
if result == wx.ID_OK:
vm = conexion.searchIndex.FindByUuid(None,fila[8], True)
if vm is not None:
if logger != None: logger.info ("The current powerState is: {0}".format(vm.runtime.powerState))
TASK = vm.ShutdownGuest()
#Este da error tasks.wait_for_tasks(conexion, [TASK])
if logger != None: logger.info("Soft poweroff its done.")
# Reiniciamos el ordenador seleccionado en el menu contextual
def onreboot(self, event):
fila = self.listadoVM
for i in range(len(fila)):
if logger != None: logger.info(fila[i])
# El 9 elemento es el UUID
if logger != None: logger.info (fila[8])
#Pedimos confirmacion del reset de la mv con ventana dialogo
dlg_reset = wx.MessageDialog(self,
"Estas a punto de reiniciar \n " + fila[1] + " ",
"Confirm Exit", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
result = dlg_reset.ShowModal()
dlg_reset.Destroy()
if result == wx.ID_OK:
vm = conexion.searchIndex.FindByUuid(None,fila[8], True)
if vm is not None:
if logger != None: logger.info ("The current powerState is: {0}".format(vm.runtime.powerState))
TASK = vm.ResetVM_Task()
tasks.wait_for_tasks(conexion, [TASK])
if logger != None: logger.info("reboot its done.")
def onpower_on(self, event):
fila = self.listadoVM
for i in range(len(fila)):
if logger != None: logger.info(fila[i])
# El 9 elemento es el UUID
if logger != None: logger.info (fila[8])
#Pedimos confirmacion del poweron de la mv con ventana dialogo
dlg_reset = wx.MessageDialog(self,
"Estas a punto de iniciar \n " + fila[1] + "\nAhora esta: " + fila[3],
"Confirm Exit", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
result = dlg_reset.ShowModal()
dlg_reset.Destroy()
if result == wx.ID_OK:
vm = conexion.searchIndex.FindByUuid(None,fila[8], True)
if vm is not None and not vm.runtime.powerState == 'poweredOn':
if logger != None: logger.info ("The current powerState is: {0}".format(vm.runtime.powerState))
TASK = vm.PowerOn()
tasks.wait_for_tasks(conexion, [TASK])
if logger != None: logger.info("Power ON its done.")
def onpowerOff(self, event):
fila = self.listadoVM
for i in range(len(fila)):
if logger != None: logger.info(fila[i])
# El 9 elemento es el UUID
if logger != None: logger.info (fila[8])
#Pedimos confirmacion del reset de la mv con ventana dialogo
dlg_reset = wx.MessageDialog(self,
"Estas a punto de Apagar \n " + fila[1] + " ",
"Confirm Exit", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
result = dlg_reset.ShowModal()
dlg_reset.Destroy()
if result == wx.ID_OK:
vm = conexion.searchIndex.FindByUuid(None,fila[8], True)
if vm is not None and not vm.runtime.powerState == 'poweredOff':
if logger != None: logger.info ("The current powerState is: {0}".format(vm.runtime.powerState))
TASK = vm.PowerOff()
tasks.wait_for_tasks(conexion, [TASK])
if logger != None: logger.info("Power OFF its done.")
def update_check(parent):
"""Check for updates using the GitHub API
Args:
parent (wx.Window): The parent window (for the message dialog)
Returns:
None
"""
r = requests.get('https://api.github.com/repos/10se1ucgo/pyjam/releases/latest')
if not r.ok:
return
new = r.json()['tag_name']
try:
if StrictVersion(__version__) < StrictVersion(new.lstrip('v')):
info = wx.MessageDialog(parent, message="pyjam {v} is now available!\nGo to download page?".format(v=new),
caption="pyjam Update", style=wx.OK | wx.CANCEL | wx.ICON_INFORMATION)
if info.ShowModal() == wx.ID_OK:
webbrowser.open_new_tab(r.json()['html_url'])
info.Destroy()
except ValueError:
pass
def close(self, event):
if not self._world:
event.Skip()
return
modified = False
for level in self._world.levels:
modified = modified | level.modified
if modified:
result = wx.MessageBox('Do you want to save your changes?', 'Unsaved changes', wx.YES_NO | wx.CANCEL | wx.ICON_EXCLAMATION)
if result == wx.YES:
self._world.save()
elif result == wx.CANCEL:
return
event.Skip()
def __init__(self, parent, enable_required=True):
wx.Dialog.__init__(self, parent, title=_('Project properties'),
style=wx.DEFAULT_DIALOG_STYLE)
main_sizer = wx.FlexGridSizer(cols=1, hgap=0, rows=2, vgap=10)
main_sizer.AddGrowableCol(0)
main_sizer.AddGrowableRow(0)
self.ProjectProperties = ProjectPropertiesPanel(
self,
enable_required=enable_required)
main_sizer.AddWindow(self.ProjectProperties, flag=wx.GROW)
self.ButtonSizer = self.CreateButtonSizer(wx.OK | wx.CANCEL | wx.CENTRE)
self.Bind(wx.EVT_BUTTON, self.OnOK,
self.ButtonSizer.GetAffirmativeButton())
main_sizer.AddSizer(self.ButtonSizer, border=20,
flag=wx.ALIGN_RIGHT | wx.BOTTOM | wx.LEFT | wx.RIGHT)
self.SetSizer(main_sizer)
self.ProjectProperties.Fit()
self.Fit()
def CheckSaveBeforeClosing(self, title=_("Close Project")):
"""Function displaying an question dialog if project is not saved"
:returns: False if closing cancelled.
"""
if not self.Controler.ProjectIsSaved():
dialog = wx.MessageDialog(self, _("There are changes, do you want to save?"), title, wx.YES_NO | wx.CANCEL | wx.ICON_QUESTION)
answer = dialog.ShowModal()
dialog.Destroy()
if answer == wx.ID_YES:
self.SaveProject()
elif answer == wx.ID_CANCEL:
return False
for idx in xrange(self.TabsOpened.GetPageCount()):
window = self.TabsOpened.GetPage(idx)
if not window.CheckSaveBeforeClosing():
return False
return True
# -------------------------------------------------------------------------------
# File Menu Functions
# -------------------------------------------------------------------------------
def AddInitialStep(self, pos):
dialog = SFCStepNameDialog(self.ParentWindow, _("Please enter step name"), _("Add a new initial step"), "", wx.OK | wx.CANCEL)
dialog.SetPouNames(self.Controler.GetProjectPouNames(self.Debug))
dialog.SetVariables(self.Controler.GetEditedElementInterfaceVars(self.TagName, debug=self.Debug))
dialog.SetStepNames([block.GetName() for block in self.Blocks if isinstance(block, SFC_Step)])
if dialog.ShowModal() == wx.ID_OK:
id = self.GetNewId()
name = dialog.GetValue()
step = SFC_Step(self, name, True, id)
min_width, min_height = step.GetMinSize()
step.SetPosition(pos.x, pos.y)
width, height = step.GetSize()
step.SetSize(max(min_width, width), max(min_height, height))
self.AddBlock(step)
self.Controler.AddEditedElementStep(self.TagName, id)
self.RefreshStepModel(step)
self.RefreshBuffer()
self.RefreshScrollBars()
self.Refresh(False)
dialog.Destroy()
def AddNewComment(self, bbox):
dialog = wx.TextEntryDialog(self.ParentWindow,
_("Edit comment"),
_("Please enter comment text"),
"", wx.OK | wx.CANCEL | wx.TE_MULTILINE)
dialog.SetClientSize(wx.Size(400, 200))
if dialog.ShowModal() == wx.ID_OK:
value = dialog.GetValue()
id = self.GetNewId()
comment = Comment(self, value, id)
comment.SetPosition(bbox.x, bbox.y)
min_width, min_height = comment.GetMinSize()
comment.SetSize(*self.GetScaledSize(max(min_width, bbox.width), max(min_height, bbox.height)))
self.AddComment(comment)
self.Controler.AddEditedElementComment(self.TagName, id)
self.RefreshCommentModel(comment)
self.RefreshBuffer()
self.RefreshScrollBars()
self.RefreshVisibleElements()
comment.Refresh()
dialog.Destroy()
def AddNewJump(self, bbox, wire=None):
choices = []
for block in self.Blocks.itervalues():
if isinstance(block, SFC_Step):
choices.append(block.GetName())
dialog = wx.SingleChoiceDialog(self.ParentWindow,
_("Add a new jump"),
_("Please choose a target"),
choices,
wx.DEFAULT_DIALOG_STYLE | wx.OK | wx.CANCEL)
if dialog.ShowModal() == wx.ID_OK:
id = self.GetNewId()
jump = SFC_Jump(self, dialog.GetStringSelection(), id)
self.Controler.AddEditedElementJump(self.TagName, id)
self.AddNewElement(jump, bbox, wire)
dialog.Destroy()
def EditCommentContent(self, comment):
dialog = wx.TextEntryDialog(self.ParentWindow,
_("Edit comment"),
_("Please enter comment text"),
comment.GetContent(),
wx.OK | wx.CANCEL | wx.TE_MULTILINE)
width, height = comment.GetSize()
dialogSize = wx.Size(max(width + 30, 400), max(height + 60, 200))
dialog.SetClientSize(dialogSize)
if dialog.ShowModal() == wx.ID_OK:
value = dialog.GetValue()
rect = comment.GetRedrawRect(1, 1)
comment.SetContent(value)
comment.SetSize(*self.GetScaledSize(*comment.GetSize()))
rect = rect.Union(comment.GetRedrawRect())
self.RefreshCommentModel(comment)
self.RefreshBuffer()
self.RefreshScrollBars()
self.RefreshVisibleElements()
comment.Refresh(rect)
dialog.Destroy()
# -------------------------------------------------------------------------------
# Model update functions
# -------------------------------------------------------------------------------
def OnAdd(self, evt):
dialog = wx.TextEntryDialog(self,
"Enter name:",
"Add", style = wx.OK | wx.CANCEL)
dialog.Centre(wx.BOTH)
if dialog.ShowModal() == wx.ID_OK:
name = dialog.GetValue()
if name not in ("CURRENT", ) and name not in self.all_hosts:
fpath = os.path.join(DataPath, name)
shutil.copy(os.path.join(DataPath, "default"), fpath)
call_editor(fpath)
self.all_hosts.append(name)
self.combo_box_1.AppendItems([name])
else:
msg_dialog = wx.MessageDialog(self,
"Failed to create \"%s\".\nFile already exists." % name,
'Failed to create "%s"' % name, wx.OK | wx.ICON_ERROR)
msg_dialog.Centre(wx.BOTH)
msg_dialog.ShowModal()
msg_dialog.Destroy()
dialog.Destroy()
def __init__(self, *args, **kwargs):
super(PropertyEntryDialog, self).__init__(*args, **kwargs)
fgs = wx.FlexGridSizer(2, 2, 5, 5)
name_label = wx.StaticText(self, label="Nome: ")
unit_label = wx.StaticText(self, label="Unidade: ")
self.name_ctrl = wx.TextCtrl(self)
self.unit_ctrl = wx.TextCtrl(self)
fgs.AddMany([(name_label), (self.name_ctrl, 1, wx.EXPAND),
(unit_label), (self.unit_ctrl, 1, wx.EXPAND)])
fgs.AddGrowableCol(1, 1)
sizer = wx.BoxSizer(wx.VERTICAL)
button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)
#if _iswxphoenix:
sizer.Add(fgs, proportion=1, flag=wx.EXPAND)
sizer.Add(button_sizer, proportion=0, flag=wx.EXPAND)
#else:
# sizer.AddSizer(fgs, proportion=1, flag=wx.EXPAND)
# sizer.AddSizer(button_sizer, proportion=0, flag=wx.EXPAND)
self.SetSizer(sizer)
def __init__(self, *args, **kwargs):
if 'on_ok_callback' in kwargs:
self.on_ok_callback = kwargs.pop('on_ok_callback')
else:
self.on_ok_callback = None
if 'on_cancel_callback' in kwargs:
self.on_cancel_callback = kwargs.pop('on_cancel_callback')
else:
self.on_cancel_callback = None
super(Dialog, self).__init__(*args, **kwargs)
self.header_panel = Panel(self)
button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)
self.Bind(wx.EVT_BUTTON, self.on_button)
vbox = wx.BoxSizer(wx.VERTICAL)
vbox.Add(self.header_panel, proportion=1, flag=wx.ALL | wx.EXPAND)
vbox.Add(button_sizer, flag=wx.ALIGN_RIGHT)
self.SetSizer(vbox)
self.SetSize((800, 600))
self.SetTitle(u"Editor de Cabeçalho LAS")
def __init__(self, *args, **kwargs):
super(PropertyEntryDialog, self).__init__(*args, **kwargs)
fgs = wx.FlexGridSizer(2, 2, 5, 5)
name_label = wx.StaticText(self, label="Nome: ")
unit_label = wx.StaticText(self, label="Unidade: ")
self.name_ctrl = wx.TextCtrl(self)
self.unit_ctrl = wx.TextCtrl(self)
fgs.AddMany([(name_label), (self.name_ctrl, 1, wx.EXPAND),
(unit_label), (self.unit_ctrl, 1, wx.EXPAND)])
fgs.AddGrowableCol(1, 1)
sizer = wx.BoxSizer(wx.VERTICAL)
button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)
sizer.Add(fgs, proportion=1, flag=wx.EXPAND)
sizer.Add(button_sizer, proportion=0, flag=wx.EXPAND)
self.SetSizer(sizer)
def __init__(self, *args, **kwargs):
if 'size' not in kwargs:
kwargs['size'] = (360, 240)
super(NewRockTableDialog, self).__init__(*args, **kwargs)
# ico = wx.Icon(r'./icons/plus32x32.ico', wx.BITMAP_TYPE_ICO)
# self.SetIcon(ico)
fgs = wx.BoxSizer(wx.HORIZONTAL)
main_label = wx.StaticText(self, label="Fill up the cell below to create a new rock table.")
name_label = wx.StaticText(self, label="Name Rock Table: ")
# unit_label = wx.StaticText(self, label="Unidade: ")
self.name_ctrl = wx.TextCtrl(self)
# self.unit_ctrl = wx.TextCtrl(self)
fgs.Add(name_label, 0, wx.EXPAND)
fgs.Add(self.name_ctrl, 1, wx.EXPAND)
# fgs.AddGrowableRow(0)
sizer = wx.BoxSizer(wx.VERTICAL)
button_sizer = self.CreateButtonSizer(wx.OK | wx.CANCEL)
sizer.Add(main_label, 1, wx.GROW | wx.EXPAND)
sizer.Add(fgs, 0, wx.EXPAND)
sizer.Add(button_sizer, 0, wx.EXPAND)
self.SetSizer(sizer)
self.name_ctrl.SetFocus()
def Run( self ):
fileName = GetBoard().GetFileName()
if len(fileName)==0:
wx.LogMessage("a board needs to be saved/loaded!")
else:
dirpath = os.path.abspath(os.path.expanduser(fileName))
path, fname = os.path.split(dirpath)
ext = os.path.splitext(os.path.basename(fileName))[1]
name = os.path.splitext(os.path.basename(fileName))[0]
LogMsg="reading from "+ dirpath
out_filename=path+os.sep+name+".dxf"
LogMsg+="writing to "+out_filename
content=[]
txtFile = open(fileName,"r")
content = txtFile.readlines()
content.append(" ")
txtFile.close()
#wx.MessageDialog(None, 'This is a message box. ONLY TEST!', 'Test', wx.OK | wx.ICON_INFORMATION).ShowModal()
#wx.MessageDialog(None, 'This is a message box. ONLY TEST!', content, wx.OK | wx.ICON_INFORMATION).ShowModal()
#found_selected=False
#board = pcbnew.GetBoard()
dlg=wx.MessageBox( 'Only SAVED board file will be exported to DXF file', 'Confirm', wx.OK | wx.CANCEL | wx.ICON_INFORMATION )
if dlg == wx.OK:
if os.path.isfile(out_filename):
dlg=wx.MessageBox( 'Overwrite DXF file?', 'Confirm', wx.YES_NO | wx.NO_DEFAULT | wx.ICON_QUESTION )
if dlg == wx.YES:
export_dxf(content, out_filename)
else:
export_dxf(content, out_filename)
def nsc_findNS(self, ident=None):
"""
Locating the Name Server by using given nsHost and nsPort
"""
locator = NameServerLocator(identification=ident)
try:
if self.nsHost:
self._log('connecting to Name Server (%s:%s)' % (self.nsHost,
self.nsPort))
self.NS = locator.getNS(self.nsHost, self.nsPort, trace=1, bcaddr=self.bcAddr)
else:
self._log('broadcasting to find Name Server')
self.NS = locator.getNS(None, None, trace = 1, bcaddr=self.bcAddr)
self.nsHost = self.NS.URI.address
self.nsPort = self.NS.URI.port
self.NS._setIdentification(ident)
self._log('Name Server found, URI = %s' % self.NS.URI)
self._setNSData()
except ConnectionDeniedError, e:
if str(e).find( Pyro.constants.deniedReasons[Pyro.constants.DENIED_SECURITY] ) != -1:
msg = 'Authentication required:'
dlg = wx.TextEntryDialog(self, msg, 'Authentication',
style=wx.OK|wx.CANCEL|wx.TE_PASSWORD)
dlg.CentreOnParent()
if dlg.ShowModal() == wx.ID_OK:
ident = dlg.GetValue()
self.nsc_findNS(ident)
else:
self.NS = None
self._log('Connection to Name Server denied!','error')
else:
self.NS = None
self._logError('Unable to connect to Name Server')
except:
self.NS = None
self._logError('Name Server not found!')
def __init__(self, parent=None, message='Message:',
caption='Message', style=wx.OK|wx.CANCEL,pos=wx.DefaultPosition):
wx.Dialog.__init__(self, parent, -1, caption, size=wx.DefaultSize,
style=wx.CAPTION, pos=pos)
self._build(message, style)
self.Fit()
def WorkSpace(self,e ):
'''
Load in a project.
'''
logging.exception(self.clargs)
dbfile = self.clargs['project']
if not os.path.isfile(dbfile):
dlg = wx.MessageDialog(self, 'Project not found. Browse for the file?',
'',wx.YES_NO | wx.YES_DEFAULT | wx.CANCEL | wx.ICON_QUESTION)
val = dlg.ShowModal()
if val == wx.ID_YES:
self.OpenFile(e,False)
elif val == wx.ID_CANCEL:
dlg.Destroy()
else:
self.OpenFile(False,dbfile)
self.bplay.SetBitmapLabel(self.bplayicon)
self.panel2.Refresh()
#update timeline view
self.Layout()
self.panel3.SetFocus()
def OnSearch(self, e):
search_dlg = wx.TextEntryDialog(
self, "Search for", "", "", style=wx.OK | wx.CANCEL)
if (search_dlg.ShowModal() == wx.ID_OK):
keyword = search_dlg.GetValue()
self.data_view = [
x for x in self.data_view if keyword in x["Payload"]]
self.SetupGrid()
search_dlg.Destroy()
def reboot_pigrow_click(self, e):
dbox = wx.MessageDialog(self, "Are you sure you want to reboot the pigrow?", "reboot pigrow?", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
answer = dbox.ShowModal()
dbox.Destroy()
if (answer == wx.ID_OK):
out, error = MainApp.localfiles_ctrl_pannel.run_on_pi("sudo reboot now")
MainApp.pi_link_pnl.link_with_pi_btn_click("e")
print out, error
def update_setting_click(self, e):
#create updated settings file
#
#creating GPIO config block
item_count = config_info_pnl.gpio_table.GetItemCount()
# add dht22 sesnsor if present;
if "dht22sensor" in self.gpio_dict:
gpio_config_block = "\ngpio_dht22sensor=" + self.gpio_dict["dht22sensor"]
else:
gpio_config_block = ""
# list all devices with gpio and wiring directions
for count in range(0, item_count):
device = config_info_pnl.gpio_table.GetItem(count, 0).GetText()
gpio = config_info_pnl.gpio_table.GetItem(count, 1).GetText()
wiring = config_info_pnl.gpio_table.GetItem(count, 2).GetText()
gpio_config_block += "\ngpio_" + device + "=" + gpio
gpio_config_block += "\ngpio_" + device + "_on=" + wiring
# list all non-gpio settings
other_settings = ""
for key, value in self.config_dict.items():
other_settings += "\n" + key + "=" + value
config_text = other_settings[1:]
config_text += gpio_config_block
# show user and ask user if they relly want to update
dbox = wx.MessageDialog(self, config_text, "upload to pigrow?", wx.OK | wx.CANCEL | wx.ICON_QUESTION)
answer = dbox.ShowModal()
dbox.Destroy()
#if user said ok then upload file to pi
if (answer == wx.ID_OK):
#
# REPLACE THE FOLLOWING WITH A FUNCTION THAT ANYONE CAN CALL TO UPLOAD A FILE
#
sftp = ssh.open_sftp()
folder = "/home/" + str(pi_link_pnl.target_user) + "/Pigrow/config/"
f = sftp.open(folder + '/pigrow_config.txt', 'w')
f.write(config_text)
f.close()
def switch_device(self, device, currently):
switch_path = "/home/" + pi_link_pnl.target_user + "/Pigrow/scripts/switches/"
if currently == "ON":
switch_command = switch_path + device + "_off.py"
future_state = "OFF"
elif currently == "OFF":
switch_command = switch_path + device + "_on.py"
future_state = "ON"
else:
switch_command = "ERROR"
#if error show error message
if not switch_command == "ERROR":
#make dialogue box to ask if should switch the device
d = wx.MessageDialog(
self, "Are you sure you want to switch " + device + " to the " +
future_state + " poisition?\n\n\n " +
"Note: automated control scripts might " +
"\n switch this " + currently + " again " +
"\n if thier trigger conditions are met. "
, "Switch " + device + " " + future_state + "?"
, wx.OK | wx.CANCEL | wx.ICON_QUESTION)
answer = d.ShowModal()
d.Destroy()
#if user said ok then switch device
if (answer == wx.ID_OK):
out, error = MainApp.localfiles_ctrl_pannel.run_on_pi(switch_command)
print out # shows box with switch info from pigrow
if not error == "": print error
config_ctrl_pnl.currently_toedit = future_state #for if toggling within the dialog box
self.update_box_text()
config_ctrl_pnl.currently_new = future_state
config_ctrl_pnl.device_new = device
config_ctrl_pnl.gpio_new = config_ctrl_pnl.gpio_toedit
config_ctrl_pnl.wiring_new = config_ctrl_pnl.wiring_toedit
else:
d = wx.MessageDialog(self, "Error, current state not determined\n You must upload the settings to the pigrow before switching the device", "Error", wx.OK | wx.ICON_ERROR)
answer = d.ShowModal()
d.Destroy()
return "ERROR"
def MsgDlg(window, string, caption='OFAImage', style=wx.YES_NO | wx.CANCEL):
"""Common MessageDialog."""
dlg = wx.MessageDialog(window, string, caption, style)
result = dlg.ShowModal()
dlg.Destroy()
return result
def onInstall():
requiredVer = "Windows 10 Version 1703"
# Translators: Dialog text shown when attempting to install the add-on on an unsupported version of Windows (minSupportedVersion is the minimum version required for this add-on).
if sys.getwindowsversion().build < 15063 and gui.messageBox(_("You are using an older version of Windows. This add-on requires {minSupportedVersion} or later. Are you sure you wish to install this add-on anyway?").format(minSupportedVersion = requiredVer),
# Translators: title of the dialog shown when attempting to install the add-on on an old version of Windows.
_("Old Windows version"), wx.YES | wx.NO | wx.CANCEL | wx.CENTER | wx.ICON_QUESTION) == wx.NO:
raise RuntimeError("Old Windows version detected")