Use predefined constants for PlcStatus instead of string literals
authorAndrey Skvortsov <andrej.skvortzov@gmail.com>
Tue, 02 Oct 2018 16:53:14 +0300
changeset 2416 1ca207782dde
parent 2415 f7d8891fe708
child 2417 316ee9fff395
Use predefined constants for PlcStatus instead of string literals
Beremiz_service.py
ProjectController.py
connectors/PYRO/__init__.py
connectors/WAMP/__init__.py
etherlab/EtherCATManagementEditor.py
runtime/PLCObject.py
runtime/PlcStatus.py
--- a/Beremiz_service.py	Mon Oct 01 15:53:34 2018 +0300
+++ b/Beremiz_service.py	Tue Oct 02 16:53:14 2018 +0300
@@ -38,6 +38,7 @@
 
 from runtime import PLCObject, ServicePublisher, MainWorker
 from runtime.xenomai import TryPreloadXenomai
+from runtime import PlcStatus
 import util.paths as paths
 
 
@@ -311,14 +312,14 @@
             def OnTaskBarStartPLC(self, evt):
                 if self.pyroserver.plcobj is not None:
                     plcstatus = self.pyroserver.plcobj.GetPLCstatus()[0]
-                    if plcstatus is "Stopped":
+                    if plcstatus is PlcStatus.Stopped:
                         self.pyroserver.plcobj.StartPLC()
                     else:
                         print(_("PLC is empty or already started."))
 
             def OnTaskBarStopPLC(self, evt):
                 if self.pyroserver.plcobj is not None:
-                    if self.pyroserver.plcobj.GetPLCstatus()[0] == "Started":
+                    if self.pyroserver.plcobj.GetPLCstatus()[0] == PlcStatus.Started:
                         Thread(target=self.pyroserver.plcobj.StopPLC).start()
                     else:
                         print(_("PLC is not started."))
@@ -383,9 +384,9 @@
                 wx.CallAfter(wx.GetApp().ExitMainLoop)
 
             def UpdateIcon(self, plcstatus):
-                if plcstatus is "Started":
+                if plcstatus is PlcStatus.Started:
                     currenticon = self.MakeIcon(starticon)
-                elif plcstatus is "Stopped":
+                elif plcstatus is PlcStatus.Stopped:
                     currenticon = self.MakeIcon(stopicon)
                 else:
                     currenticon = self.MakeIcon(defaulticon)
@@ -481,7 +482,7 @@
 
     def AutoLoad(self):
         self.plcobj.AutoLoad()
-        if self.plcobj.GetPLCstatus()[0] == "Stopped":
+        if self.plcobj.GetPLCstatus()[0] == PlcStatus.Stopped:
             if autostart:
                 self.plcobj.StartPLC()
         self.plcobj.StatusChange()
--- a/ProjectController.py	Mon Oct 01 15:53:34 2018 +0300
+++ b/ProjectController.py	Tue Oct 02 16:53:14 2018 +0300
@@ -61,6 +61,7 @@
 from plcopen.types_enums import ComputeConfigurationResourceName, ITEM_CONFNODE
 import targets
 from runtime.typemapping import DebugTypesSize, UnpackDebugBuffer
+from runtime import PlcStatus
 from ConfigTreeNode import ConfigTreeNode, XSDSchemaErrorMessage
 
 base_folder = paths.AbsParentDir(__file__)
@@ -1422,20 +1423,20 @@
     }
 
     MethodsFromStatus = {
-        "Started":      {"_Stop": True,
-                         "_Transfer": True,
-                         "_Connect": False,
-                         "_Disconnect": True},
-        "Stopped":      {"_Run": True,
-                         "_Transfer": True,
-                         "_Connect": False,
-                         "_Disconnect": True},
-        "Empty":        {"_Transfer": True,
-                         "_Connect": False,
-                         "_Disconnect": True},
-        "Broken":       {"_Connect": False,
-                         "_Disconnect": True},
-        "Disconnected": {},
+        PlcStatus.Started:      {"_Stop": True,
+                                 "_Transfer": True,
+                                 "_Connect": False,
+                                 "_Disconnect": True},
+        PlcStatus.Stopped:      {"_Run": True,
+                                 "_Transfer": True,
+                                 "_Connect": False,
+                                 "_Disconnect": True},
+        PlcStatus.Empty:        {"_Transfer": True,
+                                 "_Connect": False,
+                                 "_Disconnect": True},
+        PlcStatus.Broken:       {"_Connect": False,
+                                 "_Disconnect": True},
+        PlcStatus.Disconnected: {},
     }
 
     def UpdateMethodsFromPLCStatus(self):
@@ -1448,7 +1449,7 @@
                 self.UpdatePLCLog(log_count)
         if status is None:
             self._SetConnector(None, False)
-            status = "Disconnected"
+            status = PlcStatus.Disconnected
         if self.previous_plcstate != status:
             allmethods = self.DefaultMethods.copy()
             allmethods.update(
@@ -1459,31 +1460,21 @@
             if self.AppFrame is not None:
                 updated = True
                 self.AppFrame.RefreshStatusToolBar()
-                if status == "Disconnected":
+                if status == PlcStatus.Disconnected:
                     self.AppFrame.ConnectionStatusBar.SetStatusText(
-                        self.GetTextStatus(status), 1)
+                        _(status), 1)
                     self.AppFrame.ConnectionStatusBar.SetStatusText('', 2)
                 else:
                     self.AppFrame.ConnectionStatusBar.SetStatusText(
                         _("Connected to URI: %s") % self.BeremizRoot.getURI_location().strip(), 1)
                     self.AppFrame.ConnectionStatusBar.SetStatusText(
-                        self.GetTextStatus(status), 2)
+                        _(status), 2)
         return updated
 
-    def GetTextStatus(self, status):
-        msgs = {
-            "Started":      _("Started"),
-            "Stopped":      _("Stopped"),
-            "Empty":        _("Empty"),
-            "Broken":       _("Broken"),
-            "Disconnected": _("Disconnected")
-        }
-        return msgs.get(status, status)
-
     def ShowPLCProgress(self, status="", progress=0):
         self.AppFrame.ProgressStatusBar.Show()
         self.AppFrame.ConnectionStatusBar.SetStatusText(
-            self.GetTextStatus(status), 1)
+            _(status), 1)
         self.AppFrame.ProgressStatusBar.SetValue(progress)
 
     def HidePLCProgress(self):
@@ -1501,7 +1492,7 @@
             plc_status, Traces = self._connector.GetTraceVariables()
             # print [dict.keys() for IECPath, (dict, log, status, fvalue) in
             # self.IECdebug_datas.items()]
-            if plc_status == "Started":
+            if plc_status == PlcStatus.Started:
                 if len(Traces) > 0:
                     for debug_tick, debug_buff in Traces:
                         debug_vars = UnpackDebugBuffer(
@@ -1570,7 +1561,7 @@
             self.SnapshotAndResetDebugValuesBuffers()
 
     def IsPLCStarted(self):
-        return self.previous_plcstate == "Started"
+        return self.previous_plcstate == PlcStatus.Started
 
     def ReArmDebugRegisterTimer(self):
         if self.DebugTimer is not None:
@@ -1809,7 +1800,7 @@
 
             # Init with actual PLC status and print it
             self.UpdateMethodsFromPLCStatus()
-            if self.previous_plcstate in ["Started", "Stopped"]:
+            if self.previous_plcstate in [PlcStatus.Started, PlcStatus.Stopped]:
                 if self.DebugAvailable() and self.GetIECProgramsAndVariables():
                     self.logger.write(_("Debugger ready\n"))
                     self._connect_debug()
--- a/connectors/PYRO/__init__.py	Mon Oct 01 15:53:34 2018 +0300
+++ b/connectors/PYRO/__init__.py	Tue Oct 02 16:53:14 2018 +0300
@@ -36,6 +36,7 @@
 import Pyro.util
 from Pyro.errors import PyroError
 
+from runtime import PlcStatus
 
 service_type = '_PYRO._tcp.local.'
 # this module attribute contains a list of DNS-SD (Zeroconf) service types
@@ -142,7 +143,7 @@
     _special_return_funcs = {
         "StartPLC": False,
         "GetTraceVariables": ("Broken", None),
-        "GetPLCstatus": ("Broken", None),
+        "GetPLCstatus": (PlcStatus.Broken, None),
         "RemoteExec": (-1, "RemoteExec script failed!")
     }
 
--- a/connectors/WAMP/__init__.py	Mon Oct 01 15:53:34 2018 +0300
+++ b/connectors/WAMP/__init__.py	Tue Oct 02 16:53:14 2018 +0300
@@ -36,6 +36,7 @@
 from autobahn.wamp.exception import TransportLost
 from autobahn.wamp.serializer import MsgPackSerializer
 
+from runtime import PlcStatus
 
 _WampSession = None
 _WampConnection = None
@@ -59,7 +60,7 @@
 PLCObjDefaults = {
     "StartPLC":          False,
     "GetTraceVariables": ("Broken", None),
-    "GetPLCstatus":      ("Broken", None),
+    "GetPLCstatus":      (PlcStatus.Broken, None),
     "RemoteExec":        (-1, "RemoteExec script failed!")
 }
 
--- a/etherlab/EtherCATManagementEditor.py	Mon Oct 01 15:53:34 2018 +0300
+++ b/etherlab/EtherCATManagementEditor.py	Tue Oct 02 16:53:14 2018 +0300
@@ -19,6 +19,7 @@
 
 # --------------------------------------------------------------------
 from controls import CustomGrid, CustomTable
+from runtime import PlcStatus
 # --------------------------------------------------------------------
 
 # ------------ for register management ---------------
@@ -242,7 +243,7 @@
             #  (2) Otherwise, show error message and return
             else:
                 status, _log_count = self.Controler.GetCTRoot()._connector.GetPLCstatus()
-                if status == "Started":
+                if status == PlcStatus.Started:
                     self.Controler.CommonMethod.RequestSlaveState("OP")
                     self.TextCtrlDic["TargetState"].SetValue("OP")
                 else:
@@ -906,7 +907,7 @@
         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
         if check_connect_flag:
             status, _log_count = self.Controler.GetCTRoot()._connector.GetPLCstatus()
-            if status is not "Started":
+            if status is not PlcStatus.Started:
                 dialog = wx.FileDialog(self, _("Choose a binary file"), os.getcwd(), "",  _("bin files (*.bin)|*.bin"), wx.OPEN)
 
                 if dialog.ShowModal() == wx.ID_OK:
@@ -1275,7 +1276,7 @@
         check_connect_flag = self.Controler.CommonMethod.CheckConnect(False)
         if check_connect_flag:
             status, _log_count = self.Controler.GetCTRoot()._connector.GetPLCstatus()
-            if status is not "Started":
+            if status is not PlcStatus.Started:
                 self.Controler.CommonMethod.SiiWrite(self.SiiBinary)
                 self.Controler.CommonMethod.Rescan()
 
--- a/runtime/PLCObject.py	Mon Oct 01 15:53:34 2018 +0300
+++ b/runtime/PLCObject.py	Tue Oct 02 16:53:14 2018 +0300
@@ -35,6 +35,7 @@
 
 from runtime.typemapping import TypeTranslator
 from runtime.loglevels import LogLevelsDefault, LogLevelsCount
+from runtime import PlcStatus
 
 if os.name in ("nt", "ce"):
     dlopen = _ctypes.LoadLibrary
@@ -175,7 +176,7 @@
         self.evaluator = server.evaluator
         self.argv = [server.workdir] + server.argv  # force argv[0] to be "path" to exec...
         self.workingdir = server.workdir
-        self.PLCStatus = "Empty"
+        self.PLCStatus = PlcStatus.Empty
         self.PLClibraryHandle = None
         self.PLClibraryLock = Lock()
         self.DummyIteratorLock = None
@@ -199,9 +200,9 @@
                 self._GetMD5FileName(),
                 "r").read().strip() + lib_ext
             if self.LoadPLC():
-                self.PLCStatus = "Stopped"
+                self.PLCStatus = PlcStatus.Stopped
         except Exception:
-            self.PLCStatus = "Empty"
+            self.PLCStatus = PlcStatus.Empty
             self.CurrentPLCFilename = None
 
     def StatusChange(self):
@@ -502,11 +503,11 @@
 
     @RunInMain
     def StartPLC(self):
-        if self.CurrentPLCFilename is not None and self.PLCStatus == "Stopped":
+        if self.CurrentPLCFilename is not None and self.PLCStatus == PlcStatus.Stopped:
             c_argv = ctypes.c_char_p * len(self.argv)
             res = self._startPLC(len(self.argv), c_argv(*self.argv))
             if res == 0:
-                self.PLCStatus = "Started"
+                self.PLCStatus = PlcStatus.Started
                 self.StatusChange()
                 self.PythonRuntimeCall("start")
                 self.StartSem = Semaphore(0)
@@ -516,16 +517,16 @@
                 self.LogMessage("PLC started")
             else:
                 self.LogMessage(0, _("Problem starting PLC : error %d" % res))
-                self.PLCStatus = "Broken"
+                self.PLCStatus = PlcStatus.Broken
                 self.StatusChange()
 
     @RunInMain
     def StopPLC(self):
-        if self.PLCStatus == "Started":
+        if self.PLCStatus == PlcStatus.Started:
             self.LogMessage("PLC stopped")
             self._stopPLC()
             self.PythonThread.join()
-            self.PLCStatus = "Stopped"
+            self.PLCStatus = PlcStatus.Stopped
             self.StatusChange()
             self.PythonRuntimeCall("stop")
             if self.TraceThread is not None:
@@ -540,7 +541,7 @@
 
     @RunInMain
     def NewPLC(self, md5sum, data, extrafiles):
-        if self.PLCStatus in ["Stopped", "Empty", "Broken"]:
+        if self.PLCStatus in [PlcStatus.Stopped, PlcStatus.Empty, PlcStatus.Broken]:
             NewFileName = md5sum + lib_ext
             extra_files_log = os.path.join(self.workingdir, "extra_files.txt")
 
@@ -556,7 +557,7 @@
                 self.UnLoadPLC()
 
             self.LogMessage("NewPLC (%s)" % md5sum)
-            self.PLCStatus = "Empty"
+            self.PLCStatus = PlcStatus.Empty
 
             try:
                 if replace_PLC_shared_object:
@@ -587,20 +588,20 @@
                 # Store new PLC filename
                 self.CurrentPLCFilename = NewFileName
             except Exception:
-                self.PLCStatus = "Broken"
+                self.PLCStatus = PlcStatus.Broken
                 self.StatusChange()
                 PLCprint(traceback.format_exc())
                 return False
 
             if not replace_PLC_shared_object:
-                self.PLCStatus = "Stopped"
+                self.PLCStatus = PlcStatus.Stopped
             elif self.LoadPLC():
-                self.PLCStatus = "Stopped"
+                self.PLCStatus = PlcStatus.Stopped
             else:
-                self.PLCStatus = "Broken"
+                self.PLCStatus = PlcStatus.Broken
             self.StatusChange()
 
-            return self.PLCStatus == "Stopped"
+            return self.PLCStatus == PlcStatus.Stopped
         return False
 
     def MatchMD5(self, MD5):
@@ -635,7 +636,7 @@
 
     def _TracesSwap(self):
         self.LastSwapTrace = time()
-        if self.TraceThread is None and self.PLCStatus == "Started":
+        if self.TraceThread is None and self.PLCStatus == PlcStatus.Started:
             self.TraceThread = Thread(target=self.TraceThreadProc)
             self.TraceThread.start()
         self.TraceLock.acquire()
@@ -653,7 +654,7 @@
         Return a list of traces, corresponding to the list of required idx
         """
         self._resumeDebug()  # Re-enable debugger
-        while self.PLCStatus == "Started":
+        while self.PLCStatus == PlcStatus.Started:
             tick = ctypes.c_uint32()
             size = ctypes.c_uint32()
             buff = ctypes.c_void_p()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/runtime/PlcStatus.py	Tue Oct 02 16:53:14 2018 +0300
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+
+# See COPYING.Runtime file for copyrights details.
+
+
+def _(x):
+    """No translation"""
+    return x
+
+
+Broken = _("Broken")
+Started = _("Started")
+Stopped = _("Stopped")
+Disconnected = _("Disconnected")
+Empty = _("Empty")