utils.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333
  1. # SPDX-License-Identifier: Apache-2.0
  2. # Copyright 2020 Contributors to OpenLEADR
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS,
  9. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. # See the License for the specific language governing permissions and
  11. # limitations under the License.
  12. from asyncio import iscoroutine
  13. from datetime import datetime, timedelta, timezone
  14. import random
  15. import string
  16. from collections import OrderedDict
  17. import itertools
  18. import re
  19. from pyopenadr import config
  20. DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
  21. DATETIME_FORMAT_NO_MICROSECONDS = "%Y-%m-%dT%H:%M:%SZ"
  22. def new_request_id(*args, **kwargs):
  23. return random.choice(string.ascii_lowercase) + ''.join(random.choice(string.hexdigits) for _ in range(9)).lower()
  24. def generate_id(*args, **kwargs):
  25. return new_request_id()
  26. def indent_xml(message):
  27. """
  28. Indents the XML in a nice way.
  29. """
  30. INDENT_SIZE = 2
  31. lines = [line.strip() for line in message.split("\n") if line.strip() != ""]
  32. indent = 0
  33. for i, line in enumerate(lines):
  34. if i == 0:
  35. continue
  36. if re.search(r'^</[^>]+>$', line):
  37. indent = indent - INDENT_SIZE
  38. lines[i] = " " * indent + line
  39. if not (re.search(r'</[^>]+>$', line) or line.endswith("/>")):
  40. indent = indent + INDENT_SIZE
  41. return "\n".join(lines)
  42. def normalize_dict(ordered_dict):
  43. """
  44. Convert the OrderedDict to a regular dict, snake_case the key names, and promote uniform lists.
  45. """
  46. def normalize_key(key):
  47. if key.startswith('oadr'):
  48. key = key[4:]
  49. elif key.startswith('ei'):
  50. key = key[2:]
  51. key = re.sub(r'([a-z])([A-Z])', r'\1_\2', key)
  52. if '-' in key:
  53. key = key.replace('-', '_')
  54. return key.lower()
  55. d = {}
  56. for key, value in ordered_dict.items():
  57. # Interpret values from the dict
  58. if key.startswith("@"):
  59. continue
  60. key = normalize_key(key)
  61. if isinstance(value, OrderedDict):
  62. d[key] = normalize_dict(value)
  63. elif isinstance(value, list):
  64. d[key] = []
  65. for item in value:
  66. if isinstance(item, OrderedDict):
  67. dict_item = normalize_dict(item)
  68. d[key].append(normalize_dict(dict_item))
  69. else:
  70. d[key].append(item)
  71. elif key in ("duration", "startafter", "max_period", "min_period"):
  72. d[key] = parse_duration(value)
  73. elif "date_time" in key and isinstance(value, str):
  74. d[key] = parse_datetime(value)
  75. elif value in ('true', 'false'):
  76. d[key] = parse_boolean(value)
  77. elif isinstance(value, str):
  78. d[key] = parse_int(value) or parse_float(value) or value
  79. else:
  80. d[key] = value
  81. # Do our best to make the dictionary structure as pythonic as possible
  82. if key.startswith("x_ei_"):
  83. d[key[5:]] = d.pop(key)
  84. key = key[5:]
  85. # Group all targets as a list of dicts under the key "target"
  86. if key in ("target", "report_subject", "report_data_source"):
  87. targets = d.pop(key)
  88. new_targets = []
  89. if targets:
  90. for ikey in targets:
  91. if isinstance(targets[ikey], list):
  92. new_targets.extend([{ikey: value} for value in targets[ikey]])
  93. else:
  94. new_targets.append({ikey: targets[ikey]})
  95. d[key + "s"] = new_targets
  96. key = key + "s"
  97. # Dig up the properties inside some specific target identifiers
  98. # if key in ("aggregated_pnode", "pnode", "service_delivery_point"):
  99. # d[key] = d[key]["node"]
  100. # if key in ("end_device_asset", "meter_asset"):
  101. # d[key] = d[key]["mrid"]
  102. # Group all reports as a list of dicts under the key "pending_reports"
  103. if key == "pending_reports":
  104. if isinstance(d[key], dict) and 'report_request_id' in d[key] and isinstance(d[key]['report_request_id'], list):
  105. d['pending_reports'] = [{'request_id': rrid} for rrid in d['pending_reports']['report_request_id']]
  106. # Group all events al a list of dicts under the key "events"
  107. elif key == "event" and isinstance(d[key], list):
  108. events = d.pop("event")
  109. new_events = []
  110. for event in events:
  111. new_event = event['event']
  112. new_event['response_required'] = event['response_required']
  113. new_events.append(new_event)
  114. d["events"] = new_events
  115. # If there's only one event, also put it into a list
  116. elif key == "event" and isinstance(d[key], dict) and "event" in d[key]:
  117. oadr_event = d.pop('event')
  118. ei_event = oadr_event['event']
  119. ei_event['response_required'] = oadr_event['response_required']
  120. d['events'] = [ei_event]
  121. elif key in ("request_event", "created_event") and isinstance(d[key], dict):
  122. d = d[key]
  123. # Plurarize some lists
  124. elif key in ('report_request', 'report'):
  125. if isinstance(d[key], list):
  126. d[key + 's'] = d.pop(key)
  127. else:
  128. d[key + 's'] = [d.pop(key)]
  129. elif key == 'report_description':
  130. if isinstance(d[key], list):
  131. original_descriptions = d.pop(key)
  132. report_descriptions = {}
  133. for item in original_descriptions:
  134. r_id = item.pop('r_id')
  135. report_descriptions[r_id] = item
  136. d[key + 's'] = report_descriptions
  137. else:
  138. original_description = d.pop(key)
  139. r_id = original_description.pop('r_id')
  140. d[key + 's'] = {r_id: original_description}
  141. # Promote the contents of the Qualified Event ID
  142. elif key == "qualified_event_id" and isinstance(d['qualified_event_id'], dict):
  143. qeid = d.pop('qualified_event_id')
  144. d['event_id'] = qeid['event_id']
  145. d['modification_number'] = qeid['modification_number']
  146. # Promote the contents of the tolerance items
  147. # if key == "tolerance" and "tolerate" in d["tolerance"] and len(d["tolerance"]["tolerate"]) == 1:
  148. # d["tolerance"] = d["tolerance"]["tolerate"].values()[0]
  149. # Durations are encapsulated in their own object, remove this nesting
  150. elif isinstance(d[key], dict) and "duration" in d[key] and len(d[key]) == 1:
  151. try:
  152. d[key] = d[key]["duration"]
  153. except:
  154. breakpoint()
  155. # In general, remove all double nesting
  156. elif isinstance(d[key], dict) and key in d[key] and len(d[key]) == 1:
  157. d[key] = d[key][key]
  158. # In general, remove the double nesting of lists of items
  159. elif isinstance(d[key], dict) and key[:-1] in d[key] and len(d[key]) == 1:
  160. if isinstance(d[key][key[:-1]], list):
  161. d[key] = d[key][key[:-1]]
  162. else:
  163. d[key] = [d[key][key[:-1]]]
  164. # Payload values are wrapped in an object according to their type. We don't need that information.
  165. elif key in ("signal_payload", "current_value"):
  166. value = d[key]
  167. if isinstance(d[key], dict):
  168. if 'payload_float' in d[key]:
  169. d[key] = float(d[key]['payload_float']['value'])
  170. elif 'payload_int' in d[key]:
  171. d[key] = int(d[key]['payload_int']['value'])
  172. # All values other than 'false' must be interpreted as True for testEvent (rule 006)
  173. elif key == 'test_event' and not isinstance(d[key], bool):
  174. d[key] = True
  175. # Promote the 'text' item
  176. elif isinstance(d[key], dict) and "text" in d[key] and len(d[key]) == 1:
  177. if key == 'uid':
  178. d[key] = int(d[key]["text"])
  179. else:
  180. d[key] = d[key]["text"]
  181. # Promote a 'date-time' item
  182. elif isinstance(d[key], dict) and "date_time" in d[key] and len(d[key]) == 1:
  183. d[key] = d[key]["date_time"]
  184. # Promote 'properties' item, discard the unused? 'components' item
  185. elif isinstance(d[key], dict) and "properties" in d[key] and len(d[key]) <= 2:
  186. d[key] = d[key]["properties"]
  187. # Remove all empty dicts
  188. elif isinstance(d[key], dict) and len(d[key]) == 0:
  189. d.pop(key)
  190. return d
  191. def parse_datetime(value):
  192. """
  193. Parse an ISO8601 datetime
  194. """
  195. matches = re.match(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.?(\d{1,6})?\d*Z', value)
  196. if matches:
  197. year, month, day, hour, minute, second, microsecond = (int(value) for value in matches.groups())
  198. return datetime(year, month, day, hour, minute, second, microsecond=microsecond, tzinfo=timezone.utc)
  199. else:
  200. print(f"{value} did not match format")
  201. return value
  202. def parse_duration(value):
  203. """
  204. Parse a RFC5545 duration.
  205. """
  206. # TODO: implement the full regex: matches = re.match(r'(\+|\-)?P((\d+Y)?(\d+M)?(\d+D)?T?(\d+H)?(\d+M)?(\d+S)?)|(\d+W)', value)
  207. if isinstance(value, timedelta):
  208. return value
  209. matches = re.match(r'P(\d+(?:D|W))?T(\d+H)?(\d+M)?(\d+S)?', value)
  210. if not matches:
  211. return False
  212. days = hours = minutes = seconds = 0
  213. _days, _hours, _minutes, _seconds = matches.groups()
  214. if _days:
  215. if _days.endswith("D"):
  216. days = int(_days[:-1])
  217. elif _days.endswith("W"):
  218. days = int(_days[:-1]) * 7
  219. if _hours:
  220. hours = int(_hours[:-1])
  221. if _minutes:
  222. minutes = int(_minutes[:-1])
  223. if _seconds:
  224. seconds = int(_seconds[:-1])
  225. return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  226. def parse_int(value):
  227. matches = re.match(r'^[\d-]+$', value)
  228. if not matches:
  229. return False
  230. else:
  231. return int(value)
  232. def parse_float(value):
  233. matches = re.match(r'^[\d.-]+$', value)
  234. if not matches:
  235. return False
  236. else:
  237. return float(value)
  238. def parse_boolean(value):
  239. if value == 'true':
  240. return True
  241. else:
  242. return False
  243. def peek(iterable):
  244. """
  245. Peek into an iterable.
  246. """
  247. try:
  248. first = next(iterable)
  249. except StopIteration:
  250. return None
  251. else:
  252. return itertools.chain([first], iterable)
  253. def datetimeformat(value, format=DATETIME_FORMAT):
  254. if not isinstance(value, datetime):
  255. return value
  256. return value.astimezone(timezone.utc).strftime(format)
  257. def timedeltaformat(value):
  258. """
  259. Format a timedelta to a RFC5545 Duration.
  260. """
  261. if not isinstance(value, timedelta):
  262. return value
  263. days = value.days
  264. hours, seconds = divmod(value.seconds, 3600)
  265. minutes, seconds = divmod(seconds, 60)
  266. formatted = "P"
  267. if days:
  268. formatted += f"{days}D"
  269. if hours or minutes or seconds:
  270. formatted += f"T"
  271. if hours:
  272. formatted += f"{hours}H"
  273. if minutes:
  274. formatted += f"{minutes}M"
  275. if seconds:
  276. formatted += f"{seconds}S"
  277. return formatted
  278. def booleanformat(value):
  279. """
  280. Format a boolean value
  281. """
  282. if isinstance(value, bool):
  283. if value == True:
  284. return "true"
  285. elif value == False:
  286. return "false"
  287. elif value in ("true", "false"):
  288. return value
  289. else:
  290. raise ValueError("A boolean value must be provided.")