tconnectsync 3.0.0__tar.gz → 3.0.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. {tconnectsync-3.0.0/tconnectsync.egg-info → tconnectsync-3.0.1}/PKG-INFO +31 -1
  2. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/README.md +30 -0
  3. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/setup.cfg +8 -1
  4. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/api/__init__.py +6 -2
  5. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/api/common.py +1 -1
  6. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/api/tandemsource.py +14 -2
  7. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/domain/tandemsource/event_class.py +1 -1
  8. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/domain/tandemsource/pump_settings.py +2 -2
  9. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/nightscout.py +20 -67
  10. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/parser/nightscout.py +17 -9
  11. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/secret.py +5 -0
  12. tconnectsync-3.0.1/tconnectsync/sync/tandemsource/autoupdate.py +297 -0
  13. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/cli_helpers.py +1 -1
  14. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process.py +16 -6
  15. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_alarm.py +15 -7
  16. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_basal.py +6 -3
  17. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_basal_resume.py +6 -3
  18. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_basal_suspension.py +6 -3
  19. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_bolus.py +3 -4
  20. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_cartridge.py +4 -5
  21. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_cgm_alert.py +11 -3
  22. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_cgm_reading.py +11 -12
  23. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_cgm_start_join_stop.py +23 -4
  24. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_device_status.py +1 -2
  25. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/process_user_mode.py +20 -13
  26. {tconnectsync-3.0.0 → tconnectsync-3.0.1/tconnectsync.egg-info}/PKG-INFO +31 -1
  27. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync.egg-info/SOURCES.txt +2 -0
  28. tconnectsync-3.0.1/tests/test_eu_region_integration.py +320 -0
  29. tconnectsync-3.0.1/tests/test_nightscout.py +68 -0
  30. tconnectsync-3.0.0/tconnectsync/sync/tandemsource/autoupdate.py +0 -185
  31. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/LICENSE.md +0 -0
  32. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/pyproject.toml +0 -0
  33. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/setup.py +0 -0
  34. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/__init__.py +0 -0
  35. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/__main__.py +0 -0
  36. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/check.py +0 -0
  37. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/domain/__init__.py +0 -0
  38. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/domain/tandemsource/__init__.py +0 -0
  39. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/__init__.py +0 -0
  40. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/build_events.py +0 -0
  41. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/events.py +0 -0
  42. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/generic.py +0 -0
  43. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/raw_event.py +0 -0
  44. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/static_dicts.py +0 -0
  45. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/transforms.py +0 -0
  46. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/eventparser/utils.py +0 -0
  47. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/features.py +0 -0
  48. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/parser/__init__.py +0 -0
  49. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/__init__.py +0 -0
  50. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/__init__.py +0 -0
  51. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/choose_device.py +0 -0
  52. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/helpers.py +0 -0
  53. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/heroku_helpers.py +0 -0
  54. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/sync/tandemsource/update_profiles.py +0 -0
  55. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/util/__init__.py +0 -0
  56. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/util/cli.py +0 -0
  57. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync/util/constants.py +0 -0
  58. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync.egg-info/dependency_links.txt +0 -0
  59. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync.egg-info/entry_points.txt +0 -0
  60. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync.egg-info/requires.txt +0 -0
  61. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tconnectsync.egg-info/top_level.txt +0 -0
  62. {tconnectsync-3.0.0 → tconnectsync-3.0.1}/tests/test_secret.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: tconnectsync
3
- Version: 3.0.0
3
+ Version: 3.0.1
4
4
  Summary: Syncs Tandem Source (formerly t:connect) insulin pump data to Nightscout for the t:slim X2 and Tandem Mobi
5
5
  Home-page: https://github.com/jwoglom/tconnectsync
6
6
  Author: James Woglom
@@ -414,6 +414,36 @@ An example `run.sh` if you built tconnectsync locally:
414
414
  docker run tconnectsync --auto-update
415
415
  ```
416
416
 
417
+ #### Tuning Auto-Update
418
+
419
+ These optional environment variables control how `--auto-update` polls and how
420
+ it behaves when things go wrong. The defaults are sensible; you generally only
421
+ need these if you are seeing too many (or too few) restarts.
422
+
423
+ | Variable | Default | What it does |
424
+ | --- | --- | --- |
425
+ | `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` | `300` | Poll interval when no better estimate is available. Also the ceiling for the retry backoff below. |
426
+ | `AUTOUPDATE_MAX_SLEEP_SECONDS` | `1500` | Upper bound on the adaptive poll interval, regardless of how rarely new data appears. |
427
+ | `AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS` | `60` | How long to wait when new data is overdue based on the pump's previous cadence. |
428
+ | `AUTOUPDATE_USE_FIXED_SLEEP` | `false` | Set true to always sleep `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` instead of adapting to the pump's observed upload cadence. |
429
+ | `AUTOUPDATE_API_FAILURE_MINUTES` | `45` | Exit with a non-zero code after this many minutes of unbroken API/network failure, so your container platform restarts tconnectsync and can alert you. Set `0` to never exit. |
430
+ | `AUTOUPDATE_NO_DATA_FAILURE_MINUTES` | `180` | Log an error if the pump has not reported new events for this long. Usually means the pump simply is not uploading. |
431
+ | `AUTOUPDATE_FAILURE_MINUTES` | `75` | Log an error if events are appearing but no data has synced successfully for this long. |
432
+ | `AUTOUPDATE_RESTART_ON_FAILURE` | `false` | Whether the two watchdogs above also exit non-zero. Independent of `AUTOUPDATE_API_FAILURE_MINUTES`. |
433
+ | `AUTOUPDATE_MAX_LOOP_INVOCATIONS` | `-1` | Stop after this many poll cycles. `-1` means run forever; mainly useful for testing. |
434
+
435
+ **On failures and restarts.** Transient errors (DNS blips, timeouts, HTTP 404/502/503
436
+ from Tandem) do not crash tconnectsync. It retries with a growing backoff — 30s,
437
+ 60s, 120s, 240s, then holding at `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` — and resets
438
+ as soon as a poll succeeds. Staying in-process matters: an exit discards the
439
+ cached credentials, so a restart loop means a fresh login on every attempt,
440
+ which risks tripping Tandem's rate limiting.
441
+
442
+ Only once the API has been failing continuously for `AUTOUPDATE_API_FAILURE_MINUTES`
443
+ does tconnectsync give up and exit, so that a genuine outage surfaces (roughly one
444
+ restart per hour) instead of disappearing into an endless quiet retry. Invalid
445
+ credentials are never retried — they exit immediately, since retrying cannot help.
446
+
417
447
  ### Running with Cron
418
448
 
419
449
  If you choose not to run tconnectsync with `--auto-update` continuously,
@@ -381,6 +381,36 @@ An example `run.sh` if you built tconnectsync locally:
381
381
  docker run tconnectsync --auto-update
382
382
  ```
383
383
 
384
+ #### Tuning Auto-Update
385
+
386
+ These optional environment variables control how `--auto-update` polls and how
387
+ it behaves when things go wrong. The defaults are sensible; you generally only
388
+ need these if you are seeing too many (or too few) restarts.
389
+
390
+ | Variable | Default | What it does |
391
+ | --- | --- | --- |
392
+ | `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` | `300` | Poll interval when no better estimate is available. Also the ceiling for the retry backoff below. |
393
+ | `AUTOUPDATE_MAX_SLEEP_SECONDS` | `1500` | Upper bound on the adaptive poll interval, regardless of how rarely new data appears. |
394
+ | `AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS` | `60` | How long to wait when new data is overdue based on the pump's previous cadence. |
395
+ | `AUTOUPDATE_USE_FIXED_SLEEP` | `false` | Set true to always sleep `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` instead of adapting to the pump's observed upload cadence. |
396
+ | `AUTOUPDATE_API_FAILURE_MINUTES` | `45` | Exit with a non-zero code after this many minutes of unbroken API/network failure, so your container platform restarts tconnectsync and can alert you. Set `0` to never exit. |
397
+ | `AUTOUPDATE_NO_DATA_FAILURE_MINUTES` | `180` | Log an error if the pump has not reported new events for this long. Usually means the pump simply is not uploading. |
398
+ | `AUTOUPDATE_FAILURE_MINUTES` | `75` | Log an error if events are appearing but no data has synced successfully for this long. |
399
+ | `AUTOUPDATE_RESTART_ON_FAILURE` | `false` | Whether the two watchdogs above also exit non-zero. Independent of `AUTOUPDATE_API_FAILURE_MINUTES`. |
400
+ | `AUTOUPDATE_MAX_LOOP_INVOCATIONS` | `-1` | Stop after this many poll cycles. `-1` means run forever; mainly useful for testing. |
401
+
402
+ **On failures and restarts.** Transient errors (DNS blips, timeouts, HTTP 404/502/503
403
+ from Tandem) do not crash tconnectsync. It retries with a growing backoff — 30s,
404
+ 60s, 120s, 240s, then holding at `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` — and resets
405
+ as soon as a poll succeeds. Staying in-process matters: an exit discards the
406
+ cached credentials, so a restart loop means a fresh login on every attempt,
407
+ which risks tripping Tandem's rate limiting.
408
+
409
+ Only once the API has been failing continuously for `AUTOUPDATE_API_FAILURE_MINUTES`
410
+ does tconnectsync give up and exit, so that a genuine outage surfaces (roughly one
411
+ restart per hour) instead of disappearing into an endless quiet retry. Invalid
412
+ credentials are never retried — they exit immediately, since retrying cannot help.
413
+
384
414
  ### Running with Cron
385
415
 
386
416
  If you choose not to run tconnectsync with `--auto-update` continuously,
@@ -1,6 +1,6 @@
1
1
  [metadata]
2
2
  name = tconnectsync
3
- version = 3.0.0
3
+ version = 3.0.1
4
4
  author = James Woglom
5
5
  author_email = j@wogloms.net
6
6
  description = Syncs Tandem Source (formerly t:connect) insulin pump data to Nightscout for the t:slim X2 and Tandem Mobi
@@ -48,6 +48,13 @@ exclude =
48
48
  console_scripts =
49
49
  tconnectsync = tconnectsync:main
50
50
 
51
+ [mypy]
52
+ files =
53
+ tconnectsync
54
+ follow_imports = silent
55
+ ignore_missing_imports = True
56
+ disable_error_code = import-untyped
57
+
51
58
  [egg_info]
52
59
  tag_build =
53
60
  tag_date = 0
@@ -1,6 +1,7 @@
1
1
  import logging
2
2
 
3
3
  from .tandemsource import TandemSourceApi
4
+ from .. import secret
4
5
 
5
6
  logger = logging.getLogger(__name__)
6
7
 
@@ -9,10 +10,13 @@ class TConnectApi:
9
10
  email = None
10
11
  password = None
11
12
 
12
- def __init__(self, email, password, region='US'):
13
+ def __init__(self, email, password, region=None):
13
14
  self.email = email
14
15
  self.password = password
15
- self.region = region
16
+ # A caller which does not pass a region (e.g. tconnectsync-heroku)
17
+ # must get the configured TCONNECT_REGION, not a hardcoded US
18
+ # default which would send EU accounts to the US endpoints (#152).
19
+ self.region = region or secret.TCONNECT_REGION
16
20
  self._tandemsource = None
17
21
 
18
22
  @property
@@ -112,7 +112,7 @@ def days_between(start, end) -> int:
112
112
  return diff.days
113
113
 
114
114
  # both inclusive
115
- def split_days_range(start_a, end_a, days: int = 5) -> List[Tuple[str, str]]:
115
+ def split_days_range(start_a, end_a, days: int = 5) -> List[Tuple[arrow.Arrow, arrow.Arrow]]:
116
116
  ranges = []
117
117
  start = arrow.get(start_a)
118
118
  end = arrow.get(end_a)
@@ -20,10 +20,12 @@ from requests_oidc.plugins import OSCachedPlugin
20
20
  from requests_oidc.utils import ServerDetails
21
21
  from requests_oauthlib import OAuth2Session
22
22
  from jwt.algorithms import RSAAlgorithm
23
+ from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
23
24
 
24
25
 
25
26
  from ..util import timeago, cap_length
26
27
  from .common import parse_ymd_date, base_headers, base_session, ApiException, ApiLoginException
28
+ from .. import secret
27
29
  from ..secret import CACHE_CREDENTIALS, CACHE_CREDENTIALS_PATH, TIMEZONE_NAME
28
30
  from ..eventparser.generic import Events
29
31
 
@@ -214,7 +216,13 @@ class TandemSourceApi:
214
216
  'AUTHORIZATION_ENDPOINT': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api/connect/authorize'
215
217
  }
216
218
 
217
- def __init__(self, email: str, password: str, region: str = 'US') -> None:
219
+ def __init__(self, email: str, password: str, region: Optional[str] = None) -> None:
220
+ # No region means "use the configured TCONNECT_REGION": a hardcoded
221
+ # US default would send EU accounts to the US endpoints (#152).
222
+ if not region:
223
+ region = secret.TCONNECT_REGION
224
+ if not region:
225
+ raise ValueError("No region configured. Set TCONNECT_REGION to 'US' or 'EU'.")
218
226
  self.region = region.upper()
219
227
  if self.region not in ['US', 'EU']:
220
228
  raise ValueError(f"Invalid region '{region}'. Must be 'US' or 'EU'.")
@@ -386,6 +394,10 @@ class TandemSourceApi:
386
394
  key = public_keys.get(kid)
387
395
  if not key:
388
396
  raise ApiException(0, 'Public key not found for JWT: %s' % kid)
397
+ # A JWKS endpoint publishes public keys; from_jwk() is typed as possibly
398
+ # returning a private key, so narrow it before passing to jwt.decode().
399
+ if not isinstance(key, RSAPublicKey):
400
+ raise ApiException(0, 'JWK is not an RSA public key for JWT: %s' % kid)
389
401
 
390
402
  audience = self.TDC_OIDC_CLIENT_ID
391
403
  issuer = self.TDC_OIDC_ISSUER
@@ -570,7 +582,7 @@ class TandemSourceApi:
570
582
  # Trigger automatic re-login, and try again once
571
583
  if e.status_code == 401:
572
584
  logger.info("Performing automatic re-login after HTTP 401 for TandemSourceApi")
573
- self.accessTokenExpiresAt = time.time()
585
+ self.accessTokenExpiresAt = arrow.get()
574
586
  self.login(self._email, self._password)
575
587
 
576
588
  return self.get(endpoint, query, tries=tries+1)
@@ -2,7 +2,7 @@ from enum import Enum
2
2
 
3
3
  from ...eventparser import events
4
4
 
5
- class EventClass(set, Enum):
5
+ class EventClass(set, Enum): # type: ignore[misc] # set/Enum both define __hash__; the combination works at runtime
6
6
  # LidBasalDelivery = every 5min entry
7
7
  # LidBasalRateChange = only when basal rate changes
8
8
  BASAL = {events.LidBasalDelivery} # , LidBasalRateChange
@@ -1,5 +1,5 @@
1
1
  from dataclasses import dataclass
2
- from dataclasses_json import dataclass_json
2
+ from dataclasses_json import dataclass_json, DataClassJsonMixin
3
3
  from typing import List
4
4
 
5
5
  # These dataclasses model the `settings.details` blob from the Tandem Source
@@ -52,6 +52,6 @@ class PumpCgmSettings:
52
52
 
53
53
  @dataclass_json
54
54
  @dataclass
55
- class PumpSettings:
55
+ class PumpSettings(DataClassJsonMixin):
56
56
  profiles: PumpProfiles
57
57
  cgmSettings: PumpCgmSettings
@@ -19,12 +19,14 @@ DateLike = Union[str, datetime.datetime, arrow.Arrow]
19
19
  def format_datetime(date: DateLike) -> str:
20
20
  return arrow.get(date).isoformat()
21
21
 
22
- def time_range(field_name: str, start_time: Optional[DateLike], end_time: Optional[DateLike], t_to_space: bool = False) -> str:
22
+ def time_range(field_name: str, start_time: Optional[DateLike], end_time: Optional[DateLike]) -> str:
23
23
  def fmt(date: DateLike) -> str:
24
24
  ret = format_datetime(date)
25
- if t_to_space:
26
- return ret.replace('T', ' ')
27
- return ret
25
+ # URL-encode so the '+' in offsets like '+02:00' is not decoded
26
+ # to a space by the server, which would mangle the ISO-8601 value.
27
+ # Upstream instead retries with 'T' replaced by a space (t_to_space);
28
+ # encoding the value fixes the cause, so that fallback is not carried.
29
+ return urllib.parse.quote(ret, safe='')
28
30
  arg = ''
29
31
  if start_time:
30
32
  arg += '&find[%s][$gte]=%s' % (field_name, fmt(start_time))
@@ -70,138 +72,89 @@ class NightscoutApi:
70
72
  raise ApiException(r.status_code, "Nightscout put %s response: %s" % (r.status_code, r.text))
71
73
 
72
74
  def last_uploaded_entry(self, eventType: str, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
73
- def internal(t_to_space: bool) -> Optional[dict]:
74
- dateFilter = time_range('created_at', time_start, time_end, t_to_space=t_to_space)
75
+ dateFilter = time_range('created_at', time_start, time_end)
76
+ try:
75
77
  latest = requests.get(urljoin(self.url, 'api/v1/treatments?count=1&find[enteredBy]=' + urllib.parse.quote(ENTERED_BY) + '&find[eventType]=' + urllib.parse.quote(eventType) + dateFilter + '&ts=' + str(time.time())), headers={
76
78
  'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
77
79
  }, verify=self.verify)
78
80
  if latest.status_code != 200:
79
- if 'as a valid ISO-8601 date' in latest.text:
80
- logger.warning("Nightscout last_uploaded_entry %s could not process ISO-8601 date: start=%s end=%s dateFilter=%s" % (eventType, time_start, time_end, dateFilter))
81
- return None
82
81
  raise ApiException(latest.status_code, "Nightscout last_uploaded_entry %s response: %s" % (latest.status_code, latest.text))
83
82
 
84
83
  j = latest.json()
85
84
  if j and len(j) > 0:
86
85
  return j[0]
87
86
  return None
88
- try:
89
- ret = None
90
- try:
91
- ret = internal(False)
92
- except ApiException as e:
93
- #logger.warning("last_uploaded_entry with no t_to_space: %s", e)
94
- ret = None
95
- if ret is None and (time_start or time_end):
96
- try:
97
- ret = internal(True)
98
- except ApiException as e:
99
- #logger.warning("last_uploaded_entry with t_to_space: %s", e)
100
- ret = None
101
- if ret is not None:
102
- logger.warning("last_uploaded_entry with eventType=%s time_start=%s time_end=%s only returned data when timestamps contained a space" % (eventType, time_start, time_end))
103
- return ret
104
87
  except requests.exceptions.ConnectionError as e:
105
88
  if self.ignore_conn_errors:
106
89
  logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
90
+ return None
107
91
  else:
108
92
  raise e
109
93
 
110
94
  def last_uploaded_bg_entry(self, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
111
- def internal(t_to_space: bool) -> Optional[dict]:
112
- dateFilter = time_range('dateString', time_start, time_end, t_to_space=t_to_space)
95
+ dateFilter = time_range('dateString', time_start, time_end)
96
+ try:
113
97
  latest = requests.get(urljoin(self.url, 'api/v1/entries.json?count=1&find[device]=' + urllib.parse.quote(ENTERED_BY) + dateFilter + '&ts=' + str(time.time())), headers={
114
98
  'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
115
99
  }, verify=self.verify)
116
100
  if latest.status_code != 200:
117
- if 'as a valid ISO-8601 date' in latest.text:
118
- logger.warning("Nightscout last_uploaded_bg_entry could not process ISO-8601 date: start=%s end=%s dateFilter=%s" % (time_start, time_end, dateFilter))
119
- return None
120
101
  raise ApiException(latest.status_code, "Nightscout last_uploaded_bg_entry %s response: %s" % (latest.status_code, latest.text))
121
102
 
122
103
  j = latest.json()
123
104
  if j and len(j) > 0:
124
105
  return j[0]
125
106
  return None
126
-
127
- try:
128
- ret = internal(False)
129
- if ret is None and (time_start or time_end):
130
- ret = internal(True)
131
- if ret is not None:
132
- logger.warning("last_uploaded_bg_entry with time_start=%s time_end=%s only returned data when timestamps contained a space" % (time_start, time_end))
133
-
134
- return ret
135
107
  except requests.exceptions.ConnectionError as e:
136
108
  if self.ignore_conn_errors:
137
109
  logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
110
+ return None
138
111
  else:
139
112
  raise e
140
113
 
141
114
  def last_uploaded_activity(self, activityType: str, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
142
- def internal(t_to_space: bool) -> Optional[dict]:
143
- dateFilter = time_range('created_at', time_start, time_end, t_to_space=t_to_space)
115
+ dateFilter = time_range('created_at', time_start, time_end)
116
+ try:
144
117
  latest = requests.get(urljoin(self.url, 'api/v1/activity?find[enteredBy]=' + urllib.parse.quote(ENTERED_BY) + '&find[activityType]=' + urllib.parse.quote(activityType) + dateFilter + '&ts=' + str(time.time())), headers={
145
118
  'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
146
119
  }, verify=self.verify)
147
120
  if latest.status_code != 200:
148
- if 'as a valid ISO-8601 date' in latest.text:
149
- logger.warning("Nightscout activity %s could not process ISO-8601 date: start=%s end=%s dateFilter=%s" % (activityType, time_start, time_end, dateFilter))
150
- return None
151
121
  raise ApiException(latest.status_code, "Nightscout activity %s response: %s" % (latest.status_code, latest.text))
152
122
 
153
123
  j = latest.json()
154
124
  if j and len(j) > 0:
155
125
  return j[0]
156
126
  return None
157
-
158
- try:
159
- ret = internal(False)
160
- if ret is None and (time_start or time_end):
161
- ret = internal(True)
162
- if ret is not None:
163
- logger.warning("last_uploaded_activity with activityType=%s time_start=%s time_end=%s only returned data when timestamps contained a space" % (activityType, time_start, time_end))
164
- return ret
165
127
  except requests.exceptions.ConnectionError as e:
166
128
  if self.ignore_conn_errors:
167
129
  logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
130
+ return None
168
131
  else:
169
132
  raise e
170
133
 
171
134
  def last_uploaded_devicestatus(self, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
172
- def internal(t_to_space: bool) -> Optional[dict]:
173
- dateFilter = time_range('created_at', time_start, time_end, t_to_space=t_to_space)
135
+ dateFilter = time_range('created_at', time_start, time_end)
136
+ try:
174
137
  latest = requests.get(urljoin(self.url, 'api/v1/devicestatus?find[device]=' + urllib.parse.quote(ENTERED_BY) + dateFilter + '&ts=' + str(time.time())), headers={
175
138
  'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
176
139
  }, verify=self.verify)
177
140
  if latest.status_code != 200:
178
- if 'as a valid ISO-8601 date' in latest.text:
179
- logger.warning("Nightscout devicestatus could not process ISO-8601 date: start=%s end=%s dateFilter=%s" % (time_start, time_end, dateFilter))
180
- return None
181
141
  raise ApiException(latest.status_code, "Nightscout devicestatus %s response: %s" % (latest.status_code, latest.text))
182
142
 
183
143
  j = latest.json()
184
144
  if j and len(j) > 0:
185
145
  return j[0]
186
146
  return None
187
-
188
- try:
189
- ret = internal(False)
190
- if ret is None and (time_start or time_end):
191
- ret = internal(True)
192
- if ret is not None:
193
- logger.warning("devicestatus time_start=%s time_end=%s only returned data when timestamps contained a space" % (time_start, time_end))
194
- return ret
195
147
  except requests.exceptions.ConnectionError as e:
196
148
  if self.ignore_conn_errors:
197
149
  logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
150
+ return None
198
151
  else:
199
152
  raise e
200
153
 
201
154
  """
202
155
  Returns general status information about the Nightscout server.
203
156
  """
204
- def api_status(self) -> dict:
157
+ def api_status(self):
205
158
  status = requests.get(urljoin(self.url, 'api/v1/status.json'), headers={
206
159
  'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
207
160
  }, verify=self.verify)
@@ -213,7 +166,7 @@ class NightscoutApi:
213
166
  Returns information on the currently configured Nightscout profile data store
214
167
  (contains all profiles in Nightscout under one mongo object).
215
168
  """
216
- def current_profile(self, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> dict:
169
+ def current_profile(self, time_start=None, time_end=None):
217
170
  r = requests.get(urljoin(self.url, 'api/v1/profile/current?api_secret=' + self.secret), json={}, headers={
218
171
  'Accept': 'application/json',
219
172
  'Content-Type': 'application/json',
@@ -215,32 +215,40 @@ class NightscoutEntry:
215
215
  return {
216
216
  # insulin duration in hours; Nightscout JS bug requires all top-level fields to be strings
217
217
  "dia": "%s" % (profile.insulinDuration / 60),
218
- "carbratio": list(sorted([
218
+ # Sort by the typed segment.startTime (monotonic with timeAsSeconds)
219
+ # so the sort key is a well-typed int rather than an untyped dict value.
220
+ "carbratio": [
219
221
  {
220
222
  "time": minutes_to_ns_time(segment.startTime),
221
223
  "timeAsSeconds": segment.startTime * 60,
222
224
  "value": segment.carbRatio / 1000 # milliunits->units
223
- } for segment in profile.tDependentSegs if not segment.skip
224
- ], key=lambda x: x["timeAsSeconds"])),
225
+ } for segment in sorted(
226
+ (s for s in profile.tDependentSegs if not s.skip),
227
+ key=lambda s: s.startTime)
228
+ ],
225
229
 
226
230
  "carbs_hr": NIGHTSCOUT_PROFILE_CARBS_HR_VALUE,
227
231
  "delay": NIGHTSCOUT_PROFILE_DELAY_VALUE,
228
232
 
229
- "sens": list(sorted([ # Correction factor / isf
233
+ "sens": [ # Correction factor / isf
230
234
  {
231
235
  "time": minutes_to_ns_time(segment.startTime),
232
236
  "timeAsSeconds": segment.startTime * 60,
233
237
  "value": segment.isf
234
- } for segment in profile.tDependentSegs if not segment.skip
235
- ], key=lambda x: x["timeAsSeconds"])),
238
+ } for segment in sorted(
239
+ (s for s in profile.tDependentSegs if not s.skip),
240
+ key=lambda s: s.startTime)
241
+ ],
236
242
 
237
- "basal": list(sorted([
243
+ "basal": [
238
244
  {
239
245
  "time": minutes_to_ns_time(segment.startTime),
240
246
  "timeAsSeconds": segment.startTime * 60,
241
247
  "value": segment.basalRate / 1000 # milliunits->units
242
- } for segment in profile.tDependentSegs
243
- ], key=lambda x: x["timeAsSeconds"])),
248
+ } for segment in sorted(
249
+ profile.tDependentSegs,
250
+ key=lambda s: s.startTime)
251
+ ],
244
252
 
245
253
  "target_low": [
246
254
  {
@@ -73,6 +73,11 @@ AUTOUPDATE_USE_FIXED_SLEEP = get_bool('AUTOUPDATE_USE_FIXED_SLEEP', 'false')
73
73
  AUTOUPDATE_NO_DATA_FAILURE_MINUTES = get_number('AUTOUPDATE_NO_DATA_FAILURE_MINUTES', '180') # 3 hours
74
74
  AUTOUPDATE_FAILURE_MINUTES = get_number('AUTOUPDATE_FAILURE_MINUTES', '75') # 75 minutes
75
75
  AUTOUPDATE_RESTART_ON_FAILURE = get_bool('AUTOUPDATE_RESTART_ON_FAILURE', 'false')
76
+ # Give up and exit non-zero after this many minutes of unbroken API/network
77
+ # failure, so the container platform notices (and, if configured, notifies).
78
+ # Distinct from AUTOUPDATE_RESTART_ON_FAILURE, which covers the pump not
79
+ # uploading -- a case where restarting achieves nothing. Set 0 to never exit.
80
+ AUTOUPDATE_API_FAILURE_MINUTES = get_number('AUTOUPDATE_API_FAILURE_MINUTES', '45') # 45 minutes
76
81
  AUTOUPDATE_MAX_LOOP_INVOCATIONS = get_number('AUTOUPDATE_MAX_LOOP_INVOCATIONS', '-1')
77
82
 
78
83
  NIGHTSCOUT_PROFILE_UPLOAD_MODE = get_one_of('NIGHTSCOUT_PROFILE_UPLOAD_MODE', 'add', ['add', 'replace'])