Edouard@641: #!/usr/bin/env python Edouard@641: # -*- coding: utf-8 -*- Edouard@641: andrej@1571: # This file is part of Beremiz, a Integrated Development Environment for andrej@1571: # programming IEC 61131-3 automates supporting plcopen standard and CanFestival. Edouard@641: # andrej@1571: # Copyright (C) 2007: Edouard TISSERANT and Laurent BESSARD andrej@1680: # Copyright (C) 2017: Andrey Skvortsov Edouard@641: # andrej@1571: # See COPYING file for copyrights details. Edouard@641: # andrej@1571: # This program is free software; you can redistribute it and/or andrej@1571: # modify it under the terms of the GNU General Public License andrej@1571: # as published by the Free Software Foundation; either version 2 andrej@1571: # of the License, or (at your option) any later version. Edouard@641: # andrej@1571: # This program is distributed in the hope that it will be useful, andrej@1571: # but WITHOUT ANY WARRANTY; without even the implied warranty of andrej@1571: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the andrej@1571: # GNU General Public License for more details. Edouard@641: # andrej@1571: # You should have received a copy of the GNU General Public License andrej@1571: # along with this program; if not, write to the Free Software andrej@1571: # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Edouard@641: andrej@1826: andrej@1881: from __future__ import absolute_import andrej@1826: from __future__ import print_function andrej@1732: import os andrej@1732: import sys andrej@1732: import getopt andrej@1783: import threading andrej@1834: from threading import Thread, currentThread, Semaphore andrej@1783: import traceback andrej@1783: import __builtin__ andrej@1783: import Pyro.core as pyro andrej@1783: Edouard@1984: from runtime import PLCObject, ServicePublisher, MainWorker andrej@1783: import util.paths as paths Edouard@641: andrej@1736: Edouard@641: def usage(): andrej@1826: print(""" Edouard@641: Usage of Beremiz PLC execution service :\n Edouard@644: %s {[-n servicename] [-i IP] [-p port] [-x enabletaskbar] [-a autostart]|-h|--help} working_dir Edouard@641: -n - zeroconf service name (default:disabled) Edouard@644: -i - IP address of interface to bind to (default:localhost) Edouard@641: -p - port number default:3000 Edouard@641: -h - print this help text and quit Edouard@641: -a - autostart PLC (0:disable 1:enable) (default:0) Edouard@641: -x - enable/disable wxTaskbarIcon (0:disable 1:enable) (default:1) Edouard@641: -t - enable/disable Twisted web interface (0:disable 1:enable) (default:1) Edouard@1934: -w - web server port or "off" to disable web server (default:8009) Edouard@1934: -c - WAMP client default config file (default:wampconf.json) Edouard@1934: -s - WAMP client secret, given as a file Edouard@1437: -e - python extension (absolute path .py) Edouard@1434: Edouard@641: working_dir - directory where are stored PLC files andrej@1826: """ % sys.argv[0]) Edouard@641: andrej@1749: Edouard@641: try: Edouard@1900: opts, argv = getopt.getopt(sys.argv[1:], "i:p:n:x:t:a:w:c:e:s:h") Edouard@641: except getopt.GetoptError, err: Edouard@641: # print help information and exit: andrej@1826: print(str(err)) # will print something like "option -a not recognized" Edouard@641: usage() Edouard@641: sys.exit(2) Edouard@641: Edouard@641: # default values Edouard@644: given_ip = None Edouard@641: port = 3000 Edouard@1439: webport = 8009 Edouard@1893: wampsecret = None Edouard@1893: wampconf = None Edouard@641: servicename = None Edouard@641: autostart = False Edouard@641: enablewx = True Edouard@641: havewx = False Edouard@641: enabletwisted = True Edouard@641: havetwisted = False Edouard@641: andrej@1742: extensions = [] Edouard@1437: Edouard@641: for o, a in opts: Edouard@641: if o == "-h": Edouard@641: usage() Edouard@641: sys.exit() Edouard@641: elif o == "-i": Edouard@641: if len(a.split(".")) == 4 or a == "localhost": Edouard@644: given_ip = a Edouard@644: else: Edouard@644: usage() Edouard@644: sys.exit() Edouard@641: elif o == "-p": Edouard@641: # port: port that the service runs on Edouard@641: port = int(a) Edouard@641: elif o == "-n": Edouard@641: servicename = a Edouard@641: elif o == "-x": Edouard@641: enablewx = int(a) Edouard@641: elif o == "-t": Edouard@641: enabletwisted = int(a) Edouard@641: elif o == "-a": Edouard@641: autostart = int(a) Edouard@1439: elif o == "-w": Edouard@1439: webport = None if a == "off" else int(a) Edouard@1439: elif o == "-c": Edouard@1439: wampconf = None if a == "off" else a Edouard@1893: elif o == "-s": Edouard@1893: wampsecret = None if a == "off" else a Edouard@1437: elif o == "-e": Edouard@1955: fnameanddirname = list(os.path.split(os.path.realpath(a))) Edouard@1955: fnameanddirname.reverse() Edouard@1955: extensions.append(fnameanddirname) Edouard@641: else: Edouard@641: usage() Edouard@641: sys.exit() Edouard@641: andrej@1783: andrej@1680: beremiz_dir = paths.AbsDir(__file__) Edouard@1434: Edouard@641: if len(argv) > 1: Edouard@641: usage() Edouard@641: sys.exit() Edouard@641: elif len(argv) == 1: Edouard@641: WorkingDir = argv[0] Edouard@641: os.chdir(WorkingDir) Edouard@641: elif len(argv) == 0: Edouard@641: WorkingDir = os.getcwd() andrej@1742: argv = [WorkingDir] Edouard@641: Edouard@641: if __name__ == '__main__': Edouard@641: __builtin__.__dict__['_'] = lambda x: x Edouard@641: andrej@1736: andrej@1595: def Bpath(*args): andrej@1740: return os.path.join(beremiz_dir, *args) andrej@1595: andrej@1736: andrej@1595: def SetupI18n(): andrej@1595: # Get folder containing translation files andrej@1740: localedir = os.path.join(beremiz_dir, "locale") andrej@1595: # Get the default language andrej@1595: langid = wx.LANGUAGE_DEFAULT andrej@1595: # Define translation domain (name of translation files) andrej@1595: domain = "Beremiz" andrej@1595: andrej@1595: # Define locale for wx andrej@1595: loc = __builtin__.__dict__.get('loc', None) andrej@1595: if loc is None: andrej@1595: loc = wx.Locale(langid) andrej@1595: __builtin__.__dict__['loc'] = loc andrej@1595: # Define location for searching translation files andrej@1595: loc.AddCatalogLookupPathPrefix(localedir) andrej@1595: # Define locale domain andrej@1595: loc.AddCatalog(domain) andrej@1595: andrej@1595: import locale andrej@1595: global default_locale andrej@1595: default_locale = locale.getdefaultlocale()[1] andrej@1595: andrej@1595: # sys.stdout.encoding = default_locale andrej@1595: # if Beremiz_service is started from Beremiz IDE andrej@1595: # sys.stdout.encoding is None (that means 'ascii' encoding'). andrej@1595: # And unicode string returned by wx.GetTranslation() are andrej@1595: # automatically converted to 'ascii' string. andrej@1595: def unicode_translation(message): andrej@1595: return wx.GetTranslation(message).encode(default_locale) andrej@1595: andrej@1595: if __name__ == '__main__': andrej@1595: __builtin__.__dict__['_'] = unicode_translation andrej@1595: # __builtin__.__dict__['_'] = wx.GetTranslation andrej@1595: andrej@1749: Edouard@1919: # Life is hard... have a candy. Edouard@1919: # pylint: disable=wrong-import-position,wrong-import-order Edouard@641: if enablewx: Edouard@641: try: Edouard@1451: import wx Edouard@641: havewx = True andrej@1780: except ImportError: andrej@1826: print("Wx unavailable !") Edouard@641: havewx = False Edouard@641: Edouard@641: if havewx: Edouard@1451: import re Edouard@1451: from types import * andrej@1590: andrej@1590: if wx.VERSION >= (3, 0, 0): andrej@1590: app = wx.App(redirect=False) andrej@1590: else: andrej@1590: app = wx.PySimpleApp(redirect=False) andrej@1590: app.SetTopWindow(wx.Frame(None, -1)) Edouard@1434: andrej@1595: default_locale = None andrej@1595: SetupI18n() Edouard@1434: Edouard@1067: defaulticon = wx.Image(Bpath("images", "brz.png")) Edouard@1067: starticon = wx.Image(Bpath("images", "icoplay24.png")) Edouard@1067: stopicon = wx.Image(Bpath("images", "icostop24.png")) Edouard@1434: Edouard@641: class ParamsEntryDialog(wx.TextEntryDialog): Edouard@641: if wx.VERSION < (2, 6, 0): andrej@1744: def Bind(self, event, function, id=None): Edouard@641: if id is not None: Edouard@641: event(self, id, function) Edouard@641: else: Edouard@641: event(self, function) Edouard@1434: andrej@1744: def __init__(self, parent, message, caption=_("Please enter text"), defaultValue="", andrej@1767: style=wx.OK | wx.CANCEL | wx.CENTRE, pos=wx.DefaultPosition): Edouard@641: wx.TextEntryDialog.__init__(self, parent, message, caption, defaultValue, style, pos) Edouard@1434: Edouard@641: self.Tests = [] Edouard@641: if wx.VERSION >= (2, 8, 0): Edouard@641: self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetAffirmativeId()) Edouard@641: elif wx.VERSION >= (2, 6, 0): Edouard@641: self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetAffirmativeButton().GetId()) Edouard@641: else: Edouard@641: self.Bind(wx.EVT_BUTTON, self.OnOK, id=self.GetSizer().GetItem(3).GetSizer().GetChildren()[0].GetSizer().GetChildren()[0].GetWindow().GetId()) Edouard@1434: Edouard@641: def OnOK(self, event): Edouard@641: value = self.GetValue() andrej@1739: texts = {"value": value} Edouard@641: for function, message in self.Tests: Edouard@641: if not function(value): andrej@1745: message = wx.MessageDialog(self, message % texts, _("Error"), wx.OK | wx.ICON_ERROR) Edouard@641: message.ShowModal() Edouard@641: message.Destroy() Edouard@641: return Edouard@641: self.EndModal(wx.ID_OK) Edouard@641: event.Skip() Edouard@1434: Edouard@641: def GetValue(self): Edouard@641: return self.GetSizer().GetItem(1).GetWindow().GetValue() Edouard@1434: Edouard@641: def SetTests(self, tests): Edouard@641: self.Tests = tests Edouard@1434: Edouard@641: class BeremizTaskBarIcon(wx.TaskBarIcon): Edouard@641: TBMENU_START = wx.NewId() Edouard@641: TBMENU_STOP = wx.NewId() Edouard@641: TBMENU_CHANGE_NAME = wx.NewId() Edouard@641: TBMENU_CHANGE_PORT = wx.NewId() Edouard@641: TBMENU_CHANGE_INTERFACE = wx.NewId() Edouard@641: TBMENU_LIVE_SHELL = wx.NewId() Edouard@641: TBMENU_WXINSPECTOR = wx.NewId() Edouard@641: TBMENU_CHANGE_WD = wx.NewId() Edouard@641: TBMENU_QUIT = wx.NewId() Edouard@1434: Edouard@835: def __init__(self, pyroserver, level): Edouard@641: wx.TaskBarIcon.__init__(self) Edouard@641: self.pyroserver = pyroserver Edouard@641: # Set the image Edouard@641: self.UpdateIcon(None) Edouard@835: self.level = level Edouard@1434: Edouard@641: # bind some events Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarStartPLC, id=self.TBMENU_START) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarStopPLC, id=self.TBMENU_STOP) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarChangeName, id=self.TBMENU_CHANGE_NAME) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarChangeInterface, id=self.TBMENU_CHANGE_INTERFACE) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarLiveShell, id=self.TBMENU_LIVE_SHELL) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarWXInspector, id=self.TBMENU_WXINSPECTOR) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarChangePort, id=self.TBMENU_CHANGE_PORT) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarChangeWorkingDir, id=self.TBMENU_CHANGE_WD) Edouard@641: self.Bind(wx.EVT_MENU, self.OnTaskBarQuit, id=self.TBMENU_QUIT) Edouard@1434: Edouard@641: def CreatePopupMenu(self): Edouard@641: """ Edouard@641: This method is called by the base class when it needs to popup Edouard@641: the menu for the default EVT_RIGHT_DOWN event. Just create Edouard@641: the menu how you want it and return it from this function, Edouard@641: the base class takes care of the rest. Edouard@641: """ Edouard@641: menu = wx.Menu() Edouard@641: menu.Append(self.TBMENU_START, _("Start PLC")) Edouard@641: menu.Append(self.TBMENU_STOP, _("Stop PLC")) andrej@1742: if self.level == 1: Edouard@835: menu.AppendSeparator() Edouard@835: menu.Append(self.TBMENU_CHANGE_NAME, _("Change Name")) Edouard@835: menu.Append(self.TBMENU_CHANGE_INTERFACE, _("Change IP of interface to bind")) Edouard@835: menu.Append(self.TBMENU_CHANGE_PORT, _("Change Port Number")) Edouard@835: menu.Append(self.TBMENU_CHANGE_WD, _("Change working directory")) Edouard@835: menu.AppendSeparator() Edouard@835: menu.Append(self.TBMENU_LIVE_SHELL, _("Launch a live Python shell")) Edouard@835: menu.Append(self.TBMENU_WXINSPECTOR, _("Launch WX GUI inspector")) Edouard@641: menu.AppendSeparator() Edouard@641: menu.Append(self.TBMENU_QUIT, _("Quit")) Edouard@641: return menu Edouard@1434: Edouard@641: def MakeIcon(self, img): Edouard@641: """ Edouard@641: The various platforms have different requirements for the Edouard@641: icon size... Edouard@641: """ Edouard@641: if "wxMSW" in wx.PlatformInfo: Edouard@641: img = img.Scale(16, 16) Edouard@641: elif "wxGTK" in wx.PlatformInfo: Edouard@641: img = img.Scale(22, 22) Edouard@641: # wxMac can be any size upto 128x128, so leave the source img alone.... andrej@1746: icon = wx.IconFromBitmap(img.ConvertToBitmap()) Edouard@641: return icon Edouard@1434: Edouard@641: def OnTaskBarStartPLC(self, evt): Edouard@1434: if self.pyroserver.plcobj is not None: andrej@1592: plcstatus = self.pyroserver.plcobj.GetPLCstatus()[0] andrej@1738: if plcstatus is "Stopped": andrej@1592: self.pyroserver.plcobj.StartPLC() andrej@1592: else: andrej@1826: print(_("PLC is empty or already started.")) Edouard@1434: Edouard@641: def OnTaskBarStopPLC(self, evt): Edouard@641: if self.pyroserver.plcobj is not None: andrej@1592: if self.pyroserver.plcobj.GetPLCstatus()[0] == "Started": andrej@1592: Thread(target=self.pyroserver.plcobj.StopPLC).start() andrej@1592: else: andrej@1826: print(_("PLC is not started.")) Edouard@1434: Edouard@641: def OnTaskBarChangeInterface(self, evt): andrej@1593: ip_addr = self.pyroserver.ip_addr andrej@1593: ip_addr = '' if ip_addr is None else ip_addr andrej@1730: dlg = ParamsEntryDialog(None, _("Enter the IP of the interface to bind"), defaultValue=ip_addr) Edouard@641: dlg.SetTests([(re.compile('\d{1,3}(?:\.\d{1,3}){3}$').match, _("IP is not valid!")), andrej@1767: (lambda x:len([x for x in x.split(".") if 0 <= int(x) <= 255]) == 4, andrej@1773: _("IP is not valid!"))]) Edouard@641: if dlg.ShowModal() == wx.ID_OK: Edouard@644: self.pyroserver.ip_addr = dlg.GetValue() Edouard@1887: self.pyroserver.Restart() Edouard@1434: Edouard@641: def OnTaskBarChangePort(self, evt): Edouard@641: dlg = ParamsEntryDialog(None, _("Enter a port number "), defaultValue=str(self.pyroserver.port)) andrej@1739: dlg.SetTests([(UnicodeType.isdigit, _("Port number must be an integer!")), (lambda port: 0 <= int(port) <= 65535, _("Port number must be 0 <= port <= 65535!"))]) Edouard@641: if dlg.ShowModal() == wx.ID_OK: Edouard@641: self.pyroserver.port = int(dlg.GetValue()) Edouard@1887: self.pyroserver.Restart() Edouard@1434: Edouard@641: def OnTaskBarChangeWorkingDir(self, evt): Edouard@641: dlg = wx.DirDialog(None, _("Choose a working directory "), self.pyroserver.workdir, wx.DD_NEW_DIR_BUTTON) Edouard@641: if dlg.ShowModal() == wx.ID_OK: Edouard@641: self.pyroserver.workdir = dlg.GetPath() Edouard@1887: self.pyroserver.Restart() Edouard@1434: Edouard@641: def OnTaskBarChangeName(self, evt): andrej@1594: servicename = self.pyroserver.servicename andrej@1594: servicename = '' if servicename is None else servicename andrej@1594: dlg = ParamsEntryDialog(None, _("Enter a name "), defaultValue=servicename) andrej@1739: dlg.SetTests([(lambda name: len(name) is not 0, _("Name must not be null!"))]) Edouard@641: if dlg.ShowModal() == wx.ID_OK: andrej@1594: self.pyroserver.servicename = dlg.GetValue() Edouard@641: self.pyroserver.Restart() Edouard@1434: Edouard@959: def _LiveShellLocals(self): Edouard@959: if self.pyroserver.plcobj is not None: andrej@1740: return {"locals": self.pyroserver.plcobj.python_runtime_vars} Edouard@959: else: Edouard@959: return {} Edouard@1434: Edouard@641: def OnTaskBarLiveShell(self, evt): Edouard@959: from wx import py Edouard@959: frame = py.crust.CrustFrame(**self._LiveShellLocals()) Edouard@959: frame.Show() Edouard@1434: Edouard@641: def OnTaskBarWXInspector(self, evt): Edouard@641: # Activate the widget inspection tool Edouard@641: from wx.lib.inspection import InspectionTool Edouard@641: if not InspectionTool().initialized: Edouard@959: InspectionTool().Init(**self._LiveShellLocals()) Edouard@959: Edouard@959: wnd = wx.GetApp() Edouard@641: InspectionTool().Show(wnd, True) Edouard@1434: Edouard@641: def OnTaskBarQuit(self, evt): Laurent@1121: if wx.Platform == '__WXMSW__': Laurent@1121: Thread(target=self.pyroserver.Quit).start() Edouard@641: self.RemoveIcon() Laurent@1121: wx.CallAfter(wx.GetApp().ExitMainLoop) Edouard@1434: Edouard@641: def UpdateIcon(self, plcstatus): andrej@1739: if plcstatus is "Started": Edouard@1067: currenticon = self.MakeIcon(starticon) Edouard@641: elif plcstatus is "Stopped": Edouard@1067: currenticon = self.MakeIcon(stopicon) Edouard@641: else: Edouard@1067: currenticon = self.MakeIcon(defaulticon) Edouard@641: self.SetIcon(currenticon, "Beremiz Service") Edouard@641: Edouard@641: Edouard@641: if not os.path.isdir(WorkingDir): Edouard@641: os.mkdir(WorkingDir) Edouard@641: andrej@1736: Edouard@867: def default_evaluator(tocall, *args, **kwargs): Edouard@867: try: andrej@1742: res = (tocall(*args, **kwargs), None) Edouard@1051: except Exception: andrej@1742: res = (None, sys.exc_info()) Edouard@867: return res Edouard@641: andrej@1736: andrej@1831: class Server(object): Edouard@1438: def __init__(self, servicename, ip_addr, port, Edouard@1984: workdir, argv, Edouard@1438: statuschange=None, evaluator=default_evaluator, Edouard@1458: pyruntimevars=None): Edouard@641: self.continueloop = True Edouard@641: self.daemon = None Edouard@641: self.servicename = servicename Edouard@644: self.ip_addr = ip_addr Edouard@641: self.port = port Edouard@641: self.workdir = workdir Edouard@641: self.argv = argv Edouard@641: self.plcobj = None Edouard@641: self.servicepublisher = None Edouard@641: self.statuschange = statuschange Edouard@641: self.evaluator = evaluator Edouard@1458: self.pyruntimevars = pyruntimevars Edouard@1434: edouard@1987: def _to_be_published(self): edouard@1987: return self.servicename is not None and \ edouard@1987: self.ip_addr is not None and \ edouard@1987: self.ip_addr != "localhost" and \ edouard@1987: self.ip_addr != "127.0.0.1" edouard@1987: edouard@1987: def PrintServerInfo(self): edouard@1987: print(_("Pyro port :"), self.port) edouard@1987: edouard@1987: # Beremiz IDE detects LOCAL:// runtime is ready by looking edouard@1987: # for self.workdir in the daemon's stdout. edouard@1987: print(_("Current working directory :"), self.workdir) edouard@1987: edouard@1987: if self._to_be_published(): edouard@1987: print(_("Publishing service on local network")) edouard@1987: edouard@1987: sys.stdout.flush() edouard@1987: edouard@1987: Edouard@1984: def PyroLoop(self): Edouard@641: while self.continueloop: Edouard@1887: pyro.initServer() Edouard@1887: self.daemon = pyro.Daemon(host=self.ip_addr, port=self.port) edouard@1987: Edouard@1901: # pyro never frees memory after connection close if no timeout set Edouard@1929: # taking too small timeout value may cause Edouard@1929: # unwanted diconnection when IDE is kept busy for long periods Edouard@1953: self.daemon.setTimeout(60) Edouard@1984: Edouard@1984: uri = self.daemon.connect(self.plcobj, "PLCObject") Edouard@1984: edouard@1987: if self._to_be_published(): Edouard@1984: self.servicepublisher = ServicePublisher.ServicePublisher() Edouard@1984: self.servicepublisher.RegisterService(self.servicename, self.ip_addr, self.port) Edouard@1984: Edouard@1887: self.daemon.requestLoop() Edouard@1887: self.daemon.sock.close() Edouard@1434: Edouard@641: def Restart(self): Edouard@1887: self._stop() Edouard@641: Edouard@641: def Quit(self): Edouard@641: self.continueloop = False Edouard@1045: if self.plcobj is not None: andrej@1596: self.plcobj.StopPLC() Edouard@1045: self.plcobj.UnLoadPLC() Edouard@1887: self._stop() Edouard@641: Edouard@1984: def RegisterPLCObject(self, plcobj): Edouard@1984: self.plcobj = plcobj Edouard@1434: Edouard@1887: def _stop(self): Edouard@1045: if self.plcobj is not None: Edouard@1045: self.plcobj.StopPLC() Edouard@641: if self.servicepublisher is not None: Edouard@641: self.servicepublisher.UnRegisterService() Edouard@641: self.servicepublisher = None Edouard@641: self.daemon.shutdown(True) Edouard@641: andrej@1749: Edouard@641: if enabletwisted: Edouard@641: import warnings Edouard@641: with warnings.catch_warnings(): Edouard@641: warnings.simplefilter("ignore") Edouard@641: try: Edouard@641: if havewx: Edouard@641: from twisted.internet import wxreactor Edouard@641: wxreactor.install() Edouard@1438: from twisted.internet import reactor Edouard@1434: Edouard@641: havetwisted = True andrej@1780: except ImportError: andrej@1826: print(_("Twisted unavailable.")) Edouard@641: havetwisted = False Edouard@641: Edouard@1438: pyruntimevars = {} Edouard@1438: statuschange = [] Edouard@1438: Edouard@641: if havetwisted: Edouard@641: if havewx: Edouard@641: reactor.registerWxApp(app) Edouard@1438: Edouard@641: if havewx: Edouard@641: wx_eval_lock = Semaphore(0) Edouard@867: main_thread = currentThread() Edouard@835: Edouard@1438: def statuschangeTskBar(status): andrej@1740: wx.CallAfter(taskbar_instance.UpdateIcon, status) Edouard@1434: Edouard@1438: statuschange.append(statuschangeTskBar) Edouard@1438: Edouard@867: def wx_evaluator(obj, *args, **kwargs): andrej@1740: tocall, args, kwargs = obj.call Edouard@867: obj.res = default_evaluator(tocall, *args, **kwargs) Edouard@867: wx_eval_lock.release() Edouard@1434: Edouard@867: def evaluator(tocall, *args, **kwargs): andrej@1828: if main_thread == currentThread(): Edouard@1434: # avoid dead lock if called from the wx mainloop Edouard@867: return default_evaluator(tocall, *args, **kwargs) Edouard@641: else: andrej@1742: o = type('', (object,), dict(call=(tocall, args, kwargs), res=None)) andrej@1740: wx.CallAfter(wx_evaluator, o) Edouard@641: wx_eval_lock.acquire() Edouard@867: return o.res Edouard@1434: Edouard@1438: pyroserver = Server(servicename, given_ip, port, Edouard@1984: WorkingDir, argv, Edouard@1438: statuschange, evaluator, pyruntimevars) Edouard@1438: Edouard@835: taskbar_instance = BeremizTaskBarIcon(pyroserver, enablewx) Edouard@641: else: Edouard@1438: pyroserver = Server(servicename, given_ip, port, Edouard@1984: WorkingDir, argv, Edouard@1438: statuschange, pyruntimevars=pyruntimevars) Edouard@1438: Edouard@641: Edouard@1916: # Exception hooks andrej@1736: Edouard@1906: Edouard@1906: def LogMessageAndException(msg, exp=None): Edouard@1906: if exp is None: Edouard@1906: exp = sys.exc_info() Edouard@1906: if pyroserver.plcobj is not None: Edouard@1906: pyroserver.plcobj.LogMessage(0, msg + '\n'.join(traceback.format_exception(*exp))) Edouard@1906: else: Edouard@1906: print(msg) Edouard@1906: traceback.print_exception(*exp) Edouard@1906: Edouard@1916: Edouard@1067: def LogException(*exp): Edouard@1919: LogMessageAndException("", exp) andrej@1749: Edouard@1955: Edouard@1067: sys.excepthook = LogException andrej@1736: andrej@1736: Edouard@1067: def installThreadExcepthook(): Edouard@1067: init_old = threading.Thread.__init__ andrej@1750: Edouard@1067: def init(self, *args, **kwargs): Edouard@1067: init_old(self, *args, **kwargs) Edouard@1067: run_old = self.run andrej@1750: Edouard@1067: def run_with_except_hook(*args, **kw): Edouard@1067: try: Edouard@1067: run_old(*args, **kw) Edouard@1067: except (KeyboardInterrupt, SystemExit): Edouard@1067: raise andrej@1780: except Exception: Edouard@1067: sys.excepthook(*sys.exc_info()) Edouard@1067: self.run = run_with_except_hook Edouard@1067: threading.Thread.__init__ = init andrej@1749: andrej@1749: Edouard@1067: installThreadExcepthook() Edouard@1067: Edouard@1446: if havetwisted: andrej@1739: if webport is not None: Edouard@1446: try: andrej@1872: import runtime.NevowServer as NS # pylint: disable=ungrouped-imports Edouard@1446: except Exception, e: andrej@1826: print(_("Nevow/Athena import failed :"), e) Edouard@1446: webport = None Edouard@1453: NS.WorkingDir = WorkingDir Edouard@1446: Edouard@1934: # Find pre-existing project WAMP config file Edouard@1934: _wampconf = os.path.join(WorkingDir, "wampconf.json") Edouard@1934: Edouard@1953: # If project's WAMP config file exits, override default (-c) Edouard@1934: if os.path.exists(_wampconf): Edouard@1934: wampconf = _wampconf Edouard@1894: andrej@1739: if wampconf is not None: Edouard@1446: try: andrej@1872: import runtime.WampClient as WC # pylint: disable=ungrouped-imports Edouard@1446: except Exception, e: andrej@1826: print(_("WAMP import failed :"), e) Edouard@1446: wampconf = None Edouard@1446: Edouard@1437: # Load extensions Edouard@1905: for extention_file, extension_folder in extensions: Edouard@1437: sys.path.append(extension_folder) Edouard@1905: execfile(os.path.join(extension_folder, extention_file), locals()) Edouard@1437: Edouard@1446: if havetwisted: andrej@1739: if webport is not None: Edouard@1446: try: Edouard@1446: website = NS.RegisterWebsite(webport) Edouard@1446: pyruntimevars["website"] = website Edouard@1446: statuschange.append(NS.website_statuslistener_factory(website)) Edouard@1906: except Exception: Edouard@1906: LogMessageAndException(_("Nevow Web service failed. ")) Edouard@1446: andrej@1739: if wampconf is not None: Edouard@1446: try: Edouard@1901: _wampconf = WC.LoadWampClientConf(wampconf) Edouard@1901: if _wampconf: Edouard@1901: if _wampconf["url"]: # TODO : test more ? Edouard@1894: WC.RegisterWampClient(wampconf, wampsecret) Edouard@1894: pyruntimevars["wampsession"] = WC.GetSession Edouard@1894: WC.SetServer(pyroserver) Edouard@1894: else: Edouard@1906: raise Exception(_("WAMP config is incomplete.")) Edouard@1893: else: Edouard@1906: raise Exception(_("WAMP config is missing.")) Edouard@1906: except Exception: Edouard@1906: LogMessageAndException(_("WAMP client startup failed. ")) Edouard@1446: Edouard@1984: plcobj = PLCObject(pyroserver) Edouard@1984: Edouard@1984: plcobj.AutoLoad() Edouard@1984: if plcobj.GetPLCstatus()[0] == "Stopped": Edouard@1984: if autostart: Edouard@1984: plcobj.StartPLC() Edouard@1984: plcobj.StatusChange() Edouard@1984: Edouard@1984: pyro_thread = Thread(target=pyroserver.PyroLoop) Edouard@1984: pyro_thread.start() Edouard@1984: edouard@1987: pyroserver.PrintServerInfo() Edouard@1446: Edouard@641: if havetwisted or havewx: Edouard@641: if havetwisted: Edouard@1984: # reactor._installSignalHandlersAgain() Edouard@1984: def ui_thread_target(): Edouard@1984: # FIXME: had to disable SignaHandlers install because Edouard@1984: # signal not working in non-main thread Edouard@1984: reactor.run(installSignalHandlers=False) Edouard@1984: else : Edouard@1984: ui_thread_target = app.MainLoop Edouard@1984: Edouard@1984: ui_thread = Thread(target = ui_thread_target) Edouard@1984: ui_thread.start() Edouard@1984: Edouard@1984: try: Edouard@1984: MainWorker.runloop() Edouard@1984: except KeyboardInterrupt: Edouard@1984: pass Edouard@1984: Edouard@641: pyroserver.Quit() Edouard@641: sys.exit(0)