utils.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683
  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 datetime import datetime, timedelta, timezone
  13. from dataclasses import is_dataclass, asdict
  14. from collections import OrderedDict
  15. from openleadr import enums, objects
  16. import asyncio
  17. import itertools
  18. import re
  19. import ssl
  20. import hashlib
  21. import uuid
  22. import logging
  23. logger = logging.getLogger('openleadr')
  24. DATETIME_FORMAT = "%Y-%m-%dT%H:%M:%S.%fZ"
  25. DATETIME_FORMAT_NO_MICROSECONDS = "%Y-%m-%dT%H:%M:%SZ"
  26. def generate_id(*args, **kwargs):
  27. """
  28. Generate a string that can be used as an identifier in OpenADR messages.
  29. """
  30. return str(uuid.uuid4())
  31. def indent_xml(message):
  32. """
  33. Indents the XML in a nice way.
  34. """
  35. INDENT_SIZE = 2
  36. lines = [line.strip() for line in message.split("\n") if line.strip() != ""]
  37. indent = 0
  38. for i, line in enumerate(lines):
  39. if i == 0:
  40. continue
  41. if re.search(r'^</[^>]+>$', line):
  42. indent = indent - INDENT_SIZE
  43. lines[i] = " " * indent + line
  44. if not (re.search(r'</[^>]+>$', line) or line.endswith("/>")):
  45. indent = indent + INDENT_SIZE
  46. return "\n".join(lines)
  47. def flatten_xml(message):
  48. """
  49. Flatten the entire XML structure.
  50. """
  51. lines = [line.strip() for line in message.split("\n") if line.strip() != ""]
  52. for line in lines:
  53. line = re.sub(r'\n', '', line)
  54. line = re.sub(r'\s\s+', ' ', line)
  55. return "".join(lines)
  56. def normalize_dict(ordered_dict):
  57. """
  58. Main conversion function for the output of xmltodict to the OpenLEADR
  59. representation of OpenADR contents.
  60. :param ordered_dict dict: The OrderedDict, dict or dataclass that you wish to convert.
  61. """
  62. if is_dataclass(ordered_dict):
  63. ordered_dict = asdict(ordered_dict)
  64. def normalize_key(key):
  65. if key.startswith('oadr'):
  66. key = key[4:]
  67. elif key.startswith('ei'):
  68. key = key[2:]
  69. # Don't normalize the measurement descriptions
  70. if key in enums._MEASUREMENT_NAMESPACES:
  71. return key
  72. key = re.sub(r'([a-z])([A-Z])', r'\1_\2', key)
  73. if '-' in key:
  74. key = key.replace('-', '_')
  75. return key.lower()
  76. d = {}
  77. for key, value in ordered_dict.items():
  78. # Interpret values from the dict
  79. if key.startswith("@"):
  80. continue
  81. key = normalize_key(key)
  82. if isinstance(value, (OrderedDict, dict)):
  83. d[key] = normalize_dict(value)
  84. elif isinstance(value, list):
  85. d[key] = []
  86. for item in value:
  87. if isinstance(item, (OrderedDict, dict)):
  88. dict_item = normalize_dict(item)
  89. d[key].append(normalize_dict(dict_item))
  90. else:
  91. d[key].append(item)
  92. elif key in ("duration", "startafter", "max_period", "min_period"):
  93. d[key] = parse_duration(value)
  94. elif ("date_time" in key or key == "dtstart") and isinstance(value, str):
  95. d[key] = parse_datetime(value)
  96. elif value in ('true', 'false'):
  97. d[key] = parse_boolean(value)
  98. elif isinstance(value, str):
  99. if re.match(r'^-?\d+$', value):
  100. d[key] = int(value)
  101. elif re.match(r'^-?[\d.]+$', value):
  102. d[key] = float(value)
  103. else:
  104. d[key] = value
  105. else:
  106. d[key] = value
  107. # Do our best to make the dictionary structure as pythonic as possible
  108. if key.startswith("x_ei_"):
  109. d[key[5:]] = d.pop(key)
  110. key = key[5:]
  111. # Group all targets as a list of dicts under the key "target"
  112. if key == 'target':
  113. targets = d.pop(key)
  114. new_targets = []
  115. if targets:
  116. for ikey in targets:
  117. if isinstance(targets[ikey], list):
  118. new_targets.extend([{ikey: value} for value in targets[ikey]])
  119. else:
  120. new_targets.append({ikey: targets[ikey]})
  121. d[key + "s"] = new_targets
  122. key = key + "s"
  123. # Also add a targets_by_type element to this dict
  124. # to access the targets in a more convenient way.
  125. d['targets_by_type'] = group_targets_by_type(new_targets)
  126. # Group all reports as a list of dicts under the key "pending_reports"
  127. if key == "pending_reports":
  128. if isinstance(d[key], dict) and 'report_request_id' in d[key] \
  129. and isinstance(d[key]['report_request_id'], list):
  130. d['pending_reports'] = [{'request_id': rrid}
  131. for rrid in d['pending_reports']['report_request_id']]
  132. # Group all events al a list of dicts under the key "events"
  133. elif key == "event" and isinstance(d[key], list):
  134. events = d.pop("event")
  135. new_events = []
  136. for event in events:
  137. new_event = event['event']
  138. new_event['response_required'] = event['response_required']
  139. new_events.append(new_event)
  140. d["events"] = new_events
  141. # If there's only one event, also put it into a list
  142. elif key == "event" and isinstance(d[key], dict) and "event" in d[key]:
  143. oadr_event = d.pop('event')
  144. ei_event = oadr_event['event']
  145. ei_event['response_required'] = oadr_event['response_required']
  146. d['events'] = [ei_event]
  147. elif key in ("request_event", "created_event") and isinstance(d[key], dict):
  148. d = d[key]
  149. # Plurarize some lists
  150. elif key in ('report_request', 'report', 'specifier_payload'):
  151. if isinstance(d[key], list):
  152. d[key + 's'] = d.pop(key)
  153. else:
  154. d[key + 's'] = [d.pop(key)]
  155. elif key in ('report_description', 'event_signal'):
  156. descriptions = d.pop(key)
  157. if not isinstance(descriptions, list):
  158. descriptions = [descriptions]
  159. for description in descriptions:
  160. # We want to make the identification of the measurement universal
  161. for measurement in enums._MEASUREMENT_NAMESPACES:
  162. if measurement in description:
  163. name, item = measurement, description.pop(measurement)
  164. break
  165. else:
  166. break
  167. item['description'] = item.pop('item_description', None)
  168. item['unit'] = item.pop('item_units', None)
  169. if 'si_scale_code' in item:
  170. item['scale'] = item.pop('si_scale_code')
  171. if 'pulse_factor' in item:
  172. item['pulse_factor'] = item.pop('pulse_factor')
  173. description['measurement'] = {'name': name,
  174. **item}
  175. d[key + 's'] = descriptions
  176. # Promote the contents of the Qualified Event ID
  177. elif key == "qualified_event_id" and isinstance(d['qualified_event_id'], dict):
  178. qeid = d.pop('qualified_event_id')
  179. d['event_id'] = qeid['event_id']
  180. d['modification_number'] = qeid['modification_number']
  181. # Durations are encapsulated in their own object, remove this nesting
  182. elif isinstance(d[key], dict) and "duration" in d[key] and len(d[key]) == 1:
  183. d[key] = d[key]["duration"]
  184. # In general, remove all double nesting
  185. elif isinstance(d[key], dict) and key in d[key] and len(d[key]) == 1:
  186. d[key] = d[key][key]
  187. # In general, remove the double nesting of lists of items
  188. elif isinstance(d[key], dict) and key[:-1] in d[key] and len(d[key]) == 1:
  189. if isinstance(d[key][key[:-1]], list):
  190. d[key] = d[key][key[:-1]]
  191. else:
  192. d[key] = [d[key][key[:-1]]]
  193. # Payload values are wrapped in an object according to their type. We don't need that.
  194. elif key in ("signal_payload", "current_value"):
  195. value = d[key]
  196. if isinstance(d[key], dict):
  197. if 'payload_float' in d[key] and 'value' in d[key]['payload_float'] \
  198. and d[key]['payload_float']['value'] is not None:
  199. d[key] = float(d[key]['payload_float']['value'])
  200. elif 'payload_int' in d[key] and 'value' in d[key]['payload_int'] \
  201. and d[key]['payload_int'] is not None:
  202. d[key] = int(d[key]['payload_int']['value'])
  203. # Report payloads contain an r_id and a type-wrapped payload_float
  204. elif key == 'report_payload':
  205. if 'payload_float' in d[key] and 'value' in d[key]['payload_float']:
  206. v = d[key].pop('payload_float')
  207. d[key]['value'] = float(v['value'])
  208. elif 'payload_int' in d[key] and 'value' in d[key]['payload_int']:
  209. v = d[key].pop('payload_float')
  210. d[key]['value'] = int(v['value'])
  211. # All values other than 'false' must be interpreted as True for testEvent (rule 006)
  212. elif key == 'test_event' and not isinstance(d[key], bool):
  213. d[key] = True
  214. # Promote the 'text' item
  215. elif isinstance(d[key], dict) and "text" in d[key] and len(d[key]) == 1:
  216. if key == 'uid':
  217. d[key] = int(d[key]["text"])
  218. else:
  219. d[key] = d[key]["text"]
  220. # Promote a 'date-time' item
  221. elif isinstance(d[key], dict) and "date_time" in d[key] and len(d[key]) == 1:
  222. d[key] = d[key]["date_time"]
  223. # Promote 'properties' item, discard the unused? 'components' item
  224. elif isinstance(d[key], dict) and "properties" in d[key] and len(d[key]) <= 2:
  225. d[key] = d[key]["properties"]
  226. # Remove all empty dicts
  227. elif isinstance(d[key], dict) and len(d[key]) == 0:
  228. d.pop(key)
  229. return d
  230. def parse_datetime(value):
  231. """
  232. Parse an ISO8601 datetime into a datetime.datetime object.
  233. """
  234. matches = re.match(r'(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})\.?(\d{1,6})?\d*Z', value)
  235. if matches:
  236. year, month, day, hour, minute, second, micro = (int(value) for value in matches.groups())
  237. return datetime(year, month, day, hour, minute, second, micro, tzinfo=timezone.utc)
  238. else:
  239. logger.warning(f"parse_datetime: {value} did not match format")
  240. return value
  241. def parse_duration(value):
  242. """
  243. Parse a RFC5545 duration.
  244. """
  245. # TODO: implement the full regex:
  246. # matches = re.match(r'(\+|\-)?P((\d+Y)?(\d+M)?(\d+D)?T?(\d+H)?(\d+M)?(\d+S)?)|(\d+W)', value)
  247. if isinstance(value, timedelta):
  248. return value
  249. matches = re.match(r'P(\d+(?:D|W))?T?(\d+H)?(\d+M)?(\d+S)?', value)
  250. if not matches:
  251. return False
  252. days = hours = minutes = seconds = 0
  253. _days, _hours, _minutes, _seconds = matches.groups()
  254. if _days:
  255. if _days.endswith("D"):
  256. days = int(_days[:-1])
  257. elif _days.endswith("W"):
  258. days = int(_days[:-1]) * 7
  259. if _hours:
  260. hours = int(_hours[:-1])
  261. if _minutes:
  262. minutes = int(_minutes[:-1])
  263. if _seconds:
  264. seconds = int(_seconds[:-1])
  265. return timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
  266. def parse_boolean(value):
  267. if value == 'true':
  268. return True
  269. else:
  270. return False
  271. def peek(iterable):
  272. """
  273. Peek into an iterable.
  274. """
  275. try:
  276. first = next(iterable)
  277. except StopIteration:
  278. return None
  279. else:
  280. return itertools.chain([first], iterable)
  281. def datetimeformat(value, format=DATETIME_FORMAT):
  282. """
  283. Format a given datetime as a UTC ISO3339 string.
  284. """
  285. if not isinstance(value, datetime):
  286. return value
  287. return value.astimezone(timezone.utc).strftime(format)
  288. def timedeltaformat(value):
  289. """
  290. Format a timedelta to a RFC5545 Duration.
  291. """
  292. if not isinstance(value, timedelta):
  293. return value
  294. days = value.days
  295. hours, seconds = divmod(value.seconds, 3600)
  296. minutes, seconds = divmod(seconds, 60)
  297. formatted = "P"
  298. if days:
  299. formatted += f"{days}D"
  300. if hours or minutes or seconds:
  301. formatted += "T"
  302. if hours:
  303. formatted += f"{hours}H"
  304. if minutes:
  305. formatted += f"{minutes}M"
  306. if seconds:
  307. formatted += f"{seconds}S"
  308. return formatted
  309. def booleanformat(value):
  310. """
  311. Format a boolean value
  312. """
  313. if isinstance(value, bool):
  314. if value is True:
  315. return "true"
  316. elif value is False:
  317. return "false"
  318. elif value in ("true", "false"):
  319. return value
  320. else:
  321. raise ValueError(f"A boolean value must be provided, not {value}.")
  322. def ensure_bytes(obj):
  323. """
  324. Converts a utf-8 str object to bytes.
  325. """
  326. if obj is None:
  327. return obj
  328. if isinstance(obj, bytes):
  329. return obj
  330. if isinstance(obj, str):
  331. return bytes(obj, 'utf-8')
  332. else:
  333. raise TypeError("Must be bytes or str")
  334. def ensure_str(obj):
  335. """
  336. Converts bytes to a utf-8 string.
  337. """
  338. if obj is None:
  339. return None
  340. if isinstance(obj, str):
  341. return obj
  342. if isinstance(obj, bytes):
  343. return obj.decode('utf-8')
  344. else:
  345. raise TypeError("Must be bytes or str")
  346. def certificate_fingerprint_from_der(der_bytes):
  347. hash = hashlib.sha256(der_bytes).digest().hex()
  348. return ":".join([hash[i-2:i].upper() for i in range(-20, 0, 2)])
  349. def certificate_fingerprint(certificate_str):
  350. """
  351. Calculate the fingerprint for the given certificate, as defined by OpenADR.
  352. """
  353. der_bytes = ssl.PEM_cert_to_DER_cert(ensure_str(certificate_str))
  354. return certificate_fingerprint_from_der(der_bytes)
  355. def extract_pem_cert(tree):
  356. """
  357. Extract a given X509 certificate inside an XML tree and return the standard
  358. form of a PEM-encoded certificate.
  359. :param tree lxml.etree: The tree that contains the X509 element. This is
  360. usually the KeyInfo element from the XMLDsig Signature
  361. part of the message.
  362. """
  363. cert = tree.find('.//{http://www.w3.org/2000/09/xmldsig#}X509Certificate').text
  364. return "-----BEGIN CERTIFICATE-----\n" + cert + "-----END CERTIFICATE-----\n"
  365. def find_by(dict_or_list, key, value, *args):
  366. """
  367. Find a dict inside a dict or list by key, value properties.
  368. """
  369. search_params = [(key, value)]
  370. if args:
  371. search_params += [(args[i], args[i+1]) for i in range(0, len(args), 2)]
  372. if isinstance(dict_or_list, dict):
  373. dict_or_list = dict_or_list.values()
  374. for item in dict_or_list:
  375. if not isinstance(item, dict):
  376. _item = item.__dict__
  377. else:
  378. _item = item
  379. for key, value in search_params:
  380. if isinstance(value, tuple):
  381. if _item[key] not in value:
  382. break
  383. else:
  384. if _item[key] != value:
  385. break
  386. else:
  387. return item
  388. else:
  389. return None
  390. def group_by(list_, key, pop_key=False):
  391. """
  392. Return a dict that groups values
  393. """
  394. grouped = {}
  395. key_path = key.split(".")
  396. for item in list_:
  397. value = item
  398. for key in key_path:
  399. value = value.get(key)
  400. if value not in grouped:
  401. grouped[value] = []
  402. grouped[value].append(item)
  403. return grouped
  404. def cron_config(interval, randomize_seconds=False):
  405. """
  406. Returns a dict with cron settings for the given interval
  407. """
  408. if interval < timedelta(minutes=1):
  409. second = f"*/{interval.seconds}"
  410. minute = "*"
  411. hour = "*"
  412. elif interval < timedelta(hours=1):
  413. second = "0"
  414. minute = f"*/{int(interval.total_seconds()/60)}"
  415. hour = "*"
  416. elif interval < timedelta(hours=24):
  417. second = "0"
  418. minute = "0"
  419. hour = f"*/{int(interval.total_seconds()/3600)}"
  420. else:
  421. second = "0"
  422. minute = "0"
  423. hour = "0"
  424. cron_config = {"second": second, "minute": minute, "hour": hour}
  425. if randomize_seconds:
  426. jitter = min(int(interval.total_seconds() / 10), 300)
  427. cron_config['jitter'] = jitter
  428. return cron_config
  429. def get_cert_fingerprint_from_request(request):
  430. ssl_object = request.transport.get_extra_info('ssl_object')
  431. if ssl_object:
  432. der_bytes = ssl_object.getpeercert(binary_form=True)
  433. if der_bytes:
  434. return certificate_fingerprint_from_der(der_bytes)
  435. def get_certificate_common_name(request):
  436. cert = request.transport.get_extra_info('peercert')
  437. if cert:
  438. subject = dict(x[0] for x in cert['subject'])
  439. return subject.get('commonName')
  440. def group_targets_by_type(list_of_targets):
  441. targets_by_type = {}
  442. for target in list_of_targets:
  443. for key, value in target.items():
  444. if value is None:
  445. continue
  446. if key not in targets_by_type:
  447. targets_by_type[key] = []
  448. targets_by_type[key].append(value)
  449. return targets_by_type
  450. def ungroup_targets_by_type(targets_by_type):
  451. ungrouped_targets = []
  452. for target_type, targets in targets_by_type.items():
  453. if isinstance(targets, list):
  454. for target in targets:
  455. ungrouped_targets.append({target_type: target})
  456. elif isinstance(targets, str):
  457. ungrouped_targets.append({target_type: targets})
  458. return ungrouped_targets
  459. def validate_report_measurement_dict(measurement):
  460. from openleadr.enums import _ACCEPTABLE_UNITS, _MEASUREMENT_DESCRIPTIONS
  461. if 'name' not in measurement \
  462. or 'description' not in measurement \
  463. or 'unit' not in measurement:
  464. raise ValueError("The measurement dict must contain the following keys: "
  465. "'name', 'description', 'unit'. Please correct this.")
  466. name = measurement['name']
  467. description = measurement['description']
  468. unit = measurement['unit']
  469. # Validate the item name and description match
  470. if name in _MEASUREMENT_DESCRIPTIONS:
  471. required_description = _MEASUREMENT_DESCRIPTIONS[name]
  472. if description != required_description:
  473. if description.lower() == required_description.lower():
  474. logger.warning(f"The description for the measurement with name {name} "
  475. f"was not in the correct case; you provided {description} but "
  476. f"it should be {required_description}. "
  477. "This was automatically corrected.")
  478. measurement['description'] = required_description
  479. else:
  480. raise ValueError(f"The measurement's description {description} "
  481. f"did not match the expected description for this type "
  482. f" ({required_description}). Please correct this, or use "
  483. "'customUnit' as the name.")
  484. if unit not in _ACCEPTABLE_UNITS[name]:
  485. raise ValueError(f"The unit {unit} is not acceptable for measurement {name}. Allowed "
  486. f"units are {_ACCEPTABLE_UNITS[name]}.")
  487. else:
  488. if name != 'customUnit':
  489. logger.warning(f"You provided a measurement with an unknown name {name}. "
  490. "This was corrected to 'customUnit'. Please correct this in your "
  491. "report definition.")
  492. measurement['report_description']['name'] = 'customUnit'
  493. if 'power' in name:
  494. if 'power_attributes' in measurement:
  495. power_attributes = measurement['power_attributes']
  496. if 'voltage' not in power_attributes \
  497. or 'ac' not in power_attributes \
  498. or 'hertz' not in power_attributes:
  499. raise ValueError("The power_attributes of the measurement must contain the "
  500. "following keys: 'voltage' (int), 'ac' (bool), 'hertz' (int).")
  501. else:
  502. raise ValueError("A 'power' related measurement must contain a "
  503. "'power_attributes' section that contains the following "
  504. "keys: 'voltage' (int), 'ac' (boolean), 'hertz' (int)")
  505. def get_active_period_from_intervals(intervals, as_dict=True):
  506. if is_dataclass(intervals[0]):
  507. intervals = [asdict(i) for i in intervals]
  508. period_start = min([i['dtstart'] for i in intervals])
  509. period_duration = max([i['dtstart'] + i['duration'] - period_start for i in intervals])
  510. if as_dict:
  511. return {'dtstart': period_start,
  512. 'duration': period_duration}
  513. else:
  514. from openleadr.objects import ActivePeriod
  515. return ActivePeriod(dtstart=period_start, duration=period_duration)
  516. def determine_event_status(active_period):
  517. if is_dataclass(active_period):
  518. active_period = asdict(active_period)
  519. now = datetime.now(timezone.utc)
  520. if active_period['dtstart'].tzinfo is None:
  521. active_period['dtstart'] = active_period['dtstart'].astimezone(timezone.utc)
  522. active_period_start = active_period['dtstart']
  523. active_period_end = active_period['dtstart'] + active_period['duration']
  524. if now >= active_period_end:
  525. return 'completed'
  526. if now >= active_period_start:
  527. return 'active'
  528. if active_period.get('ramp_up_duration') is not None:
  529. ramp_up_start = active_period_start - active_period['ramp_up_duration']
  530. if now >= ramp_up_start:
  531. return 'near'
  532. return 'far'
  533. async def delayed_call(func, delay):
  534. if isinstance(delay, timedelta):
  535. delay = delay.total_seconds()
  536. await asyncio.sleep(delay)
  537. if asyncio.iscoroutinefunction(func):
  538. await func()
  539. elif asyncio.iscoroutine(func):
  540. await func
  541. else:
  542. func()
  543. def hasmember(obj, member):
  544. """
  545. Check if a dict or dataclass has the given member
  546. """
  547. if is_dataclass(obj):
  548. if hasattr(obj, member):
  549. return True
  550. else:
  551. if member in obj:
  552. return True
  553. return False
  554. def getmember(obj, member):
  555. """
  556. Get a member from a dict or dataclass
  557. """
  558. if is_dataclass(obj):
  559. return getattr(obj, member)
  560. else:
  561. return obj[member]
  562. def setmember(obj, member, value):
  563. """
  564. Set a member of a dict of dataclass
  565. """
  566. if is_dataclass(obj):
  567. setattr(obj, member, value)
  568. else:
  569. obj[member] = value
  570. def get_next_event_from_deque(deque):
  571. unused_elements = []
  572. event = None
  573. for i in range(len(deque)):
  574. try:
  575. msg = deque.popleft()
  576. if isinstance(msg, objects.Event) or (isinstance(msg, dict) and 'event_descriptor' in msg):
  577. event = msg
  578. break
  579. else:
  580. unused_elements.append(msg)
  581. except IndexError:
  582. pass
  583. deque.extend(unused_elements)
  584. return event