Modbus and Bacnet websettings : Rename variables and functions to avoid name collisions.
authorEdouard Tisserant
Wed, 01 Jul 2020 10:36:20 +0200
changeset 2686 703ebf57508a
parent 2685 f71c22b2ca25
child 2687 c79c5d49ba34
Modbus and Bacnet websettings : Rename variables and functions to avoid name collisions.

Websettings for modbus and bacnet are now passed to runtime as python files loaded (execfile) at init of PLCObject with the same globals.
Because if this, same names used in previously different modules now colide.
bacnet/web_settings.py
modbus/web_settings.py
--- a/bacnet/web_settings.py	Mon Jun 29 14:38:04 2020 +0200
+++ b/bacnet/web_settings.py	Wed Jul 01 10:36:20 2020 +0200
@@ -34,14 +34,14 @@
 # Will contain references to the C functions 
 # (implemented in beremiz/bacnet/runtime/server.c)
 # used to get/set the BACnet specific configuration paramters
-GetParamFuncs = {}
-SetParamFuncs = {}
+BacnetGetParamFuncs = {}
+BacnetSetParamFuncs = {}
 
 
 # Upon PLC load, this Dictionary is initialised with the BACnet configuration
 # hardcoded in the C file
 # (i.e. the configuration inserted in Beremiz IDE when project was compiled)
-_DefaultConfiguration = None
+_BacnetDefaultConfiguration = None
 
 
 # Dictionary that contains the BACnet configuration currently being shown
@@ -52,13 +52,13 @@
 # The configuration viewed on the web will only be different to the current 
 # configuration when the user edits the configuration, and when
 # the user asks to save the edited configuration but it contains an error.
-_WebviewConfiguration = None
+_BacnetWebviewConfiguration = None
 
 
 # Dictionary that stores the BACnet configuration currently stored in a file
 # Currently only used to decide whether or not to show the "Delete" button on the
-# web interface (only shown if _SavedConfiguration is not None)
-_SavedConfiguration = None
+# web interface (only shown if _BacnetSavedConfiguration is not None)
+_BacnetSavedConfiguration = None
 
 
 # File to which the new BACnet configuration gets stored on the PLC
@@ -99,7 +99,7 @@
 
 
 
-def _CheckPortnumber(port_number):
+def _CheckBacnetPortnumber(port_number):
     """ check validity of the port number """
     try:
         portnum = int(port_number)
@@ -112,7 +112,7 @@
     
 
 
-def _CheckDeviceID(device_id):
+def _CheckBacnetDeviceID(device_id):
     """ 
     # check validity of the Device ID 
     # NOTE: BACnet device (object) IDs are 22 bits long (not counting the 10 bits for the type ID)
@@ -133,25 +133,25 @@
 
 
 
-def _CheckConfiguration(BACnetConfig):
+def _CheckBacnetConfiguration(BACnetConfig):
     res = True    
-    res = res and _CheckPortnumber(BACnetConfig["port_number"])
-    res = res and _CheckDeviceID  (BACnetConfig["device_id"])
+    res = res and _CheckBacnetPortnumber(BACnetConfig["port_number"])
+    res = res and _CheckBacnetDeviceID  (BACnetConfig["device_id"])
     return res
 
 
 
-def _CheckWebConfiguration(BACnetConfig):
+def _CheckBacnetWebConfiguration(BACnetConfig):
     res = True
     
     # check the port number
-    if not _CheckPortnumber(BACnetConfig["port_number"]):
+    if not _CheckBacnetPortnumber(BACnetConfig["port_number"]):
         raise annotate.ValidateError(
             {"port_number": "Invalid port number: " + str(BACnetConfig["port_number"])},
             _("BACnet configuration error:"))
         res = False
     
-    if not _CheckDeviceID(BACnetConfig["device_id"]):
+    if not _CheckBacnetDeviceID(BACnetConfig["device_id"]):
         raise annotate.ValidateError(
             {"device_id": "Invalid device ID: " + str(BACnetConfig["device_id"])},
             _("BACnet configuration error:"))
@@ -164,26 +164,26 @@
 
 
 
-def _SetSavedConfiguration(BACnetConfig):
+def _SetBacnetSavedConfiguration(BACnetConfig):
     """ Stores in a file a dictionary containing the BACnet parameter configuration """
-    global _SavedConfiguration
-
-    if BACnetConfig == _DefaultConfiguration :
-        _DelSavedConfiguration()
-        _SavedConfiguration = None
+    global _BacnetSavedConfiguration
+
+    if BACnetConfig == _BacnetDefaultConfiguration :
+        _DelBacnetSavedConfiguration()
+        _BacnetSavedConfiguration = None
     else :
         with open(os.path.realpath(_BACnetConfFilename), 'w') as f:
             json.dump(BACnetConfig, f, sort_keys=True, indent=4)
-        _SavedConfiguration = BACnetConfig
-
-
-def _DelSavedConfiguration():
+        _BacnetSavedConfiguration = BACnetConfig
+
+
+def _DelBacnetSavedConfiguration():
     """ Deletes the file cotaining the persistent BACnet configuration """
     if os.path.exists(_BACnetConfFilename):
         os.remove(_BACnetConfFilename)
 
 
-def _GetSavedConfiguration():
+def _GetBacnetSavedConfiguration():
     """
     # Returns a dictionary containing the BACnet parameter configuration
     # that was last saved to file. If no file exists, then return None
@@ -194,67 +194,67 @@
     except Exception:    
         return None
 
-    if _CheckConfiguration(saved_config):
+    if _CheckBacnetConfiguration(saved_config):
         return saved_config
     else:
         return None
 
 
-def _GetPLCConfiguration():
+def _GetBacnetPLCConfiguration():
     """
     # Returns a dictionary containing the current BACnet parameter configuration
     # stored in the C variables in the loaded PLC (.so file)
     """
     current_config = {}
     for par_name, x1, x2, x3 in BACnet_parameters:
-        value = GetParamFuncs[par_name]()
+        value = BacnetGetParamFuncs[par_name]()
         if value is not None:
             current_config[par_name] = value
     
     return current_config
 
 
-def _SetPLCConfiguration(BACnetConfig):
+def _SetBacnetPLCConfiguration(BACnetConfig):
     """
     # Stores the BACnet parameter configuration into the
     # the C variables in the loaded PLC (.so file)
     """
     for par_name in BACnetConfig:
         value = BACnetConfig[par_name]
-        #PLCObject.LogMessage("BACnet web server extension::_SetPLCConfiguration()  Setting "
+        #PLCObject.LogMessage("BACnet web server extension::_SetBacnetPLCConfiguration()  Setting "
         #                       + par_name + " to " + str(value) )
         if value is not None:
-            SetParamFuncs[par_name](value)
+            BacnetSetParamFuncs[par_name](value)
     # update the configuration shown on the web interface
-    global _WebviewConfiguration 
-    _WebviewConfiguration = _GetPLCConfiguration()
-
-
-
-def _GetWebviewConfigurationValue(ctx, argument):
+    global _BacnetWebviewConfiguration 
+    _BacnetWebviewConfiguration = _GetBacnetPLCConfiguration()
+
+
+
+def _GetBacnetWebviewConfigurationValue(ctx, argument):
     """
     # Callback function, called by the web interface (NevowServer.py)
     # to fill in the default value of each parameter
     """
     try:
-        return _WebviewConfiguration[argument.name]
+        return _BacnetWebviewConfiguration[argument.name]
     except Exception:
         return ""
 
 
 # The configuration of the web form used to see/edit the BACnet parameters
-webFormInterface = [(name, web_dtype (label=web_label, default=_GetWebviewConfigurationValue)) 
+webFormInterface = [(name, web_dtype (label=web_label, default=_GetBacnetWebviewConfigurationValue)) 
                     for name, web_label, c_dtype, web_dtype in BACnet_parameters]
 
 
-def OnButtonSave(**kwargs):
+def OnBacnetButtonSave(**kwargs):
     """
     # Function called when user clicks 'Save' button in web interface
     # The function will configure the BACnet plugin in the PLC with the values
     # specified in the web interface. However, values must be validated first!
     """
 
-    #PLCObject.LogMessage("BACnet web server extension::OnButtonSave()  Called")
+    #PLCObject.LogMessage("BACnet web server extension::OnBacnetButtonSave()  Called")
     
     newConfig = {}
     for par_name, x1, x2, x3 in BACnet_parameters:
@@ -264,20 +264,20 @@
 
     
     # First check if configuration is OK.
-    if not _CheckWebConfiguration(newConfig):
+    if not _CheckBacnetWebConfiguration(newConfig):
         return
 
     # store to file the new configuration so that 
     # we can recoup the configuration the next time the PLC
     # has a cold start (i.e. when Beremiz_service.py is retarted)
-    _SetSavedConfiguration(newConfig)
+    _SetBacnetSavedConfiguration(newConfig)
 
     # Configure PLC with the current BACnet parameters
-    _SetPLCConfiguration(newConfig)
-
-
-
-def OnButtonReset(**kwargs):
+    _SetBacnetPLCConfiguration(newConfig)
+
+
+
+def OnBacnetButtonReset(**kwargs):
     """
     # Function called when user clicks 'Delete' button in web interface
     # The function will delete the file containing the persistent
@@ -285,12 +285,12 @@
     """
 
     # Delete the file
-    _DelSavedConfiguration()
+    _DelBacnetSavedConfiguration()
     # Set the current configuration to the default (hardcoded in C)
-    _SetPLCConfiguration(_DefaultConfiguration)
+    _SetBacnetPLCConfiguration(_BacnetDefaultConfiguration)
     # Reset global variable
-    global _SavedConfiguration
-    _SavedConfiguration = None
+    global _BacnetSavedConfiguration
+    _BacnetSavedConfiguration = None
 
 
 
@@ -317,25 +317,25 @@
         
         # XXX TODO : stop reading from PLC .so file. This code is template code
         #            that can use modbus extension build data
-        GetParamFuncs[name]          = getattr(PLCObject.PLClibraryHandle, GetParamFuncName)
-        GetParamFuncs[name].restype  = c_dtype
-        GetParamFuncs[name].argtypes = None
+        BacnetGetParamFuncs[name]          = getattr(PLCObject.PLClibraryHandle, GetParamFuncName)
+        BacnetGetParamFuncs[name].restype  = c_dtype
+        BacnetGetParamFuncs[name].argtypes = None
         
-        SetParamFuncs[name]          = getattr(PLCObject.PLClibraryHandle, SetParamFuncName)
-        SetParamFuncs[name].restype  = None
-        SetParamFuncs[name].argtypes = [c_dtype]
+        BacnetSetParamFuncs[name]          = getattr(PLCObject.PLClibraryHandle, SetParamFuncName)
+        BacnetSetParamFuncs[name].restype  = None
+        BacnetSetParamFuncs[name].argtypes = [c_dtype]
 
     # Default configuration is the configuration done in Beremiz IDE
     # whose parameters get hardcoded into C, and compiled into the .so file
     # We read the default configuration from the .so file before the values
     # get changed by the user using the web server, or by the call (further on)
-    # to _SetPLCConfiguration(SavedConfiguration)
-    global _DefaultConfiguration 
-    _DefaultConfiguration = _GetPLCConfiguration()
+    # to _SetBacnetPLCConfiguration(BacnetSavedConfiguration)
+    global _BacnetDefaultConfiguration 
+    _BacnetDefaultConfiguration = _GetBacnetPLCConfiguration()
     
     # Show the current PLC configuration on the web interface        
-    global _WebviewConfiguration
-    _WebviewConfiguration = _GetPLCConfiguration()
+    global _BacnetWebviewConfiguration
+    _BacnetWebviewConfiguration = _GetBacnetPLCConfiguration()
  
     # Read from file the last used configuration, which is likely
     # different to the hardcoded configuration.
@@ -344,13 +344,13 @@
     # so the PLC will start off with this saved configuration instead
     # of the hardcoded (in Beremiz C generated code) configuration values.
     #
-    # Note that _SetPLCConfiguration() will also update 
-    # _WebviewConfiguration , if necessary.
-    global _SavedConfiguration
-    _SavedConfiguration  = _GetSavedConfiguration()
-    if _SavedConfiguration is not None:
-        if _CheckConfiguration(_SavedConfiguration):
-            _SetPLCConfiguration(_SavedConfiguration)
+    # Note that _SetBacnetPLCConfiguration() will also update 
+    # _BacnetWebviewConfiguration , if necessary.
+    global _BacnetSavedConfiguration
+    _BacnetSavedConfiguration  = _GetBacnetSavedConfiguration()
+    if _BacnetSavedConfiguration is not None:
+        if _CheckBacnetConfiguration(_BacnetSavedConfiguration):
+            _SetBacnetPLCConfiguration(_BacnetSavedConfiguration)
             
     WebSettings = NS.newExtensionSetting("BACnet extension", "bacnet_token")
 
@@ -360,7 +360,7 @@
         _("BACnet Configuration"),         # description
         webFormInterface,                  # fields
         _("Apply"),  # button label
-        OnButtonSave)                      # callback    
+        OnBacnetButtonSave)                      # callback    
 
     # Add the Delete button to the web interface
     WebSettings.addSettings(
@@ -369,15 +369,15 @@
         [ ("status",
            annotate.String(label=_("Current state"),
                            immutable=True,
-                           default=lambda *k:getConfigStatus())),
+                           default=lambda *k:getBacnetConfigStatus())),
         ],                                       # fields  (empty, no parameters required!)
         _("Reset"), # button label
-        OnButtonReset) 
-
-
-
-def getConfigStatus():
-    if _WebviewConfiguration == _DefaultConfiguration :
+        OnBacnetButtonReset) 
+
+
+
+def getBacnetConfigStatus():
+    if _BacnetWebviewConfiguration == _BacnetDefaultConfiguration :
         return "Unchanged"
     return "Modified"
 
@@ -392,11 +392,11 @@
     
     NS.removeExtensionSetting("bacnet_token")
     
-    GetParamFuncs = {}
-    SetParamFuncs = {}
-    _WebviewConfiguration = None
-    _SavedConfiguration   = None
-
-
-
-
+    BacnetGetParamFuncs = {}
+    BacnetSetParamFuncs = {}
+    _BacnetWebviewConfiguration = None
+    _BacnetSavedConfiguration   = None
+
+
+
+
--- a/modbus/web_settings.py	Mon Jun 29 14:38:04 2020 +0200
+++ b/modbus/web_settings.py	Wed Jul 01 10:36:20 2020 +0200
@@ -213,14 +213,14 @@
 
 
 
-def _SetSavedConfiguration(WebNode_id, newConfig):
+def _SetModbusSavedConfiguration(WebNode_id, newConfig):
     """ Stores a dictionary in a persistant file containing the Modbus parameter configuration """
     WebNode_entry = _WebNodeList[WebNode_id]
 
     if WebNode_entry["DefaultConfiguration"] == newConfig:
 
-        _DelSavedConfiguration(WebNode_id)
-        WebNode_entry["SavedConfiguration"] = None
+        _DelModbusSavedConfiguration(WebNode_id)
+        WebNode_entry["ModbusSavedConfiguration"] = None
 
     else:
 
@@ -237,12 +237,12 @@
         with open(os.path.realpath(filename), 'w') as f:
             json.dump(save_info, f, sort_keys=True, indent=4)
             
-        WebNode_entry["SavedConfiguration"] = newConfig
-
-
-
-
-def _DelSavedConfiguration(WebNode_id):
+        WebNode_entry["ModbusSavedConfiguration"] = newConfig
+
+
+
+
+def _DelModbusSavedConfiguration(WebNode_id):
     """ Deletes the file cotaining the persistent Modbus configuration """
     filename = _WebNodeList[WebNode_id]["filename"]
     
@@ -252,7 +252,7 @@
 
 
 
-def _GetSavedConfiguration(WebNode_id):
+def _GetModbusSavedConfiguration(WebNode_id):
     """
     Returns a dictionary containing the Modbus parameter configuration
     that was last saved to file. If no file exists, or file contains 
@@ -284,7 +284,7 @@
 
 
 
-def _GetPLCConfiguration(WebNode_id):
+def _GetModbusPLCConfiguration(WebNode_id):
     """
     Returns a dictionary containing the current Modbus parameter configuration
     stored in the C variables in the loaded PLC (.so file)
@@ -303,7 +303,7 @@
 
 
 
-def _SetPLCConfiguration(WebNode_id, newconfig):
+def _SetModbusPLCConfiguration(WebNode_id, newconfig):
     """
     Stores the Modbus parameter configuration into the
     the C variables in the loaded PLC (.so file)
@@ -319,7 +319,7 @@
 
 
 
-def _GetWebviewConfigurationValue(ctx, WebNode_id, argument):
+def _GetModbusWebviewConfigurationValue(ctx, WebNode_id, argument):
     """
     Callback function, called by the web interface (NevowServer.py)
     to fill in the default value of each parameter of the web form
@@ -335,7 +335,7 @@
 
 
 
-def OnButtonSave(**kwargs):
+def OnModbusButtonSave(**kwargs):
     """
     Function called when user clicks 'Save' button in web interface
     The function will configure the Modbus plugin in the PLC with the values
@@ -346,7 +346,7 @@
     "WebNode_id" argument, and call this function to do the work.
     """
 
-    #PLCObject.LogMessage("Modbus web server extension::OnButtonSave()  Called")
+    #PLCObject.LogMessage("Modbus web server extension::OnModbusButtonSave()  Called")
     
     newConfig    = {}
     WebNode_id   =  kwargs.get("WebNode_id", None)
@@ -366,19 +366,19 @@
     # store to file the new configuration so that 
     # we can recoup the configuration the next time the PLC
     # has a cold start (i.e. when Beremiz_service.py is retarted)
-    _SetSavedConfiguration(WebNode_id, newConfig)
+    _SetModbusSavedConfiguration(WebNode_id, newConfig)
 
     # Configure PLC with the current Modbus parameters
-    _SetPLCConfiguration(WebNode_id, newConfig)
+    _SetModbusPLCConfiguration(WebNode_id, newConfig)
 
     # Update the viewable configuration
-    # The PLC may have coerced the values on calling _SetPLCConfiguration()
+    # The PLC may have coerced the values on calling _SetModbusPLCConfiguration()
     # so we do not set it directly to newConfig
-    _WebNodeList[WebNode_id]["WebviewConfiguration"] = _GetPLCConfiguration(WebNode_id)
-
-
-
-def OnButtonReset(**kwargs):
+    _WebNodeList[WebNode_id]["WebviewConfiguration"] = _GetModbusPLCConfiguration(WebNode_id)
+
+
+
+def OnModbusButtonReset(**kwargs):
     """
     Function called when user clicks 'Delete' button in web interface
     The function will delete the file containing the persistent
@@ -388,17 +388,17 @@
     WebNode_id = kwargs.get("WebNode_id", None)
     
     # Delete the file
-    _DelSavedConfiguration(WebNode_id)
+    _DelModbusSavedConfiguration(WebNode_id)
 
     # Set the current configuration to the default (hardcoded in C)
     new_config = _WebNodeList[WebNode_id]["DefaultConfiguration"]
-    _SetPLCConfiguration(WebNode_id, new_config)
+    _SetModbusPLCConfiguration(WebNode_id, new_config)
     
     #Update the webviewconfiguration
     _WebNodeList[WebNode_id]["WebviewConfiguration"] = new_config
     
-    # Reset SavedConfiguration
-    _WebNodeList[WebNode_id]["SavedConfiguration"] = None
+    # Reset ModbusSavedConfiguration
+    _WebNodeList[WebNode_id]["ModbusSavedConfiguration"] = None
     
 
 
@@ -461,17 +461,17 @@
     # Upon PLC load, this Dictionary is initialised with the Modbus configuration
     # hardcoded in the C file
     # (i.e. the configuration inserted in Beremiz IDE when project was compiled)
-    WebNode_entry["DefaultConfiguration"] = _GetPLCConfiguration(WebNode_id)
+    WebNode_entry["DefaultConfiguration"] = _GetModbusPLCConfiguration(WebNode_id)
     WebNode_entry["WebviewConfiguration"] = WebNode_entry["DefaultConfiguration"]
     
     # Dictionary that stores the Modbus configuration currently stored in a file
     # Currently only used to decide whether or not to show the "Delete" button on the
-    # web interface (only shown if "SavedConfiguration" is not None)
-    SavedConfig = _GetSavedConfiguration(WebNode_id)
-    WebNode_entry["SavedConfiguration"] = SavedConfig
+    # web interface (only shown if "ModbusSavedConfiguration" is not None)
+    SavedConfig = _GetModbusSavedConfiguration(WebNode_id)
+    WebNode_entry["ModbusSavedConfiguration"] = SavedConfig
     
     if SavedConfig is not None:
-        _SetPLCConfiguration(WebNode_id, SavedConfig)
+        _SetModbusPLCConfiguration(WebNode_id, SavedConfig)
         WebNode_entry["WebviewConfiguration"] = SavedConfig
         
     # Define the format for the web form used to show/change the current parameters
@@ -486,14 +486,14 @@
     #           even though we store it as an integer, which is the data type expected
     #           by the set_***() C functions in mb_runtime.c
     def __GetWebviewConfigurationValue(ctx, argument):
-        return str(_GetWebviewConfigurationValue(ctx, WebNode_id, argument))
+        return str(_GetModbusWebviewConfigurationValue(ctx, WebNode_id, argument))
     
     webFormInterface = [(name, web_dtype (label=web_label, default=__GetWebviewConfigurationValue)) 
                     for name, web_label, c_dtype, web_dtype in WebNode_entry["WebParamList"]]
 
     # Configure the web interface to include the Modbus config parameters
     def __OnButtonSave(**kwargs):
-        OnButtonSave(WebNode_id=WebNode_id, **kwargs)
+        OnModbusButtonSave(WebNode_id=WebNode_id, **kwargs)
 
     WebSettings = NS.newExtensionSetting("Modbus #"+ str(WebNode_id), config_hash)
 
@@ -505,9 +505,9 @@
         __OnButtonSave)                                # callback   
     
     def __OnButtonReset(**kwargs):
-        return OnButtonReset(WebNode_id = WebNode_id, **kwargs)
+        return OnModbusButtonReset(WebNode_id = WebNode_id, **kwargs)
             
-    def getConfigStatus():
+    def getModbusConfigStatus():
         if WebNode_entry["WebviewConfiguration"] == WebNode_entry["DefaultConfiguration"]:
             return "Unchanged"
         return "Modified"
@@ -518,7 +518,7 @@
         [ ("status",
            annotate.String(label=_("Current state"),
                            immutable=True,
-                           default=lambda *k:getConfigStatus())),
+                           default=lambda *k:getModbusConfigStatus())),
         ],                                       # fields  (empty, no parameters required!)
         _("Reset"), # button label
         __OnButtonReset)