79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
from lxml import etree
|
|
class Xml_reader:
|
|
""" reader for the XML configuration """
|
|
|
|
def __init__(self, xml_path, xsd_path):
|
|
"""inits the reader
|
|
|
|
Args:
|
|
path (string): path to the XML config file
|
|
"""
|
|
#check the XML for validity using the XSD file
|
|
if not self.validate(xml_path,xsd_path):
|
|
raise SyntaxError('the XML config file has an invalid syntax')
|
|
self.root = etree.parse(xml_path).getroot()
|
|
|
|
def validate(self, xml_path:str, xsd_path: str) -> bool:
|
|
"""validates a xml by using a xsd file
|
|
|
|
Args:
|
|
xml_path (str): the path to the xml file
|
|
xsd_path (str): the path to the xsd file
|
|
|
|
Returns:
|
|
bool: result of the validation
|
|
"""
|
|
xml_schema = etree.XMLSchema(etree.parse(xsd_path))
|
|
return xml_schema.validate(etree.parse(xml_path))
|
|
|
|
def get_device_names(self):
|
|
"""returns the names of all devices in the config
|
|
|
|
Returns:
|
|
list: names of the devices
|
|
"""
|
|
return [device.get("name") for device in self.root.findall('Device')]
|
|
|
|
def get_value_info(self,device_name):
|
|
"""returns the value information for a device
|
|
|
|
Args:
|
|
device_name (string): the name of the relevant device
|
|
|
|
Returns:
|
|
dict: {'type','unit','offset','factor'}
|
|
"""
|
|
if self.root.find("Device[@name='%s']" % device_name) is None:
|
|
return None
|
|
value_info = self.root.find(
|
|
"Device[@name='%s']/ValueInfo" % device_name)
|
|
return {
|
|
'type': value_info.get('type'),
|
|
'unit': value_info.get('unit'),
|
|
'offset': None if value_info.find("Offset") is None
|
|
else value_info.find("Offset").text,
|
|
'factor': None if value_info.find("Factor") is None
|
|
else value_info.find("Factor").text,
|
|
}
|
|
|
|
def get_port(self,device_name):
|
|
"""returns the port details for a device
|
|
|
|
Args:
|
|
device_name (string): the name of the relevant device
|
|
|
|
Returns:
|
|
dict: {'protocol', [list: pins]}
|
|
"""
|
|
if self.root.find("Device[@name='%s']" % device_name) is None:
|
|
return None
|
|
port = self.root.find(
|
|
"Device[@name='%s']/Port" % device_name)
|
|
return {
|
|
'protocol': port.get('protocol'),
|
|
'pins': [
|
|
pin.text for pin in self.root.findall(
|
|
"Device[@name='%s']/Port/Pin" % device_name
|
|
)
|
|
]
|
|
} |