PMCUCalculatedParameter.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import re
  2. from pimonitor.cu.PMCUParameter import PMCUParameter
  3. from pimonitor.cu.PMCUStandardParameter import PMCUStandardParameter
  4. __author__ = 'citan'
  5. class PMCUCalculatedParameter(PMCUStandardParameter):
  6. def __init__(self, pid, name, desc, target):
  7. PMCUStandardParameter.__init__(self, pid, name, desc, PMCUParameter.CU_INVALID_BYTE_INDEX(),
  8. PMCUParameter.CU_INVALID_BIT_INDEX(), target)
  9. self._cu_type = PMCUParameter.CU_TYPE_CALCULATED_PARAMETER()
  10. self._dependencies = []
  11. def add_dependency(self, parameter):
  12. self._dependencies.append(parameter)
  13. def get_calculated_value(self, packets, unit=None):
  14. value = ""
  15. local_vars = locals()
  16. if len(self._conversions) > 0 and unit is None:
  17. unit = self._conversions[0][0]
  18. for conversion in self._conversions:
  19. curr_unit = conversion.get_unit()
  20. expr = conversion.get_expr()
  21. value_format = conversion.get_format()
  22. conversion_map = {}
  23. if unit == curr_unit:
  24. param_pairs = re.findall(r'\[([^]]*)\]', expr)
  25. for pair in param_pairs:
  26. attributes = pair.split(":")
  27. key = attributes[0]
  28. unit = attributes[1]
  29. expr = expr.replace("[" + key + ":" + unit + "]", key)
  30. conversion_map.update({key: unit})
  31. param_no = 0
  32. for packet in packets:
  33. param = self._parameters[param_no]
  34. if param.get_id() in conversion_map:
  35. conversion_unit = conversion_map[param.get_id()]
  36. else:
  37. conversion_unit = None
  38. if param.get_dependencies():
  39. return "DEPS :("
  40. else:
  41. value = param.get_value(packet, conversion_unit)
  42. local_vars[param.get_id()] = float(value)
  43. param_no += 1
  44. try:
  45. value = eval(expr)
  46. except (SyntaxError, ZeroDivisionError):
  47. value = 0.0
  48. format_tokens = value_format.split(".")
  49. output_format = "%.0f"
  50. if len(format_tokens) > 1:
  51. output_format = "%." + str(len(format_tokens[1])) + "f"
  52. value = output_format % value
  53. return value
  54. def is_supported(self, parameters):
  55. param_ids = [p.get_id() for p in parameters]
  56. for dependency in self._dependencies:
  57. if dependency not in param_ids:
  58. return False
  59. return True
  60. def to_string(self):
  61. return "id=" + self._id + "\nname=" + self._name + "\ndesc=" + self._desc + "\ntarget=" + str(
  62. self._target) + "\nconversion:\n\t" + '%s' % ',\n\t'.join(x.to_string() for x in self._conversions) + \
  63. '\ndependency: ' + '%s' % ', '.join(x for x in self._dependencies)