Compare commits

...
331 Commits
Author SHA1 Message Date
ClaudeandJames Woglom 67731f23ff Name known alert ids in place of placeholders
Rename ALERTS_DICT id 49 from DEFAULT_ALERT_49 to
FILL_TUBING_STILL_IN_PROGRESS, matching pumpX2's AlertResponseType id
49. Regenerate the autogenerated eventparser/events.py via
build_events.py so the embedded AlertidMap/enum stays in sync.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01P93H2Avp5zLLg61TzR1ocm
2026-08-16 12:00:18 -04:00
ClaudeandJames Woglom 2b8d8ebaf8 Drop the percent-vs-voltage invariant; cover the charging phase
test_observed_charge_percent_tracks_voltage asserted that batteryChargePercent
is non-decreasing in batteryLipoMilliVolts. That holds across OBSERVED_EVENTS
only because every one of those captures is a resting/discharge sample.
Charging lifts terminal voltage well above the resting SoC curve, so a
charging sample can read a higher voltage at a lower SoC; the invariant fails
15 times in a 452-record capture from a second pump, worst case 3841 mV -> 27%
against 3840 mV -> 57%. It was a false alarm on a correct decoder, and the
per-record equality assertions already pin field alignment. Remove it.

Add RESERIALIZED_BLE_EVENTS, six records from that capture converted into
Source byte order, asserted the same way. They are kept in their own table
rather than merged into OBSERVED_EVENTS, which is Source-captured throughout.
They cover what the Source captures do not: the charging phase, the 3928 mV /
48% sample that disproves the invariant, and finalEventForDay set.

Also soften the finalEventForDay claims. Both day rollovers in that capture
are preceded by final=1, but so is one mid-afternoon record a second before
LID_PUMPING_RESUMED ended an alarm suspension, with no reset following. It
reads as a close-out marker whose usual but not only trigger is the rollover
-- not enough to pin the semantics, so pumpX2's TODO(confirm) stays open.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YN9Y6PAaXaXwueiiDvt7zi
2026-08-13 19:45:57 -04:00
ClaudeandJames Woglom da58c6fc81 Drop redundant comments from the device status tests
The test names and assertions already say what these checked; only the
capture labels and the note on how to read them stay.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YN9Y6PAaXaXwueiiDvt7zi
2026-08-13 19:45:57 -04:00
ClaudeandJames Woglom 196ffc2cfb Keep the original "Mobi @ ~XX%" capture labels as comments
Carry the collection-time battery annotations on the table entries in their
original wording rather than folding them into a dict key.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YN9Y6PAaXaXwueiiDvt7zi
2026-08-13 19:45:57 -04:00
ClaudeandJames Woglom 2753b4da20 Parse every observed event 81 capture in the device status tests
The captures collected from real pumps were sitting in a trailing comment
block, annotated under the old (wrong) field layout, with only some of them
reachable from a skipped test. Promote all 13 to an OBSERVED_EVENTS table and
assert the full decode of each -- seqNum, timestamp, the three float32s and
the three battery fields -- so a bad offset anywhere in the record fails
loudly rather than only where a battery assertion happens to look.

The table also carries the battery level each capture was originally
annotated with. Where that disagrees with the pump's own SoC byte the byte
wins; the labels look like estimates, and their relative ordering agrees with
the decoded values.

Also asserts across the whole set that the SoC byte stays in 0-100, the
voltage stays in 1S LiPo range, and that percent is non-decreasing in
voltage -- corroboration that the two fields are aligned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YN9Y6PAaXaXwueiiDvt7zi
2026-08-13 19:45:57 -04:00
ClaudeandJames Woglom 97ad0e7629 Fix LID_DAILY_BASAL trailing field offsets
Event 81's last 4 bytes are a single packed uint32:

    (batteryLipoMilliVolts << 16) | (batteryChargePercent << 8) | finalEventForDay

Tandem Source serializes scalars big-endian, so on the wire those bytes land
as [lipo_hi, lipo_lo, percent, final] at absolute offsets 22-25. The schema
instead used the offsets from pumpX2's Java/Swift ports, which decode the same
u32 out of a little-endian BLE stream — correct there, misaligned here. The
result was that every field after iob was wrong: the existing test fixture
decoded to 14080 mV, an impossible voltage for a 1S LiPo.

Re-key the schema to lipo@12 (uint16), percent@14, final@15 (relative offsets)
and regenerate events.py. The same fixture now yields 3830 mV / 55% / 0, and
the one previously annotated "Mobi @ MAX seen" yields 4176 mV / 100% with
finalEventForDay set, at 23:58 pump-local.

batteryChargePercent is now the pump's own state-of-charge byte rather than
(mV - 3584)/768, the linear voltage->SoC approximation the removed
battery_charge_percent transform applied to the two millivolt bytes. It is
already scaled 0-100, so the sync layer drops its *100 factor.

finalEventForDay is decoded but deliberately unused; nothing in the sync layer
acts on it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YN9Y6PAaXaXwueiiDvt7zi
2026-08-13 19:45:57 -04:00
James Woglom 7c4b2f4ddb v3.0.1 2026-07-21 01:32:09 -04:00
ClaudeandJames Woglom 74576bbb51 Make full-package mypy pass on the Python 3.8 CI (older mypy)
The Python 3.8 CI job installs an older mypy that behaves differently from
newer releases, surfacing two things the newer local mypy did not:

- requests (and other stub-less deps) raise `import-untyped`, which older
  mypy does not silence via ignore_missing_imports. Add
  `disable_error_code = import-untyped` so stub-less third-party libs are
  treated as untyped rather than failing the run.
- TandemSourceApi.__init__: older mypy infers secret.TCONNECT_REGION as
  Optional[str], so region.upper() tripped union-attr. Guard against an
  unset region (also avoids an AttributeError at runtime) which narrows it
  to str.

Verified with both mypy 1.19.1 and 2.3.0; tests still green (461 passed).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaQXTakxAKEfeeys5cv3en
2026-07-21 00:58:41 -04:00
ClaudeandJames Woglom 272a329664 Type-check the full tconnectsync package, not just process_alarm
Remove the single-file opt-in in setup.cfg ([mypy] files) so mypy checks
the entire tconnectsync package, and fix everything that surfaced.

Config:
- setup.cfg: mypy `files` now points at the whole `tconnectsync` package.

Event processors (were typed as BaseEvent, which lacks the per-event fields
like seqNum and the event-specific attributes):
- Type each *_to_nsentry / helper with the concrete event type(s) it handles
  (or a Union of them), matching the existing process_alarm.py pattern.
- process_basal_suspension, process_basal_resume, process_cgm_start_join_stop:
  filter out None before appending to ns_entries, matching process_basal /
  process_cgm_alert. Previously a None from a non-matching event would have
  been appended and passed to upload_entry().
- Add explicit `return None` fall-throughs where a helper annotated to return
  a value could implicitly return None.
- process_cgm_reading: give each sensor's GlucosevaluestatusEnum its own local
  variable so the enum types don't clash.

process.py:
- Add an EventProcessor Protocol and annotate event_classes with it, so the
  instantiated handlers are typed instead of `object`.
- Rename the updater-loop variable so it no longer collides with the
  processor-loop variable's type.

Other:
- api/tandemsource.py: narrow the JWKS key to RSAPublicKey before jwt.decode,
  and use arrow.get() (not time.time()) when forcing token expiry so the
  attribute type stays consistent.
- api/common.py: split_days_range returns Arrow tuples, not str tuples.
- parser/nightscout.py: sort profile segments by the typed startTime rather
  than an untyped dict value (same resulting order).
- domain/tandemsource/pump_settings.py: PumpSettings inherits DataClassJsonMixin
  so from_dict is visible to the type checker.
- domain/tandemsource/event_class.py: ignore the set/Enum __hash__ clash.
- nightscout.py: explicit return None when a ConnectionError is swallowed.

No runtime behavior change; full test suite (461 passed, 1 skipped) still green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UaQXTakxAKEfeeys5cv3en
2026-07-21 00:58:41 -04:00
xannasavinandJames Woglom 758204d4de URL-encode Nightscout date filters instead of retrying with a mangled timestamp
arrow's isoformat() ends a timestamp with its UTC offset, e.g.
'2026-07-16T00:00:00+02:00'. Placed raw into a query string, '+' is a
reserved character that servers decode as a space, so Nightscout receives
'2026-07-16T00:00:00 02:00' and answers 'could not parse as a valid ISO-8601
date'. Any user on a positive UTC offset hits this on every date-filtered
query.

The current workaround retries the request with 'T' replaced by a space
(t_to_space) and treats a failure as 'no previous entry'. That gets a
response, but it works around the symptom: the value is still mangled, every
affected query costs two round-trips, and a genuinely empty result is
indistinguishable from a rejected one.

Percent-encoding the value fixes the cause: the offset survives, the first
request succeeds, and the t_to_space fallback and its retry wrapper are no
longer needed and are removed.

Adds tests for time_range(): that a positive offset is encoded rather than
emitted raw, that the encoded value round-trips back to the original instant,
that negative offsets and 'Z' still parse, and the bounds/no-bounds cases.
There was no coverage of time_range() before. The encoding test fails on
master with '+' present in the query and passes with this change.

Running with this in my EU deployment since May.
2026-07-20 20:50:13 -04:00
ClaudeandJames Woglom ddeaa79ded Fix #156: handle LidMalfunctionActivated in ProcessAlarm; add typed guardrail
ProcessAlarm.skip_event() read event.alarmId on every EventClass.ALARM event,
but LidMalfunctionActivated (a sibling of LidAlarmActivated in that class) has
no alarmId, so a malfunction alarm crashed the sync with AttributeError.

- Narrow with isinstance before reading alarmId; malfunction events now upload
  as "Malfunction" as intended, and sync continues.
- Type the alarm handlers against an explicit AlarmEvent union and add an
  assert_never exhaustiveness guard, so a type checker rejects unguarded
  subtype attribute access and flags any newly added ALARM event type.
- Fix a latent None-leak: alarm_to_nsentry now always returns a dict.
- Add mypy as a gradual-typing beachhead (setup.cfg [mypy], CI step, Pipfile
  typecheck script), scoped to process_alarm.py. This configuration fails on
  exactly the #156 class of bug.
- Add regression tests: malfunction processing, mixed alarm batches, the event
  shape, and an AlarmEvent/EventClass.ALARM sync guard.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LpMTd5LzkqFLZTUKd3H8em
2026-07-20 20:49:43 -04:00
James WoglomandClaude Opus 4.8 c95fe424ab Fix flaky autoupdate tests: use constant mocked clock
Patching autoupdate.time.time patches the global time.time, which
logging calls internally per record; a finite side_effect list gets
exhausted and raises StopIteration on Python 3.11. Use return_value.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 20:46:23 -04:00
James Woglom 4bae860212 tests/sync/tandemsource/test_autoupdate.py 2026-07-20 20:40:02 -04:00
xannasavinandJames Woglom 823bb785ba Harden autoupdate against transient errors instead of exiting
get() retries only HTTP 401 and 500, so any other API error propagates out of
the autoupdate loop and exits the process. When Tandem retired the
reportsfacade endpoints and pumpeventmetadata began returning 404 (#146), a
container with a restart policy would crash-loop. That is the worst possible
response to an API outage: the credentials cache dies with the process, so
every restart performs a full login against sso.tandemdiabetes.com. In my EU
deployment that was a fresh login roughly every two minutes for hours from a
single IP, which seems a good way to earn a WAF ban while already broken.

Transient network errors (DNS failures, timeouts, mid-stream disconnects,
urllib3 retry-budget exhaustion) have the same problem.

This keeps both failure families inside the loop and backs off exponentially:
30s doubling to a cap of AUTOUPDATE_DEFAULT_SLEEP_SECONDS (300s default),
reset on any successful poll. The cap reuses the existing poll interval, so a
failing API is never contacted more often than a healthy one. After three
consecutive failures the log escalates from WARNING to ERROR.

Staying alive forever would make a real outage silent on deployments whose
only alarm is the container dying, so after AUTOUPDATE_API_FAILURE_MINUTES
(default 45) of unbroken failure the process gives up and exits non-zero.
That is roughly one restart per hour during a genuine outage instead of one
every two minutes, while short blips stay silent. Set 0 to disable.

This is deliberately not gated on AUTOUPDATE_RESTART_ON_FAILURE, which covers
the pump-not-uploading watchdog where restarting achieves nothing (as the
existing TODO notes) and which many users therefore disable. An unreachable
API is a different failure and gets its own knob.

ApiLoginException stays fatal: bad credentials are not transient, and
retrying them in-process would hammer the login endpoint with attempts that
cannot succeed.

Also included:

- A defensive clamp so a negative rolling-average entry can never reach
  time.sleep() and crash with ValueError.
- Tests covering the backoff sequence, reset-on-success, the sustained-failure
  exit, the opt-out, and that login failures and programming errors still
  propagate.
- README documentation for all nine AUTOUPDATE_* variables, none of which were
  documented outside secret.py.
2026-07-20 19:12:24 -04:00
ClaudeandJames Woglom 984487da44 Trim over-explanatory comments in EU integration tests
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012DEvvZSWHo2dki5h1HikUU
2026-07-17 19:13:07 -04:00
ClaudeandJames Woglom 4655e31561 Fix hardcoded US region default; add EU region integration tests (#152)
TConnectApi and TandemSourceApi defaulted their region parameter to a
hardcoded 'US', so callers that construct them without an explicit
region (e.g. tconnectsync-heroku's check_login path) sent EU accounts
to the US login endpoint, which rejected them with HTTP 401
account/invalid_credentials even when TCONNECT_REGION=EU was set.

Both classes (and fetch_oneshot) now fall back to the configured
TCONNECT_REGION when no region argument is given, so downstream
consumers honor the .env/environment configuration.

Adds top-level integration tests that configure the EU region via each
supported mechanism (TCONNECT_REGION environment variable, .env file,
and --region CLI flag) and drive the real downstream code -- including
the full main(['--check-login']) entrypoint -- against a mocked HTTP
layer with a real RS256-signed OIDC id_token. Only the EU endpoints are
registered, and the tests assert the EU login/token/jwks/pumper/
pump-logs endpoints are actually invoked and that no US host is ever
contacted.

Fixes #152

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012DEvvZSWHo2dki5h1HikUU
2026-07-17 19:13:07 -04:00
James Woglom 7f88d88ea4 Fix PyPI publish workflow: use setup-python@v5 with Python 3.11
setup-python@v1 could not find Python 3.9 on current GitHub runners.
Bump checkout to v4 and pin an available Python version.
2026-07-01 07:26:32 +00:00
James Woglom afbc99010c v3.0.0 - uses new Tandem Source APIs 2026-07-01 07:16:51 +00:00
James Woglom 6f987989b8 Add real-data unit tests for cartridge, basal, basal suspend/resume, and CGM alert handlers
One test file per handler, built from real captured pump-log events (verbatim,
deviceAssignmentId redacted) embedded inline. Assert exact Nightscout output:
- cartridge: site-change reason strings (insulinVolume fill, -1 tubing sentinel, %.1f cannula)
- basal: rate scaling, commandedRateSource reason, inter-event + capped durations (locks total_seconds), zero-rate suspend
- basal suspension/resume: exact treatments + dedup
- cgm alert: Dexcom-prefixed dalertId names, out-of-range + unmapped skips, cleared/ack not synced
2026-07-01 07:15:58 +00:00
James Woglom 1500438c1b Add end-to-end integration tests for the Tandem Source -> Nightscout flow
Drive the real ProcessTimeRange + process_* handlers and the real
TandemSourceApi / NightscoutApi clients, mocking only the HTTP transport
(base_session / requests). Tandem responses are a small representative slice of
real captured pump-log events (verbatim, deviceAssignmentId redacted); tests
assert the exact Nightscout operations produced: full multi-type sync, api-secret
header, resume-alarm skip, dedup, pretend mode, and empty window.
2026-07-01 07:09:43 +00:00
James Woglom ee7384cc31 Sync events.json to upstream schema; preserve camelCase attribute names
Copy the exact eventSchema.json to events.json (camelCase keys) and fix
build_events.py's fieldNameFormat to preserve camelCase instead of collapsing
it via .title() (which turned schema keys like commandedRate into commandedrate).
Regenerate events.py so attributes are clean camelCase (commandedRate,
currentGlucoseDisplayValue, egvTimeStamp, bolusId, ...); acronyms follow the
schema's own casing (bg, iob, rssi). Update the battery transform and all
attribute references in the process handlers and tests to match.
2026-07-01 06:50:30 +00:00
James Woglom e5304dc605 Add G6 JSON-path tests to ProcessCGMReading from real early-2023 data
Real Dexcom G6 (LidCgmDataGxb, eventCode 256) pump-logs JSON readings captured
from a live t:slim X2 account, exercising the production Events -> ProcessCGMReading
path (the existing G6 coverage used only the binary decoder). Covers steady/rising/
falling/high readings plus a SpecialLow (raw display 0 -> LOW sentinel 39).
2026-07-01 06:27:57 +00:00
James Woglom cb045796e5 Add ProcessBolus tests from real captured pump-log data
Covers regular, extended (combo), and canceled boluses using complete event
groups captured verbatim from the live Tandem Source API (all messages of each
bolusId; deviceAssignmentId redacted), embedded inline as test class variables.
2026-07-01 06:22:06 +00:00
James Woglom ef87d18469 Fix event-processing correctness bugs found during test audit
- process_basal / process_user_mode: use timedelta.total_seconds() instead of
  .seconds so durations spanning >=24h (and negative deltas) are correct.
- process_cartridge: report cartridge fill from insulinVolume (v2Volume is 0 on
  real pumps); treat tubing primeSize -1 as 'not recorded'; format cannula
  primeSize with %.1f instead of %d.
- process_bolus: no longer drop the extended portion of a combo bolus. The
  initial portion is emitted as before; the extended portion (LidBolexCompleted)
  is added as a separate treatment at its completion time.
- check.py: return after a config ImportError instead of falling through to an
  unbound-name NameError.
2026-07-01 06:22:00 +00:00
James Woglom 9d8ab283a0 Add per-event-type parser tests from real captured pump-log data
One test file per event type observed in captured Tandem Source
pump-logs responses (30 types), each asserting parse/dispatch,
field round-trip, and enum/bitmask/ratio resolution against real
capture fixtures.
2026-07-01 05:26:46 +00:00
James Woglom a28e0f1ee0 Add pump_clock_changes() to fetch parsed clock-change events
Mirrors pump_events(): pages get_pump_logs across date windows and dedupes
clockChanges (LID_TIME_CHANGED/LID_DATE_CHANGED, codes 13/14) by
(sequenceGroup, sequenceNumber), returning them parsed via Events().
2026-07-01 04:40:53 +00:00
James Woglom ddca912eea Remove PumpMetadata transform; callers use raw BffPump, normalize at call sites
Delete the PumpMetadata TypedDict, _bff_pump_to_metadata and pump_metadata
transform layer. Callers now consume the raw BffPump dicts from get_pumper()
directly. The pump-local -> UTC date conversion is kept as a shared
naive_local_to_utc() helper, applied only at the call sites that compare a
pump date against real UTC (choose_device staleness/selection, autoupdate
timing).

Also expand pump_events JSON parse coverage: drive bolus (20), basal (279),
CGM (399) and alarm (5) events through pump_events(), asserting decoded
fields and enum members (previously only eventCode 16 was covered).
2026-07-01 04:22:57 +00:00
James Woglom 46a5a28baf Normalize BFF pump dates to UTC and fix BffPump optional-field typing
maxDateOfEvents and availableDataRange.start are pump-local naive
wall-clock strings, but consumers parse them with arrow.get() (assumes
UTC) and compare against arrow.utcnow()/time.time(). Normalize both to
true UTC at the adapter boundary via _naive_local_to_utc (interpreting
the naive value in TIMEZONE_NAME), fixing the off-by-offset staleness
warning and update-timing telemetry.

Split BffPump into a required base plus a total=False extension so the
always-present fields are typed required, and read algorithm (canonically
optional) via .get() to avoid a KeyError.
2026-07-01 03:39:07 +00:00
James Woglom b7375d11da Test get() 401 re-login and 500 retry paths 2026-07-01 03:05:36 +00:00
James Woglom 6030022476 Pass CGM glucose status enum members as keyword args 2026-07-01 03:04:10 +00:00
James Woglom a977bd65f9 Report CGM out-of-range readings as LOW/HIGH sentinels
The bff pump-logs endpoint gives glucoseValueStatus + a raw display value; a
below/above-range reading (e.g. status SpecialLow with displayValue 38) is a
boundary indicator, not a measurement. Mirror the Tandem Source frontend
(CgmBuilder.determineGlucoseValue): map SpecialLow/precise<40 -> 39 and
SpecialHigh/precise>400 -> 401. Each sensor (G7/G6/FSL2/FSL3) is resolved
against its own glucoseValueStatus enum members rather than assuming the enums
are consistent across sensor types.

Also widen the real-JSON CGM tests to span glucose 38..361 (incl. the LOW
sentinel) and add a ProcessTimeRange basal JSON integration test.
2026-07-01 03:03:26 +00:00
James Woglom 69637015e2 Fold pump-logs JSON handling into Event()/Events()
Event(x) and Events(x) now accept either a raw binary event/stream or a
pump-logs JSON event dict / iterable of dicts, dispatching on input type,
replacing the separate Event_from_json/Events_from_json functions. Point
pump_events() and all tests at the unified entry points, and add real-JSON
sync tests for CGM readings, user-mode sleep/exercise, and alarms alongside
the existing binary-fixture tests.
2026-07-01 02:52:16 +00:00
James Woglom d1d67b5042 Add real-JSON CGM reading tests via the production path
Exercise Events_from_json -> ProcessCGMReading with real LID_CGM_DATA_G7
pump-logs events captured from a live account (device id redacted), asserting
sgv, egv-derived dateString, pump_event_id, and last-upload skip behavior.
The existing binary-fixture tests are kept alongside.
2026-07-01 02:45:18 +00:00
James Woglom 7516226bd3 Verify UpdateProfiles builds Nightscout profiles from the new settings
UpdateProfiles already sources settings.details via pump_metadata(); add
end-to-end compare_profiles tests over a real-shape PumpSettings confirming
the per-segment basal/carbratio/sens schedule, flat-cgm target_low/high, and
defaultProfile are translated correctly, and that a matching Nightscout
profile yields no change.
2026-07-01 02:40:04 +00:00
James Woglom 1b89a4ba4d Parse the new bff/pumper settings.details schema in PumpSettings
The settings.details blob differs from the old lastUpload.settings: profile
segments live under timeDependentSegments (was tDependentSegs), cgmSettings
is flat (highGlucoseAlertMgPerDl/lowGlucoseAlertMgPerDl, not nested per-alert
objects), and carbEntry is a string enum. Rework the dataclasses to the new
shape (verified against live t:slim X2 and Mobi accounts), keep a
tDependentSegs alias for segment consumers, and point tandemsource_profile_store
at the flat cgm fields. Values remain milliunit-scaled, so the NS translation
math is unchanged.
2026-07-01 02:39:12 +00:00
James Woglom 02e3910928 Document that the new API drops DEVICE_STATUS and ignores eventIds
Live probes against t:slim X2 and Mobi accounts confirm the pump-logs
endpoint never returns event 81 (LID_DAILY_BASAL) and no returned event
carries battery data, so DEVICE_STATUS yields nothing on the new API (it
degrades gracefully). The endpoint also ignores the eventIds filter and
returns every event in the window; filtering is effectively client-side.
2026-07-01 02:34:19 +00:00
James Woglom c5854ac17c Degrade DEVICE_STATUS gracefully when event 81 is missing or partial
Event 81 (LidDailyBasal, battery) is not in Tandem's default id list; the
pump-logs endpoint may not return it. DEVICE_STATUS already fetches all
event types, and no-daily-basal-event already returns nothing — add a test
pinning that, plus a guard so an event 81 that arrives without battery
fields is skipped with a warning instead of raising on the percent math.
2026-07-01 02:29:57 +00:00
James Woglom b362bbbf3d Rewire pump_events() onto the pump-logs endpoint with date windowing
Fetch pre-parsed JSON events from get_pump_logs instead of decoding the
retired reportsfacade binary stream:
- page the requested range into inclusive windows of at most 28 days
  (the endpoint caps each request at ~4 weeks), covering short ranges and
  single days correctly
- dedupe events that span windows by (sequenceGroup, sequenceNumber)
- count but skip clockChanges (LID_TIME_CHANGED/LID_DATE_CHANGED are not
  consumed by any processor)
- parse via Events_from_json

Remove the dead reportsfacade pump_events_raw() and the now-unused
pump_event_metadata()/PumpEventMetadata/LastUpload types.
2026-07-01 02:27:20 +00:00
James Woglom 408366fe6b Test enum/ratio, bitmask array, and raw-field shims on the JSON adapter
Verify against real captured pump-logs events that build_from_json:
- resolves enum/dictionary fields from their raw ints (commandedRateSource,
  alarmId, requestedAction, previousUserMode, glucoseValueStatus incl. 0)
- scales ratio fields (rate x0.1)
- folds bitmask arrays of set-bit indices back to the raw int the IntFlag
  expects (activeSleepSchedule [0]->1, cgmDataType [0]->1,
  egvInfoBitmask [0,5,6,7,8,11,12]->6625), and empty array->0
- keeps the raw.timestamp shim used by process_device_status and the raw
  egvTimeStamp seconds used by ProcessCGMReading
2026-07-01 02:19:54 +00:00
James Woglom 0779803de2 Generate JSON->event adapter via the events codemod
Extend build_events.py (the codemod) so events.json stays the source of
truth: each generated event class gains build_from_json(event), mapping a
pump-logs JSON event's eventProperties onto its {field}[Raw] attrs
(matched by normalized field name), plus RawEvent.build_from_json() which
derives timestampRaw from pumpDateTime so eventTimestamp/seqNum/eventId
keep working. Add generic.Event_from_json()/Events_from_json() dispatchers
mirroring Event()/Events(); unknown eventCode -> bare RawEvent.

Enum/dictionary/ratio fields are raw ints (map directly onto {field}Raw so
existing properties resolve); bitmask fields arrive as arrays of set-bit
indices, converted to the raw int via _bitmask_arr_to_int. events.py is
regenerated; the byte-path build() is unchanged.

Tests: tests/eventparser/test_from_json.py.
2026-07-01 02:04:24 +00:00
James Woglom d2e947ffa3 Add get_pump_logs() BFF events fetch with typed response
Implement TandemSourceApi.get_pump_logs(device_id, ...) for GET
api/reports/bff/pump-logs/{assignmentId}?pumperId&startDate&endDate&eventIds,
the JSON events endpoint that replaces the base64 reportsfacade/pumpevents.
startDate/endDate are sent as {ymd}T00:00:00Z / {ymd}T23:59:59Z per the
captured request. Adds typed PumpLogsResponse/PumpLogEvent TypedDicts,
verified to cover every key across all captured pump-logs responses.

Tests: URL/path/param construction (order-independent parse_qs), default
vs custom vs empty eventIds, empty query dict passthrough, return
passthrough, and None-dates-default-to-today.
2026-07-01 01:38:39 +00:00
James Woglom 27ddf0cb1d Rename misleading check.py local var to deviceId
The device-id flow now carries the UUID assignmentId (as deviceId) end to
end; rename the leftover tconnectDeviceId local in check.py to match. The
deviceId flow is exercised by the existing choose_device, process and
update_profiles tests.
2026-07-01 01:27:09 +00:00
James Woglom b60bfb94ee Add Phase-2 backfill tests (update_profiles, adapter, event ids)
- tests/sync/tandemsource/test_update_profiles.py: settings sourcing from
  pump_metadata() — matching deviceId with settings reaches
  PumpSettings.from_dict (proven via sentinel, using the real BFF
  settings.details shape); settings=None / no-match / empty return False
  without parsing.
- test_tandemsource.py: adapter edge cases (availableDataRange/settings
  keys absent, missing required key raises KeyError, Mobi Control-IQ+
  passthrough) and DEFAULT_EVENT_IDS regression (55 ids, no dupes,
  477/480/486 present).

Fixtures are inline and trimmed from the real captured responses.
2026-07-01 01:26:22 +00:00
James Woglom 4c548203a5 Migrate metadata consumers to BFF pump_metadata()
Switch choose_device, check, update_profiles, process.py and cli_helpers
from the old pump_event_metadata() (reportsfacade) to the normalized
pump_metadata() (BFF): tconnectDeviceId -> deviceId (UUID), and
lastUpload.settings -> settings.

Handle the BFF returning never-uploaded pumps (maxDateWithEvents=None):
skip them in the most-recent auto-select and fall back to the first
pump; raise a clear NoDevicesFound on an empty account instead of an
opaque TypeError. Clean stale comments/docstrings in tandemsource.py.

Tests: add tests/sync/tandemsource/test_choose_device.py (11 cases:
explicit/auto/never-uploaded/empty/InvalidSerialNumber/stale-warning)
and tests/api/test_tandemsource.py (pump_metadata adapter mapping),
and update the test_process fixture to the new keys.
2026-07-01 01:18:52 +00:00
James Woglom 5c5449d5bd Add normalized PumpMetadata model + BFF adapter
Introduce a typed PumpMetadata TypedDict and pump_metadata()/
_bff_pump_to_metadata() that adapt get_pumper().pumps[] into the stable
shape the sync code needs. Maps the new BFF fields to normalized names:
assignmentId -> deviceId (UUID), maxDateOfEvents -> maxDateWithEvents,
availableDataRange.start -> minDateWithEvents, settings.details ->
settings. Verified against the captured account response (7 pumps).

Additive only; consumers are migrated off pump_event_metadata() in a
follow-up commit.
2026-07-01 01:04:16 +00:00
James Woglom 8761e70b18 Add get_pumper() BFF metadata method with typed response
Add TandemSourceApi.get_pumper() for GET api/reports/bff/pumper/{pumperId},
the new device-list endpoint that replaces pumpeventmetadata. Adds
strictly-typed TypedDicts (BffPumper, BffPump, AvailableDataRange,
PumpSettingsEnvelope) derived from the captured account response; verified
they exactly cover the real JSON keys. pumps[].assignmentId is the UUID
device id for the pump-logs endpoint; settings.details (typed as dict for
now) will be modeled by PumpSettings in a later step. Nullable/absent
fields use total=False + Optional.
2026-07-01 01:02:23 +00:00
James Woglom f124b884b2 Harden id_token audience validation in extract_jwt
After the client_id change, extract_jwt still validates the id_token
audience against TDC_OIDC_CLIENT_ID (the OIDC-standard case). But since
the token exchange wasn't captured, we can't be certain Tandem sets
aud=client_id on the id_token. If it doesn't, fall back to decoding with
verify_aud disabled (signature + issuer still verified) and log a
warning, rather than failing login outright.
2026-07-01 01:00:30 +00:00
James Woglom d568a5be85 Update US Tandem Source OIDC client_id
The Tandem Source web app now authenticates with client_id
0oa4wnbvtladeyVZX4h7 (US); the old 0oa27ho9tpZE9Arjy4h7 no longer
appears in the current build. This value is used both for the OIDC
authorize/token requests and the id_token audience check, which stay
consistent. EU client_id left unchanged (no EU capture to verify).
2026-07-01 00:59:14 +00:00
James Woglom 654ee7ead3 Update DEFAULT_EVENT_IDS to the live 55-ID pump-logs list
Match the Tandem Source web app's getLogIDList() as observed in the live
GET api/reports/bff/pump-logs request (from the captured HAR). Adds the
FSL3 event ids 477 (join), 480 (data), 486 (stop); reorders to match the
frontend. No removals (was 52 ids, now 55).
2026-07-01 00:53:11 +00:00
James Woglom 9619174958 CI: run on dev branch (replaces develop)
The develop branch was replaced by dev, so point the push/pull_request
triggers at dev instead of the now-removed develop branch.
2026-07-01 00:27:19 +00:00
James Woglom a9c9a7ebd9 Add type annotations to TandemSource sync processors
Annotate the 11 event processors, the ProcessTimeRange orchestrator, and
UpdateProfiles. The shared processor interface is now typed:
__init__(tconnect, nightscout, tconnect_device_id, pretend, features),
enabled() -> bool, process(events, time_start, time_end) -> List[dict],
write(ns_entries) -> int. Converter helpers return Optional[dict] since
they fall through to None on type mismatch.

ProcessTimeRange.process() returns Tuple[int, Optional[int]] and its
tconnectDevice param reuses the PumpEventMetadata TypedDict. Client
params (TConnectApi/NightscoutApi/BaseEvent) use TYPE_CHECKING-guarded
imports with string forward refs to avoid import cycles at runtime.
2026-06-30 23:29:17 +00:00
James Woglom 8fd9bfcf72 Add type annotations to NightscoutApi
Annotate NightscoutApi methods and the module-level date helpers. Adds a
DateLike alias (str | datetime | arrow.Arrow) for the timestamp/filter
params. Writers return None; the last_uploaded_* getters return
Optional[dict]; api_status/current_profile return dict.

Response shapes are kept as loose dict/Optional[dict] rather than
TypedDicts since the Nightscout API shape varies across versions; only
inputs (which we control) are tightly typed.
2026-06-30 23:20:35 +00:00
James Woglom 000bae38b6 Add precise type annotations to TandemSourceApi
Annotate method signatures and dynamic JSON response types. Adds
TypedDicts for the responses whose shapes are confirmed from call sites
and logs:
- PumpEventMetadata (+ nested LastUpload) for pump_event_metadata()
- JwtClaims for the decoded id_token stored on jwtData; pumperId and
  accountId are UUID strings, not ints

pump_events_raw() returns a base64 str (not Any). pumper_info() stays
Any since it has no callers and its shape is never logged. TypedDict is
imported with a typing_extensions fallback for Python 3.7.
2026-06-30 23:14:06 +00:00
ClaudeandJames Woglom ea7cc8f4ec Remove dead code for legacy pre-Tandem Source APIs
Since the 2.0 migration to Tandem Source, the live sync path
(api.tandemsource + sync/tandemsource/*) no longer references the
legacy t:connect APIs. This removes that now-unreachable code.

Removed modules:
- api/controliq.py, api/ws2.py, api/android.py, api/webui.py
  (the legacy controliq / tconnectws2 / android / webui clients)
- process.py (old process_time_range; already broken since it
  imported sync submodules that no longer exist)
- parser/ciq_therapy_events.py, parser/tconnect.py (TConnectEntry)
- domain/therapy_event.py, domain/bolus.py, domain/device_settings.py,
  domain/utility.py

Trimmed dead wiring from live modules:
- api/__init__.py: dropped the controliq/ws2/android/webui properties,
  keeping only the tandemsource accessor
- check.py: removed the unused TConnectEntry import
- parser/nightscout.py: removed the unused legacy profile_store() plus
  the now-orphaned tandem_to_ns_time / tandem_to_ns_time_seconds helpers
  and InvalidTimeException (the live path uses tandemsource_profile_store)

Tests: removed suites covering the deleted modules; pared tests/api/fake.py
down to the TConnectApi fake still used by the tandemsource tests. README
"Tandem APIs" sections updated to reflect the single Tandem Source API.

Full test suite passes (48 passed, 1 skipped).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LQNn3mBG1kXTAdQb9c2jfW
2026-06-30 19:12:44 -04:00
James Woglom e5195b2613 Fix WAF 403 by sending same-origin Origin/Referer to Source API
api_headers() hardcoded Origin/Referer to tconnect.tandemdiabetes.com,
but requests target SOURCE_URL (source.tandemdiabetes.com /
source.eu.tandemdiabetes.com). The WAF enforces same-origin and
returned HTTP 403 ("The request is blocked"). Derive Origin/Referer
from SOURCE_URL so both US and EU regions match.
2026-06-30 22:56:26 +00:00
Beshoy GirgisandJames Woglom f0f94baf02 revert nightscout.py 2026-03-27 11:08:23 -07:00
Beshoy GirgisandJames Woglom bf894bce02 Add script to update events.json from minified url 2026-03-27 11:08:23 -07:00
Beshoy GirgisandJames Woglom 594ee19450 Add Freestyle Libre 3 (FSL3) CGM sensor support
Implement FSL3 sensor integration alongside G6, G7, and FSL2 with expanded
CGM alert codes, improved datetime handling, and test coverage.

**FSL3 Event Integration:**
- Add FSL3 events to CGM_READING, _CGM_JOIN, and _CGM_STOP event classes
- Enable unified processing of FSL3 alongside existing sensor variants:
  - Event 480: LID_CGM_DATA_FSL3
  - Event 477: LID_CGM_JOIN_SESSION_FSL3
  - Event 486: LID_CGM_STOP_SESSION_FSL3

**CGM Alert Enumeration:**
- Expand CGM alert codes from 8 to 18 mapped codes
- Add verified alert codes: 1, 2, 3, 8, 12, 22, 25, 45, 46, 48
- Rename alert 51 to CONTROL_IQ_LOW (was DEFAULT_ALERT_51)
- Add alert descriptions based on pump history verification

**Code Quality Improvements:**
- Fix duplicate enum keys in events.json (Sensor Type codes 12, 13)
- Add logging infrastructure to generic.py for event diagnostics
- Add conftest.py test configuration

**DateTime and API Improvements:**
- Fix format_datetime() for proper UTC conversion with Z suffix
- Simplify Nightscout API methods by removing redundant retry logic
- Improve error reporting in last_uploaded_entry() and last_uploaded_bg_entry()

**Test Coverage:**
- Add 3 FSL3 test cases with real pump data
- Test single reading processing, multiple readings, and JOIN event parsing
- All 105 tests passing (102 existing + 3 new FSL3 tests)
2026-03-27 11:08:23 -07:00
James Woglom d78d70adf5 fix #136 2026-03-26 03:56:47 -04:00
James Woglom 8381e50fe6 fix duplicate enum keys 2026-03-15 13:53:03 -04:00
James Woglom 93b0901aae Update events.json blob 2026-03-15 13:35:43 -04:00
Alessio RosiandJames Woglom 82ccaa5a88 fix: upgrade Python 3.9 → 3.11 to fix missing python-dotenv 2026-03-15 02:22:10 -04:00
James Woglom b1f63f8858 v2.3.5 2026-03-05 19:22:32 -05:00
James Woglom 9878e83755 exclude venv from flake8 2026-03-05 19:17:12 -05:00
James Woglom d8b57fe788 remove duplicate pipfile definitions also in setup.cfg, fix actions 2026-03-05 19:13:21 -05:00
James Woglom 664f97be35 pin pyjwt in setup.cfg 2026-03-05 18:54:08 -05:00
James Woglom 9094976085 update for py3.8 2026-03-05 18:50:11 -05:00
James Woglom b592f6b464 ci 3.8: PyO3 modules compiled for CPython 3.8 or older may only be initialized once per interpreter process 2026-03-05 03:00:20 -05:00
James Woglom 4f2affe70f switch from pkg_resources to importlib_metadata 2026-03-05 02:54:45 -05:00
James Woglom 0733531f67 add setuptools dep 2026-03-05 02:50:33 -05:00
James Woglom 68dcb25911 v2.3.4 2025-12-14 23:59:06 -05:00
James Woglom 795361c6ad timezone tests 2025-12-14 23:58:35 -05:00
James Woglom c9190df50a timestamp override in tests 2025-12-14 23:56:30 -05:00
James Woglom 15160537f5 add process_cgm_reading tests 2025-12-14 23:52:55 -05:00
Andy LowandJames Woglom 1f1e755503 Add timezone support to timestamp calculation
Update timestamp handling to include timezone information.
2025-12-14 23:51:35 -05:00
James Woglom aea3f6bd6b v2.3.3 2025-11-23 00:03:34 -05:00
James Woglom 2bf40cac28 fix TypeError: can't compare offset-naive and offset-aware datetimes 2025-11-23 00:03:16 -05:00
James Woglom 73dabe5ead v2.3.2 2025-11-18 14:01:18 -05:00
James Woglom e848a8482d add new process test for tz change 2025-11-18 14:00:54 -05:00
James Woglom 9c06efb045 when pump TZ changes moves date into the future, do not add "current" basal to extend to that timestamp 2025-11-18 13:59:17 -05:00
James Woglom 64aeb4d752 v2.3.1 2025-06-08 17:17:13 -04:00
James Woglom 6a9a426b97 explicit time_start/time_end for autoupdate 2025-06-08 11:07:57 -04:00
samfundevandJames Woglom 5a76a4cfd1 Fix auto-update only running for 24 hours
Fixes #11
2025-06-08 11:06:24 -04:00
James Woglom 4837ac1e86 v2.3.0 2025-06-07 23:34:42 -04:00
James Woglom 8b15ec5c90 add test_profile_data 2025-06-07 23:31:10 -04:00
James Woglom 37b008f6c3 fix test path 2025-06-07 23:29:09 -04:00
James Woglom 8c40fdb533 fix test import 2025-06-07 23:27:42 -04:00
James Woglom d51080f6d0 Fix profile test 2025-06-07 23:24:41 -04:00
James Woglom b32415aaac Delete dead non-tandem source tests 2025-06-07 23:21:38 -04:00
James Woglom ffd3c5b1ea Delete dead non-tandem source code 2025-06-07 23:21:18 -04:00
James Woglom 0b4674bae9 update check script 2025-06-07 23:19:23 -04:00
James Woglom a1202decbe ignore name never assigned in scope flake8 2025-06-07 22:53:18 -04:00
Adam BovillandJames Woglom 4888426034 feat: Add EU region support for Tandem t:connect API
Add comprehensive support for European Tandem t:connect servers alongside existing US support.

Features:
- Region parameter in TandemSourceApi (default: US, supports: US/EU)
- EU-specific API endpoints and client ID configuration
- Region-aware credential caching to prevent cross-region conflicts
- Command line --region flag and TCONNECT_REGION environment variable
- Full backward compatibility (defaults to US region)

Technical Changes:
- Separated common SSO URLs from region-specific service URLs
- Added region validation and URL property methods
- Enhanced credential cache with region isolation
- Updated CLI argument parsing and configuration system
- Added comprehensive logging for region selection

Testing:
- Verified US region backward compatibility
- Successfully tested EU authentication and data retrieval
- Processed real EU pump data (1500+ events, 39KB)
- Validated all event types: basal, bolus, CGM, user modes, alarms
- Confirmed Nightscout integration compatibility

This enables EU Tandem pump users to sync their data using:
  --region EU or TCONNECT_REGION=EU
2025-06-07 22:48:43 -04:00
James Woglom 803b15b886 v2.2.4 2025-05-06 13:14:01 -04:00
JoshandJames Woglom 9e78fe770f chore: add main py for module finding in vscode 2025-05-06 13:13:19 -04:00
JoshandJames Woglom dfb39e07ef warn: add warning if selected pump serial has no recent events 2025-05-06 13:13:19 -04:00
JoshandJames Woglom 9fad0d71ef chore: update gitignore with venv and vscode dirs 2025-05-06 13:13:19 -04:00
James Woglom f5cd7c0151 v2.2.3 2025-03-29 23:37:15 -04:00
James Woglom 13bb106924 defaults: failure time to 75 min, turn off auto restart on failure 2025-03-29 23:36:53 -04:00
James Woglom fd96b08aab stop running pipenv check 2025-01-15 19:14:20 -05:00
James Woglom 4a8da39b44 process: automatically fetch all event types for devicestatus feature 2025-01-15 18:56:36 -05:00
James Woglom 7a0f9477f2 eventparser: add todict function on all event classes 2025-01-15 18:56:08 -05:00
James Woglom 934d90e3b9 log found ProcessDeviceStatus 2025-01-02 20:05:31 -05:00
James Woglom ea84b0b9cc v2.2.2 2024-12-30 22:05:22 -05:00
James Woglom 07aaea9e1c fix tests 2024-12-30 22:05:11 -05:00
James Woglom 67b9f42f9b v2.2.1 2024-12-30 22:02:54 -05:00
James Woglom 997ab7bac8 attempt to fix batteryChargePercent 2024-12-30 22:02:36 -05:00
James Woglom b1f8263ceb v2.2.0 2024-12-13 19:47:29 -05:00
James Woglom 29d08a7f1b fix non-autoupdate 2024-12-13 19:47:01 -05:00
James Woglom c7ade49eea devicestatus: tune nightscout output to look more like Loops uploader 2024-12-13 02:09:36 -05:00
James Woglom 1f0fbd7788 less noisy logs in update profiles 2024-12-13 01:42:58 -05:00
James Woglom 4bda0a21f2 more explicit logging for last update seen 2024-12-13 01:41:16 -05:00
James Woglom d1341e09c0 devicestatus: set pump.battery.percent 2024-12-12 22:20:13 -05:00
James Woglom fb9588ff2c catch iso8601 date errors 2024-12-12 00:41:51 -05:00
James Woglom 2339b4543e v2.1.9 2024-12-12 00:36:16 -05:00
James Woglom 3f6010fafc add processdevicestatus 2024-12-12 00:36:06 -05:00
James Woglom a028cdf3fe v2.1.8 2024-12-12 00:29:19 -05:00
James Woglom 093b42ff94 fix codecov 2024-12-12 00:29:11 -05:00
James Woglom 00023c6aba fix flake8 2024-12-12 00:27:35 -05:00
James Woglom 1ed3d35965 v2.1.7 2024-12-12 00:23:45 -05:00
James Woglom 9493b6546f process_alarm exclude resumepumpalarm and test 2024-12-12 00:23:17 -05:00
James Woglom 24a635ca21 add process_device_status and process_user_mode tests 2024-12-12 00:09:28 -05:00
James Woglom 80824906d9 add unit test 2024-12-11 22:41:58 -05:00
James Woglom e5259a7981 attempt to mutate battery charge percent 2024-12-11 00:56:01 -05:00
James Woglom 650fb60988 support excluding event id filter 2024-12-11 00:50:40 -05:00
James Woglom 2b367d45f3 eventparser: use eventID consistently as seqNum 2024-12-10 20:35:17 -05:00
James Woglom dd2dcd17bd eventparser: add custom events 2024-12-10 17:48:51 -05:00
James Woglom 98b7edc904 eventparser: handle unknown ids in Event() 2024-12-10 17:44:54 -05:00
James Woglom e82d311fd6 eventparser: move baseevent 2024-12-10 17:44:32 -05:00
James Woglom 9a2a4ca771 v2.1.6 2024-10-16 21:34:22 -04:00
James Woglom 54ba2ed7df profiles: sort and set enteredBy 2024-10-16 21:34:11 -04:00
James Woglom 2892eb8ace exclude empty pump profile segments 2024-10-16 21:13:41 -04:00
James Woglom 1d432982ad v2.1.5 with pypi upload fix 2024-10-07 21:59:01 -04:00
James Woglom 891c2e2c10 fix printf 2024-10-07 21:30:50 -04:00
James Woglom 7dc479c84b v2.1.4 2024-10-05 12:56:17 -04:00
James Woglom 0417fb9fd8 add IGNORE_ZERO_UNIT_BASAL 2024-10-05 12:55:59 -04:00
James Woglom b80d52662b v2.1.3 2024-10-03 01:00:16 -04:00
Zack FernandesandJames Woglom 51ac469f00 Fix choose_device import class name 2024-10-03 00:59:45 -04:00
James Woglom 81b13f236a v2.1.2 2024-10-02 23:07:43 -04:00
James Woglom d57b3872f1 fix process_user_mode again 2024-10-02 23:07:34 -04:00
James Woglom 0609a46ed2 v2.1.1 2024-10-02 22:23:39 -04:00
James Woglom e63d725c2b process_user_mode: fix bug when exercise concludes 2024-10-02 22:23:24 -04:00
James Woglom fec964e767 v2.1.0 2024-10-02 02:14:28 -04:00
James Woglom 366182f65b fix timezone transformation logic 2024-10-02 02:14:01 -04:00
James Woglom d9d09dddb3 v2.0.9 2024-10-02 01:35:10 -04:00
James Woglom 04643255fe heroku_helpers 2024-10-02 01:34:47 -04:00
James Woglom c2f7070f3b no 3.7 build job 2024-10-02 00:56:38 -04:00
James Woglom 9c35f850b9 v2.0.8 2024-10-02 00:54:29 -04:00
James Woglom a7383b0796 fix return code 2024-10-02 00:52:41 -04:00
James Woglom 4f52927d2f try to fix jwt import error 2024-10-02 00:45:39 -04:00
James Woglom 5b938c010d only conditionally import typing_extensions 2024-10-02 00:39:56 -04:00
James Woglom 3e50c7018d py3.7 force pyopenssl 2024-10-01 21:02:04 -04:00
James Woglom 32f3639eb0 py3.7 actions 2024-10-01 17:29:49 -04:00
James Woglom 9a7cb1bdfd no anchors 2024-10-01 17:27:01 -04:00
James Woglom ead7ab883b check old python versions 2024-10-01 17:25:26 -04:00
James Woglom ff395ffa3e test on py3.7 2024-10-01 17:17:55 -04:00
James Woglom 8f2ad586fd v2.0.7: fix py3.7 compat 2024-10-01 17:17:33 -04:00
James Woglom 828cccaf10 v2.0.6: update install_requires packages 2024-10-01 17:05:54 -04:00
James Woglom ae26102df2 v2.0.5 2024-10-01 17:01:40 -04:00
James Woglom 152c263fe0 Use pyjwt v2.8 to allow python3.7 support 2024-10-01 16:56:19 -04:00
James Woglom 38c933a257 v2.0.4 2024-10-01 16:50:19 -04:00
James Woglom d507e47e7a convert to float 2024-10-01 16:44:20 -04:00
James Woglom 8c2f41c2d5 skip processing no basal events 2024-10-01 16:30:18 -04:00
James Woglom 018c6d2228 dont repeat the last event on a process cycle 2024-10-01 16:29:23 -04:00
James Woglom 32ba49dc8a autoupdate bugfix 2024-10-01 16:24:43 -04:00
James Woglom a5cbc5d612 v2.0.3 2024-10-01 16:08:06 -04:00
James Woglom ef515021cc check changes for last seen event id 2024-10-01 16:07:48 -04:00
James Woglom 4af54bf7cb set tzinfo (fix #100) 2024-10-01 15:59:20 -04:00
James Woglom d9d1b8a8fb v2.0.2 2024-09-30 01:13:28 -04:00
James Woglom 29ed755356 3.8+ and add 3.11 2024-09-30 01:13:06 -04:00
James Woglom b862ea9d0d pin 2024-09-30 01:12:26 -04:00
James Woglom 2677fc86be pin arrow version for py3.7 compat 2024-09-30 01:09:25 -04:00
James Woglom 1ae40e3cdb python3.7 compat 2024-09-30 01:06:21 -04:00
James Woglom 90c63c8211 py3.7 compat 2024-09-30 00:58:22 -04:00
James Woglom 60c2e08dcf py3.7 compat 2024-09-30 00:53:14 -04:00
James Woglom d6f08c61b8 v2.0.1 2024-09-30 00:50:07 -04:00
James Woglom 784387dcb8 sensor start/stop/join eventtypes 2024-09-30 00:49:59 -04:00
James Woglom 84092e1de6 formatting fixes 2024-09-30 00:32:07 -04:00
James Woglom bb3094869d fix old tests (will be removed/updated) 2024-09-30 00:14:16 -04:00
James Woglom ec497d7d00 unit bugfixes 2024-09-30 00:09:38 -04:00
James Woglom 5aa5ea5215 version 2.0.0 2024-09-29 23:18:12 -04:00
James Woglom 34853dfb36 update readme and default sync features 2024-09-29 23:17:43 -04:00
James Woglom 362888cb14 update profiles 2024-09-29 23:06:42 -04:00
James Woglom abe8ea32aa fix event id 2024-09-29 22:13:21 -04:00
James Woglom 40cccc5de5 lambda 2024-09-29 22:11:11 -04:00
James Woglom 81d1e80b59 formatting fixes 2024-09-29 22:10:41 -04:00
James Woglom 210bcddbd3 V2 substantial completion 2024-09-29 21:50:17 -04:00
James Woglom c0cddb80b9 parser fixes 2024-09-21 21:53:36 -04:00
James Woglom 254d3fbbfc sync: initial source implementations (basal, suspension, alarm) 2024-09-21 21:53:19 -04:00
James Woglom 712b8a19cf event class 2024-09-21 21:52:52 -04:00
James Woglom 9752270b6c eventparser: fix parsing 2024-09-21 17:16:40 -04:00
James Woglom 7066afef33 sync/tandemsource: stub 2024-09-21 17:16:25 -04:00
James Woglom 63fe56467e api/tandemsource: cache credentials 2024-09-21 17:15:44 -04:00
James Woglom 6b7afaba03 fix syntax 2024-09-19 00:27:35 -04:00
James Woglom 454b545e35 exclude none 2024-09-19 00:26:04 -04:00
James Woglom 4e4de23e80 exclude true/false enum vals 2024-09-19 00:20:22 -04:00
James Woglom 68384caa04 remove tconnectpatcher ref 2024-09-19 00:16:27 -04:00
James Woglom 6fc49c60d3 event parser V1 2024-09-19 00:15:38 -04:00
James Woglom 75260c6957 update readme 2024-09-19 00:14:41 -04:00
James Woglom a77ebb5429 TandemSource API 2024-09-18 22:49:40 -04:00
James Woglom 822589e4b2 more ignore 2024-09-08 15:11:23 -04:00
James Woglom 90f2406b4f ignore more unrelated pipenv check failures 2024-09-08 15:10:20 -04:00
James Woglom 9d8554bd03 to str 2024-09-08 15:08:34 -04:00
James Woglom c60b19dbed handle WAF block 2024-09-08 15:07:54 -04:00
James Woglom 492963e240 bump to v1.0.0 2024-09-08 15:02:50 -04:00
James Woglom c9f6362928 Work-around for broken web-based auth method 2024-09-08 15:01:42 -04:00
James Woglom 3d2c2dc280 bump v0.9.8 2024-06-08 20:02:49 -04:00
James Woglom e2b55d55af bump current tconnect version 2024-06-08 20:02:30 -04:00
James Woglom 6150619d1a use NS_IGNORE_CONN_ERRORS secret 2024-06-08 20:01:16 -04:00
James Woglom 7cba6bb0e6 ignore connectionerrors in pretend mode 2024-06-08 20:01:05 -04:00
James Woglom d2190db45d dont fail on codecov error 2024-05-23 02:08:30 -04:00
James Woglom d928c0ca72 version: bump to v0.9.7 2024-05-23 00:52:38 -04:00
James Woglom 5c09748fdb add more ignores 2024-05-23 00:48:42 -04:00
James Woglom 2bfc5a7860 test pump events 2024-05-23 00:44:06 -04:00
James Woglom 73a0e2924d ignore irrelevant pipenv errors 2024-05-23 00:08:16 -04:00
Matthew MazaikaandJames Woglom f973f374e7 fix: update sleep events if their duration changes 2024-05-22 22:26:41 -04:00
James Woglom 8fb2ced9c5 version: bump to 0.9.6 2023-10-18 00:05:10 -04:00
James WoglomandGitHub d902cd7aab Push latest tag 2023-10-18 00:02:32 -04:00
James WoglomandGitHub a781e458c3 Update README.md 2023-09-30 21:01:15 -04:00
James Woglom 3fe131bcf3 version: bump to 0.9.5 2023-09-30 20:48:39 -04:00
James Woglom 3260442893 Bump supported tconnect software version 2023-09-30 20:37:05 -04:00
James Woglom e3542bc002 webui: detect logged out state and trigger re-login 2023-09-30 20:33:55 -04:00
James Woglom fb5f89e051 version: bump to 0.9.4 2023-06-11 00:28:18 -04:00
James Woglom 017e8845b9 Warn when default nightscout url or serial are being used 2023-06-11 00:24:42 -04:00
James Woglom 30f1a8cbcd Warn when default username or password is being used 2023-06-11 00:24:42 -04:00
James Woglom 22006f7c0f Bump supported software version and display login error message 2023-06-11 00:24:42 -04:00
James Woglom 166a142de5 Update README.md 2023-02-04 19:04:58 -05:00
jwalbergandJames Woglom b68425c5d3 Fixed typo in batch file instructions 2023-02-04 19:04:58 -05:00
jwalbergandJames Woglom 9ab6906e81 Update Readme.md for non-WSL Windows installation
This works in Windows, as-is. Updated the installation instructions with folder paths and scheduling instructions.
2023-02-04 19:04:58 -05:00
James Woglom 86b6b28803 bump to v0.9.3 2023-02-04 00:15:12 -05:00
James Woglom 4409b78890 add completed extended bolus test 2023-02-04 00:09:35 -05:00
James Woglom e52cd73549 Fix incomplete extended bolus parsing 2023-02-03 23:40:15 -05:00
James Woglom 10fca69038 ignore unrelated pipenv check 2023-01-25 01:17:41 -05:00
James Woglom 1f95dd99f6 fix AutoupdateNoNewDataDetectedError 2023-01-25 01:13:53 -05:00
James Woglom 1e16b7ad01 bump version to v0.9.2 2023-01-16 19:59:49 -05:00
James Woglom cffee9cdca fix codecov config 2023-01-16 19:58:44 -05:00
James Woglom ee85226c2f fix test failure 2023-01-16 19:54:16 -05:00
James Woglom db7d34e62e flake8 fix 2023-01-16 19:52:22 -05:00
James Woglom 7b17304efc bump v0.9.1 2023-01-16 19:49:47 -05:00
James Woglom d0af9c5c91 Profile sync bugfix and extra validation logic 2023-01-16 19:35:01 -05:00
James Woglom 85303bca82 transparently split large time range calls to ws2 therapytimeline 2023-01-16 19:25:21 -05:00
James Woglom c6820b7a0d update log message in process when in pretend mode 2023-01-16 18:21:21 -05:00
James Woglom 04c5a37b8d separate basal suspension events into own feature to allow skipping WS2 api 2023-01-16 18:06:29 -05:00
James Woglom 31e6737ca7 bump version to 0.9.0 2023-01-16 17:37:13 -05:00
James Woglom b9fae36dda ensure permutations of the same number in different types are considered the same NS profile 2023-01-16 17:35:31 -05:00
James Woglom 1507398eb0 track count in integration tests 2023-01-16 17:12:46 -05:00
James Woglom 4208ffa709 secret bugfix 2023-01-16 17:06:40 -05:00
James Woglom 3b66718e1f update README with profile sync feature 2023-01-16 17:01:04 -05:00
James Woglom d9e49e1fc8 integration tests for profile upload 2023-01-16 16:58:19 -05:00
James Woglom dd9a9ea72c tests for profile synchronization 2023-01-16 16:00:50 -05:00
James Woglom d69a760f5b Translate Tandem profile information to Nightscout format 2023-01-16 14:25:31 -05:00
James Woglom df4e9e4ed0 fix codecov configuration 2023-01-07 01:17:56 -05:00
James Woglom 98ee986941 bump to 0.8.10 2023-01-07 00:57:52 -05:00
James Woglom 3f6a0e007d wider log output in --check-login 2023-01-07 00:56:58 -05:00
James Woglom 48ec97434f log info about failed software version check 2023-01-07 00:51:07 -05:00
James Woglom cf0a88c53a Show full error tracebacks in --check-login 2023-01-07 00:50:56 -05:00
James Woglom a4ab6398f0 bump v0.8.9 2022-12-25 13:47:11 -05:00
James Woglom f67671e1ef handle cancelled extended bolus with no timestamp: fix #73 2022-12-25 13:46:21 -05:00
James Woglom 5e4d81a618 v0.8.8 2022-12-12 22:37:30 -05:00
James Woglom cabbc783c7 catch api exceptions due to workaround with timestamp format in nightscout (#71) 2022-12-12 22:36:46 -05:00
James Woglom 62f1322ef6 v0.8.7 2022-12-02 20:48:51 -05:00
James Woglom 139ccb1878 ignore python3.7 pipenv check warning 2022-12-02 20:48:12 -05:00
James Woglom e60e9ce537 version 0.8.6 2022-12-02 20:42:35 -05:00
James Woglom 6e180d9f2a add basal therapy event type, now that Tandem is storing it along with bolus/cgm/bgs 2022-12-02 20:42:35 -05:00
Jarred YawandJames Woglom b929d1151e Moved logger.warn() statements to logger.warning() due to the deprecation msgs I was getting while testing 2022-10-02 00:18:11 -04:00
James Woglom 4d4ee7b425 v0.8.5 2022-10-02 00:07:32 -04:00
James Woglom 0c5a6d5453 when last_uploaded query returns None, try with fixed timestamp 2022-10-02 00:05:08 -04:00
James Woglom 0b7e33db96 allow self-signed SSL cert with NS_SKIP_TLS_VERIFY (fixes #63) 2022-10-01 23:49:16 -04:00
James Woglom 5d58b23d27 v0.8.4 2022-09-17 10:31:23 -04:00
James Woglom 40aea810cc pass kwargs to ws2 query 2022-09-17 10:30:01 -04:00
Ryan StutsmanandJames Woglom ec84afdb7a Fix format string in UnknownTherapyEventType.
%s was missing from the format string. This enhances the message to
report the unexpected thearpy type along with the dump of the event that
trigger the exception.
2022-08-26 10:53:50 -04:00
James Woglom fca7f573a3 set codecov threshold to 50%, to stop failing builds for 0.01% changes in code coverage 2022-08-26 10:53:38 -04:00
James WoglomandGitHub 76fc043a2b Update issue templates 2022-08-24 12:55:32 -04:00
James Woglom 86e07880a9 bump to v0.8.3 2022-08-24 12:28:43 -04:00
Jarred YawandJames Woglom 751087373c fix unknown therapy event error in ciq_therapy_event.py 2022-08-24 12:20:45 -04:00
Ryan StutsmanandJames Woglom f47421e482 Replace hand-rolled date format with isoformat().
Fixes #47.
2022-08-22 16:45:46 -04:00
t1diotacandJames Woglom dfc39d61bb Update README.md
- Added sections on creating a user-specific install and crontab.
- Added bullet points on installing on CentOS/RHEL/Rocky Linux 8
2022-08-19 10:31:39 -04:00
James Woglom e8a12e291f version bump to 0.8.2 2022-08-12 00:20:11 -04:00
James Woglom 0ebfb2b744 add 10 second timeout on ws2 requests 2022-08-12 00:19:11 -04:00
James Woglom 8f6d03797a update API section in readme, and check-login script to properly sanitize 2022-08-12 00:06:17 -04:00
James Woglom 6f15ef8857 use domain objects for webui scraping pump profiles 2022-08-11 01:22:44 -04:00
James Woglom 4da4d6e2a6 log tconnect software version 2022-08-11 00:11:46 -04:00
James Woglom 92bed13878 log times for autoupdate errors 2022-08-10 23:28:15 -04:00
James Woglom 955ac68914 improve logging 2022-08-10 02:12:19 -04:00
James Woglom 26d4c63a4d bump to v0.8.0 2022-08-10 01:54:14 -04:00
James Woglom 81a62b8902 warning messages when falling back on Ws2 2022-08-10 01:53:31 -04:00
James Woglom 2f5775cbfb internally track bolus from CIQ API identically at par with WS2 2022-08-10 01:31:45 -04:00
James Woglom f13929a45a therapy_event and tests 2022-08-10 00:22:13 -04:00
James Woglom a18c2f3d17 move Bolus internal state from dictionary to domain object 2022-08-09 22:54:51 -04:00
James Woglom 1b400d3b22 Only connect to ws2 api when requisite feature needs that data 2022-07-26 00:07:39 -04:00
James Woglom d3816b18b2 propagate time filter to all ns_writes 2022-07-20 02:43:31 -04:00
James Woglom 4a6dd5f51d include time range in last_uploaded_entry (needs tests) 2022-07-20 02:29:48 -04:00
James Woglom 51abc15512 propagate -- but do not use -- time_start and time_end in last_uploaded_entry 2022-07-20 02:17:02 -04:00
James Woglom f672a2e199 bump to v0.7.2 2022-07-20 01:36:26 -04:00
James Woglom 52031d1d8a fix GETs with data 2022-07-20 01:32:32 -04:00
James Woglom 7139247d1c ensure consistent user agent across runtime 2022-07-20 01:17:05 -04:00
James Woglom f99c2b6119 HTTP 403 workarounds 2022-07-20 01:08:52 -04:00
James Woglom 0b3808d43d fix session ordering 2022-07-20 00:39:39 -04:00
James Woglom d4918984f8 requests version upgrade: explicitly pass data for get requests 2022-07-20 00:38:48 -04:00
James Woglom 123acaf163 fix requests proxies monkey-patch 2022-07-20 00:36:22 -04:00
James Woglom 898fb63af5 fix session creation ordering 2022-07-20 00:28:07 -04:00
James Woglom 46c4d60525 YAML was a mistake
https://github.com/actions/setup-python/issues/160
2022-07-20 00:07:52 -04:00
James Woglom e0d452bdea drop python 3.6 support in setup.cfg 2022-07-20 00:04:44 -04:00
James Woglom 31d2185154 drop python 3.6 support. no longer supported by requests 2022-07-20 00:04:14 -04:00
James Woglom d7cc6f957f test proxy 2022-07-19 23:57:49 -04:00
James Woglom ae2bf9a3a6 support proxy 2022-07-19 23:23:12 -04:00
James Woglom fe57bd6c14 bump to 0.7.1 for consistency between pip package and github/package metadata 2022-04-06 17:51:32 -04:00
James WoglomandGitHub 0872c756d2 Only run publish-docker on tags 2022-03-17 16:32:45 -04:00
James Woglom 7d8dabb3ef AndroidApi: match HTTP headers with app 2022-03-17 16:18:15 -04:00
James Woglom 798225c606 api: add user_agent to AndroidApi, move improperly scoped endpoint to tconnectapi 2022-03-17 16:07:57 -04:00
James WoglomandGitHub b08b9b8c76 trigger GitHub Actions on tag push 2022-02-27 00:35:53 -05:00
James Woglom 90bbd5dc63 bump version to v0.6.6 2022-02-22 00:17:58 -05:00
James WoglomandGitHub 5e56b41b62 Update publish-docker.yml
Add tags
2022-02-22 00:16:27 -05:00
James WoglomandGitHub e8fa6c5a7c Update publish-docker.yml
Add push_to_dockerhub GitHub Action
2022-02-22 00:08:20 -05:00
James Woglom fae1d4de2c api: add WebUIScraper which can read pump settings and profile info 2022-01-09 18:36:49 -05:00
James Woglom 76085e8d65 version bump to 0.6.5 2022-01-08 03:56:24 -05:00
James Woglom b4d0dad267 remove IOB feature in defaults because it is currently not displayed in the UI. document features in readme 2022-01-08 03:55:26 -05:00
James Woglom 7b22d612c3 autoupdate: refactor into class and write test 2022-01-07 00:32:50 -05:00
James Woglom 8b1ece3ac3 readme: rephrase initial section 2022-01-04 21:23:18 -05:00
James Woglom 7b06f1c457 secret: parse API_SECRET/TZ if NS_SECRET/TIMEZONE_NAME are missing 2022-01-04 21:02:20 -05:00
James Woglom 3a400390de bump to v0.6.4 2022-01-04 00:35:44 -05:00
James Woglom e2b30687e4 autoupdate: reset API connection when event index change is recorded but no data is found, potential fix for #11 2022-01-04 00:34:46 -05:00
James Woglom 0d956516d7 update Pipfile.lock, resolve GHSA-55x5-fj6c-h6m8 2022-01-03 17:58:51 -05:00
James Woglom 50cb57f11b secret: use TZ to infer TIMEZONE_NAME if set 2022-01-03 17:58:51 -05:00
James Woglom 2e515efc54 check: add additional output to --check-login 2022-01-03 17:58:51 -05:00
James WoglomandGitHub b52006b3b0 Update README to include Heroku instructions 2022-01-03 16:52:11 -05:00
James Woglom 07e5761178 bump version to 0.6.3 2021-12-27 15:58:48 -05:00
James Woglom 631d1c7b89 parser: support temp-profile basal suspension event 2021-12-27 15:56:50 -05:00
James Woglom 0253956377 test_secret: allow test to pass even if environment variables implicitly passed to pipenv test 2021-12-27 15:56:19 -05:00
James WoglomandGitHub 59816225e0 Update README.md 2021-12-23 21:59:18 -05:00
James WoglomandGitHub be113e9cf7 Update README.md 2021-12-23 21:56:38 -05:00
143 changed files with 23443 additions and 4098 deletions
+9 -4
View File
@@ -1,11 +1,16 @@
coverage:
status:
patch: no
changes: no
project:
default: false
tconnectsync:
paths: "tconnectsync/"
target: 75%
paths:
- "tconnectsync/"
target: '60%'
threshold: '5%'
tests:
paths: "tests/"
target: 95%
paths:
- "tests/"
target: '95%'
threshold: '5%'
@@ -0,0 +1,53 @@
---
name: 'Setup help: tconnectsync-heroku'
about: When experiencing an issue setting up tconnectsync-heroku
title: ''
labels: heroku, setup help
assignees: ''
---
**Describe the problem**
A clear and concise description of the issue you're experiencing.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
2. ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Have you followed the [Troubleshooting steps in the README?](https://github.com/jwoglom/tconnectsync-heroku#troubleshooting)** (Yes or No)
**Setup details**
* **On what platform are you using the t:connect mobile app?** (Android or iOS)
* **What version are you using of the t:connect mobile app?**
**Heroku log output**
If applicable, add the full output from the heroku logs in More > View Logs. ([See the instructions in the README.](https://github.com/jwoglom/tconnectsync-heroku#testing))
**Check Login output**
If applicable, [please follow the instructions to visit the `check_login` page](https://github.com/jwoglom/tconnectsync-heroku#testing), and copy and paste the output here.
This file may contain sensitive details like your Nightscout URL and pump serial number. Copy the output into a text editor like Textedit or Notepad first and find-and-replace sensitive strings, like your Nightscout URL and pump serial number, if they appear.
The output will also contain pump and CGM related information such as delivery events and blood sugars. If you would prefer to keep the contents private, send an email to tconnectsync<at>wogloms.net with the log output so @jwoglom can investigate.
**Additional context**
Add any other context about the problem here.
@@ -0,0 +1,49 @@
---
name: 'Setup help: tconnectsync'
about: When experiencing an issue setting up tconnectsync on Windows, Linux, or MacOS.
title: ''
labels: setup help
assignees: ''
---
**Describe the problem**
A clear and concise description of the issue you're experiencing.
**To Reproduce**
Steps to reproduce the behavior:
1. ...
2. ...
**Expected behavior**
A clear and concise description of what you expected to happen.
**Setup details**
* **Operating system:**
* **tconnectsync version** (from `--version`):
* **On what platform are you using the t:connect mobile app?** (Android or iOS)
* **What version are you using of the t:connect mobile app?**
**Terminal output**
If applicable, add the full output from your terminal from running tconnectsync. Copy the output into a text editor like Textedit or Notepad first and find-and-replace sensitive strings, like your Nightscout URL and pump serial number, if they appear.
**Check Login output**
If applicable, please run `--check-login` and upload the tconnectsync-check-output.log file as an attachment on the issue. This file should have sensitive details like your Nightscout URL and pump serial number automatically removed, but double-check before uploading.
This log will contain pump and CGM related information such as delivery events and blood sugars. If you would prefer to keep the contents private, send an email to tconnectsync<at>wogloms.net with the log output so @jwoglom can investigate.
**Additional context**
Add any other context about the problem here.
+45 -3
View File
@@ -1,9 +1,9 @@
name: Publish Docker image
on:
push:
branches: [ master ]
pull_request:
branches: [ master ]
tags:
- 'v*'
workflow_dispatch:
jobs:
push_to_registry:
@@ -21,3 +21,45 @@ jobs:
registry: docker.pkg.github.com
repository: jwoglom/tconnectsync/tconnectsync
tag_with_ref: true
- name: Push latest tag to GitHub Packages
uses: docker/build-push-action@v1
with:
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
registry: docker.pkg.github.com
repository: jwoglom/tconnectsync/tconnectsync
tags: latest
push: ${{ startsWith(github.ref, 'refs/tags/') }}
push_to_dockerhub:
name: Push Docker image to Docker Hub
runs-on: ubuntu-latest
steps:
- name: Check out the repo
uses: actions/checkout@v2
- name: Log in to Docker Hub
uses: docker/login-action@f054a8b539a109f9f41c372932f1ae047eff08c9
with:
username: ${{ secrets.DOCKER_USERNAME }}
password: ${{ secrets.DOCKER_PASSWORD }}
- name: Extract metadata (tags, labels) for Docker
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: jwoglom/tconnectsync
tags: |
type=ref,event=branch
type=ref,event=pr
type=semver,pattern={{version}}
type=semver,pattern={{major}}.{{minor}}
- name: Build and push Docker image
uses: docker/build-push-action@ad44023a93711e3deb337508980b4b5e9bcdc5dc
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+5 -5
View File
@@ -7,11 +7,11 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@master
- name: Set up Python 3.9
uses: actions/setup-python@v1
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: 3.9
python-version: '3.11'
- name: Install pypa/build
run: >-
@@ -28,6 +28,6 @@ jobs:
--outdir dist/
.
- name: Publish to PyPI
uses: pypa/gh-action-pypi-publish@master
uses: pypa/gh-action-pypi-publish@release/v1
with:
password: ${{ secrets.PYPI_API_TOKEN }}
+62 -33
View File
@@ -5,9 +5,9 @@ name: Python package
on:
push:
branches: [ master, develop ]
branches: [ master, dev ]
pull_request:
branches: [ master, develop ]
branches: [ master, dev ]
jobs:
build:
@@ -15,36 +15,65 @@ jobs:
runs-on: ubuntu-latest
strategy:
matrix:
python-version: [3.6, 3.7, 3.8, 3.9]
python-version: ['3.8', '3.9', '3.10', '3.11']
steps:
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m pip install --upgrade pip
python -m pip install flake8 pytest pipenv
pipenv install --system
- name: Run pipenv check
run: |
pipenv check
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Test with pytest
run: |
pytest
- name: Generate Coverage Report
run: |
pip install coverage
coverage run -m unittest
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v1
with:
fail_ci_if_error: true
- uses: actions/checkout@v2
- name: Set up Python ${{ matrix.python-version }}
uses: actions/setup-python@v2
with:
python-version: ${{ matrix.python-version }}
- name: Install dependencies
run: |
python -m venv .venv
.venv/bin/python -m pip install --upgrade pip
.venv/bin/python -m pip install -e . flake8 pytest coverage mypy
# - name: Run pipenv check
# run: |
# # DDoS attacks in wheel and setuptools packages, not relevant
# # root certificate store, not relevant
# pipenv check \
# --ignore 51499 \
# --ignore 52495 \
# --ignore 52365 \
# --ignore 59956 \
# --ignore 58755 \
# --ignore 67895 \
# --ignore 61893 \
# --ignore 61601 \
# --ignore 62044 \
# --ignore 67599 \
# --ignore 72083 \
# --ignore 71064 \
# --ignore 71608 \
# --ignore 72236
- name: Lint with flake8
run: |
# stop the build if there are Python syntax errors or undefined names
.venv/bin/flake8 . --exclude=.venv --count --select=E9,F63,F7,F82 --ignore=F824 --show-source --statistics
# exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide
.venv/bin/flake8 . --exclude=.venv --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics
- name: Type-check annotated modules with mypy
run: |
.venv/bin/mypy
- name: Run tconnectsync --help
run: |
.venv/bin/tconnectsync --help
- name: Test with pytest
run: |
.venv/bin/pytest
- name: Check codecov configuration
run: |
curl -X POST --data-binary @.codecov.yml https://codecov.io/validate
if [[ "$(curl -s -o /dev/null -w "%{http_code}" -X POST --data-binary @.codecov.yml https://codecov.io/validate)" != "200" ]]; then
echo Error parsing codecov file
exit 1
fi
- name: Generate Coverage Report
run: |
.venv/bin/coverage run -m unittest
- name: Upload Coverage to Codecov
uses: codecov/codecov-action@v1
with:
fail_ci_if_error: false
+4
View File
@@ -7,3 +7,7 @@ build
*.swa
*.egg-info
.env
tconnectsync-check-output.log
ignore_*
.venv/
.vscode/
+1 -1
View File
@@ -1,4 +1,4 @@
FROM python:3.9-slim as base
FROM python:3.11-slim as base
# The following is adapted from:
# https://sourcery.ai/blog/python-docker/
+8 -7
View File
@@ -5,16 +5,17 @@ verify_ssl = true
[dev-packages]
ptpython = "*"
flake8 = "*"
pytest = "*"
coverage = "*"
mypy = "*"
[packages]
tconnectsync = {editable = true, path = "."}
requests = "*"
bs4 = "*"
arrow = "*"
lxml = "*"
python-dotenv = "*"
requests-mock = "*"
tconnectsync = {path = "."}
[scripts]
tconnectsync = "python3 main.py"
test = "python3 -m unittest discover -vv"
build_events = "bash -c 'cd tconnectsync/eventparser && python3 build_events.py > events.py'"
lint = "bash -c 'flake8 . --count --select=E9,F63,F7,F82 && flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 && echo PASS'"
typecheck = "mypy"
Generated
+795 -122
View File
File diff suppressed because it is too large Load Diff
+144 -39
View File
@@ -3,44 +3,72 @@
![Python Package workflow](https://github.com/jwoglom/tconnectsync/actions/workflows/python-package.yml/badge.svg)
[![codecov](https://codecov.io/gh/jwoglom/tconnectsync/branch/master/graph/badge.svg)](https://codecov.io/gh/jwoglom/tconnectsync)
Tconnectsync synchronizes data one-way from the Tandem Diabetes t:connect web/mobile application to Nightscout.
Tconnectsync synchronizes data one-way from Tandem Source to Nightscout.
If you have a t:slim X2 pump with the companion t:connect mobile Android or iOS app, this will allow your pump bolus and basal data to be uploaded to [Nightscout](https://github.com/nightscout/cgm-remote-monitor) automatically. The t:connect Android app, by default, uploads pump data to Tandem's servers every hour, [but using this tool you can update the frequency to as low as every five minutes](https://github.com/jwoglom/tconnectpatcher)! This allows for nearly real-time (but not instantaneous) pump data updates, almost like your pump uploads data directly to Nightscout!
> [!IMPORTANT]
> Tandem has announced that t:connect will be shut down in favor of Tandem Source in the US beginning September 30, 2024.
> tconnectsync has undergone major changes to support Tandem Source. **For Tandem Source support, you MUST upgrade to tconnectsync version 2.0 or above.**
At a high level, tconnectsync works by querying Tandem's undocumented APIs to receive basal and bolus data from t:connect, and then uploads that data as treatment objects to Nightscout. It contains features for checking for new Tandem pump data continuously, and updating that data along with the pump's reported IOB value to Nightscout whenever there is new data.
If you have a t:slim X2 pump with the companion t:connect mobile Android or iOS app, this will allow your pump bolus and basal data to be uploaded to [Nightscout](https://github.com/nightscout/cgm-remote-monitor) automatically.
Together with a CGM uploader, such as [xDrip+](https://github.com/NightscoutFoundation/xDrip) or the official Dexcom mobile app plus Dexcom Share, this allows your CGM _and_ pump data to be automatically uploaded to Nightscout!
## How It Works
At a high level, tconnectsync works by querying Tandem's undocumented APIs to receive basal and bolus data from Tandem Source, and then uploads that data as treatment objects to Nightscout. It contains features for checking for new Tandem pump data continuously, and updating that data to Nightscout whenever there is new data.
When you run the program with no arguments, it performs a single cycle of the following, and exits after completion:
* Queries for basal information via the t:connect ControlIQ API.
* Queries for bolus, basal, and IOB data via the t:connect non-ControlIQ API.
* Merges the basal information received from the two APIs. (If using ControlIQ, then basal information appears only on the ControlIQ API. If not using ControlIQ, it appears only on the legacy API.)
* Queries Nightscout for the most recently created Temp Basal object by tconnectsync, and uploads all data newer than that.
* Queries Nightscout for the most recently created Bolus object by tconnectsync, and uploads all data newer than that.
* Uploads a single Nightscout Activity object representing the current IOB as reported by the pump.
* Logs in to Tandem Source
* Fetches your list of pumps, and unless overridden by an environment variable, fetches the event data for the pump which was most recently used
* Processes the internal pump event metadata to extract basal, bolus, CGM, and other pump event data
* Queries Nightscout to find the most recent data which was uploaded to it for each event category
* Uploads any missing data to Nightscout
If run with the `--auto-update` flag, then the application performs the following steps:
If run with the `--auto-update` flag, then the application periodically looks for new data and synchronizes it to Nightscout in a loop every few minutes.
* Queries an API endpoint used only by the t:connect mobile app which returns an internal event ID, corresponding to the most recent event published by the mobile app.
* Whenever the internal event ID changes (denoting that the mobile app uploaded new data to synchronize), perform all of the above mentioned steps to synchronize data.
## What Gets Synced
The following synchronization features are enabled by default:
Tconnectsync is composed of individual so-called _synchronization features_, which are elements of data that can be
synchronized between t:connect data from the pump and Nightscout.
When setting up tconnectsync, you can choose to configure which synchronization features are enabled and disabled.
Here are a few examples of reasons why you might want to adjust the enabled synchronization features:
* If you currently input boluses into Nightscout manually with comments, then you may wish to _disable the `BOLUS` synchronization feature_ so that there are no duplicated boluses in Nightscout.
* If you want to see Sleep and Exercise Mode data appear in Nightscout, then you may wish to _enable the `PUMP_EVENTS` synchronization feature_.
* If you want to automatically update your Nightscout insulin profile settings from your pump, then you may wish to _enable the `PROFILES` synchronization feature_.
These synchronization features are enabled by default:
* `BASAL`: Basal data
* `BOLUS`: Bolus data
* `IOB`: Insulin-on-board data. Only the most recent IOB entry is saved to Nightscout, as an "activity"
The following synchronization feature is disabled by default, but can be enabled via the `--features` flag:
* `PUMP_EVENTS`: Events reported by the pump. Includes support for the following:
* Site/Cartridge Change (occurs for both a site change and a cartridge change)
* Empty Cartridge/Pump Shutdown (from my investigation, occurs either when the cartridge runs out of insulin OR you hard-shut off the pump)
* User Suspended (occurs when you manually disable insulin delivery)
* Exercise Mode (in Nightscout, appears with a start and end time)
* Sleep Mode (in Nightscout, appears with a start and end time)
* Alarms, like cartridge out-of-insulin or pump malfunction
* Basal suspension (user or pump-initiated) and resume
* Cartridge, cannula, and tubing filled
* Sleep and exercise modes
* `PROFILES`: Insulin profile information, including segments, basal rates, correction factors, carb ratios, and the profile which is active.
The following synchronization features can be optionally enabled:
* `CGM`: Adds Dexcom CGM readings from the pump to Nightscout as SGV (sensor glucose value) entries. This should only be used in a situation where xDrip/Dexcom Share/etc. is not used and the pump connection to the CGM will be the only source of CGM data to Nightscout. **THIS WILL DELIVER CGM DATA WITH A SIGNIFICANT (>30 MINUTE) LAG AND SHOULD NOT BE USED AS A REPLACEMENT FOR DEXCOM SHARE OR OTHER REAL TIME MONITORING.**
To specify custom synchronization features, pass the names of the desired features to the `--features` flag, e.g.:
```bash
$ tconnectsync --features BASAL BOLUS PUMP_EVENTS PROFILES
```
If you're using tconnectsync-heroku, see [this section in its README](https://github.com/jwoglom/tconnectsync-heroku#Updating-synchronization-features).
## Setup
**To get started,** you need to choose whether to install the application via
The following setup instructions assume that you have a Linux, MacOS, or Windows (with WSL) machine that will run the application continuously.
If you've configured Nightscout before, you may be familiar with Heroku. [You can opt to run tconnectsync with Heroku by following these instructions.](https://github.com/jwoglom/tconnectsync-heroku)
**To get started,** you need to choose whether to install the application on your computer via
**Pip**, **Pipenv**, or **Docker**.
After that, you can choose to run the program continuously via **Supervisord**
@@ -61,18 +89,23 @@ You should specify the following parameters:
TCONNECT_EMAIL='email@email.com'
TCONNECT_PASSWORD='password'
# Your pump's serial number (numeric)
PUMP_SERIAL_NUMBER=11111111
# OPTIONAL: Your region (US or EU)
TCONNECT_REGION=US
# URL and API secret for Nightscout
# URL of your Nightscout site
NS_URL='https://yournightscouturl/'
# Your Nightscout API_SECRET value
NS_SECRET='apisecret'
# Current timezone of the pump
TIMEZONE_NAME='America/New_York'
# OPTIONAL: Your pump's serial number (numeric)
PUMP_SERIAL_NUMBER=11111111
```
This file contains your t:connect username and password, Tandem pump serial number (which is utilized in API calls to t:connect), your Nightscout URL and secret token (for uploading data to Nightscout), and local timezone (the timezone used in t:connect).
This file contains your t:connect username and password, Tandem pump serial number (which is utilized in API calls to t:connect), your Nightscout URL and secret token (for uploading data to Nightscout), and local timezone (the timezone used in t:connect). When specifying the timezone, enter a [TZ database name value](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones).
(Alternatively, these values can be specified via environment variables.)
@@ -84,16 +117,27 @@ First, ensure that you have **Python 3** with **Pip** installed:
* **On MacOS:** Open Terminal. Install [Homebrew](https://brew.sh/), and then run `brew install python3`
* **On Linux:** Follow your distribution's specific instructions.
For Debian/Ubuntu based distros, `sudo apt install python3 python3-pip`
* **On Windows:** Install Ubuntu under the [Windows Subsystem for Linux](https://ubuntu.com/wsl).
Open the Ubuntu Terminal, then run `sudo apt install python3 python3-pip`.
Perform the remainder of the steps under the Ubuntu environment.
- For Debian/Ubuntu based distros, `sudo apt install python3 python3-pip`
- For CentOS/Rocky Linux 8:
- `sudo dnf install python39-pip`
- `sudo alternatives --set python /usr/bin/python3.9`
* **On Windows:**
- **With WSL:** Install Ubuntu under the [Windows Subsystem for Linux](https://ubuntu.com/wsl).
Open the Ubuntu Terminal, then run `sudo apt install python3 python3-pip`.
Perform the remainder of the steps under the Ubuntu environment.
- **Native:** Alternatively, you can run tconnectsync in native Windows with no modifications. However, this is less well-tested (open a GitHub issue if you experience any problems).
Now install the `tconnectsync` package with pip:
```
$ pip3 install tconnectsync
```
To install into a user environment instead of system-wide for a more contained install:
````
$ pip3 install --user tconnectsync
````
- This will place the tconnectsync binary file at ``/home/<username>/.local/bin/tconnectsync``
- For non-WSL Windows, it will be in ``<PYTHON DIRECTORY>\Lib\site-packages\tconnectsync``
If the pip3 command is not found, run `python3 -m pip install tconnectsync` instead.
@@ -124,7 +168,7 @@ Move the `.env` file you created to the following folder:
* **MacOS:** `/Users/<username>/.config/tconnectsync/.env`
* **Linux:** `$HOME/.config/tconnectsync/.env`
* **Windows:** `$HOME/.config/tconnectsync/.env` (inside WSL)
* **Windows:** `$HOME/.config/tconnectsync/.env` (inside WSL) OR `C:\Users\<username>\.config\tconnectsync` (native Windows)
```
$ tconnectsync --check-login
@@ -215,9 +259,11 @@ $ docker run tconnectsync --help
Move the `.env` file you created earlier into this folder, and run:
```
$ docker run tconnectsync --check-login
$ docker run --env-file=.env tconnectsync --check-login
```
**NOTE:** If using the `--env-file` option to `docker run`, you may need to remove all quotation marks (`'` and `"`s) around values in the `.env` file for Docker to propagate the variables correctly.
If you receive no errors, then you can move on to the **Running Tconnectsync Continuously** section.
## Running Tconnectsync Continuously
@@ -335,6 +381,36 @@ An example `run.sh` if you built tconnectsync locally:
docker run tconnectsync --auto-update
```
#### Tuning Auto-Update
These optional environment variables control how `--auto-update` polls and how
it behaves when things go wrong. The defaults are sensible; you generally only
need these if you are seeing too many (or too few) restarts.
| Variable | Default | What it does |
| --- | --- | --- |
| `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` | `300` | Poll interval when no better estimate is available. Also the ceiling for the retry backoff below. |
| `AUTOUPDATE_MAX_SLEEP_SECONDS` | `1500` | Upper bound on the adaptive poll interval, regardless of how rarely new data appears. |
| `AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS` | `60` | How long to wait when new data is overdue based on the pump's previous cadence. |
| `AUTOUPDATE_USE_FIXED_SLEEP` | `false` | Set true to always sleep `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` instead of adapting to the pump's observed upload cadence. |
| `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. |
| `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. |
| `AUTOUPDATE_FAILURE_MINUTES` | `75` | Log an error if events are appearing but no data has synced successfully for this long. |
| `AUTOUPDATE_RESTART_ON_FAILURE` | `false` | Whether the two watchdogs above also exit non-zero. Independent of `AUTOUPDATE_API_FAILURE_MINUTES`. |
| `AUTOUPDATE_MAX_LOOP_INVOCATIONS` | `-1` | Stop after this many poll cycles. `-1` means run forever; mainly useful for testing. |
**On failures and restarts.** Transient errors (DNS blips, timeouts, HTTP 404/502/503
from Tandem) do not crash tconnectsync. It retries with a growing backoff — 30s,
60s, 120s, 240s, then holding at `AUTOUPDATE_DEFAULT_SLEEP_SECONDS` — and resets
as soon as a poll succeeds. Staying in-process matters: an exit discards the
cached credentials, so a restart loop means a fresh login on every attempt,
which risks tripping Tandem's rate limiting.
Only once the API has been failing continuously for `AUTOUPDATE_API_FAILURE_MINUTES`
does tconnectsync give up and exit, so that a genuine outage surfaces (roughly one
restart per hour) instead of disappearing into an endless quiet retry. Invalid
credentials are never retried — they exit immediately, since retrying cannot help.
### Running with Cron
If you choose not to run tconnectsync with `--auto-update` continuously,
@@ -343,24 +419,41 @@ invoking tconnectsync with no arguments via cron.
If using Pipenv or a virtualenv, make sure that you either prefix the call to main.py with `pipenv run` or source the `bin/activate` file within the virtualenv, so that the proper dependencies are loaded. If not using any kind of virtualenv, you can instead just install the necessary dependencies as specified inside Pipfile globally.
An example configuration in `/etc/crontab` which runs every 15 minutes:
An system-wide example configuration in `/etc/crontab` which runs every 15 minutes, on the 15 minute mark:
```bash
# m h dom mon dow user command
0,15,30,45 * * * * root /path/to/tconnectsync/run.sh
```
An example of a user crontab `crontab -e` if not running system-wide, which runs every 15 minutes:
```
*/15 * * * * /path/to/tconnectsync/run.sh
```
You can use one of the same `run.sh` files referenced above, but remove the `--auto-update` flag since you are handling the functionality for running the script periodically yourself.
### For Native Windows
Create a batch file 'tconnectsync.bat' file containing:
```
python "C:\Users\<USERNAME>\AppData\Local\Programs\Python\<PYTHONVERSIONDIRECTORY>\Lib\site-packages\tconnectsync\main.py" --auto-update
```
If `python` does not exist in your path, specify the full path to `python.exe`.
If main.py doesn't exist in `C:\Users\<USERNAME>\AppData\Local\Programs\Python\<PYTHONVERSIONDIRECTORY>\Lib\site-packages\tconnectsync\`, create it to match the copy in this repository.
[Use Windows Task Scheduler](https://www.windowscentral.com/how-create-automated-task-using-task-scheduler-windows-10) to run this batch file on a scheduled basis.
## Tandem APIs
This application utilizes three separate Tandem APIs for obtaining t:connect data, referenced here by the identifying part of their URLs:
As of version 2.0, tconnectsync retrieves all of its data from a single Tandem API, [**tandemsource**](https://github.com/jwoglom/tconnectsync/blob/master/tconnectsync/api/tandemsource.py), which powers [Tandem Source](https://source.tandemdiabetes.com/). After logging in, tconnectsync fetches the list of pumps on the account along with a stream of raw pump event data, which is decoded locally (see [`tconnectsync/eventparser`](https://github.com/jwoglom/tconnectsync/tree/master/tconnectsync/eventparser)) to extract basal, bolus, CGM, and other pump events.
* [**controliq**](https://github.com/jwoglom/tconnectsync/blob/master/tconnectsync/api/controliq.py) - Contains Control:IQ related data, namely a timeline of all Basal events uploaded by the pump, separated by type (temp basals, algorithmically-updated basals, or profile-updated basals).
* [**android**](https://github.com/jwoglom/tconnectsync/blob/master/tconnectsync/api/android.py) - Used internally by the t:connect Android app, these API endpoints were discovered by reverse-engineering the Android app. Most of the API endpoints are used for uploading pump data, and tconnectsync uses one endpoint which returns the most recent event ID uploaded by the pump, so we know when more data has been uploaded.
* [**tconnectws2**](https://github.com/jwoglom/tconnectsync/blob/master/tconnectsync/api/ws2.py) - More legacy than the others, this seems to power the bulk of the main t:connect website. It is used to retrieve a CSV export of non-ControlIQ basal data, as well as bolus and IOB data. (I haven't found any mentions of bolus or IOB data in the Control:IQ-specific API.)
> Earlier versions of tconnectsync (1.x) instead used three separate legacy t:connect APIs (`controliq`, `android`, and `tconnectws2`). Those APIs — and the code supporting them — were removed once t:connect was shut down in favor of Tandem Source.
I have only tested tconnectsync with a Tandem pump set in the US Eastern timezone. Tandem's (to us, undocumented) APIs are [a bit loose with timezones](https://github.com/jwoglom/tconnectsync/blob/master/tconnectsync/parser.py#L15), so please let me know if you notice any timezone-related bugs.
I have only tested tconnectsync with a Tandem pump set in the US Eastern timezone. Tandem's (to us, undocumented) APIs are a bit loose with timezones, so please let me know if you notice any timezone-related bugs.
## Backfilling t:connect Data
To backfill existing t:connect data in to Nightscout, you can use the `--start-date` and `--end-date` options. For example, the following will upload all t:connect data between January 1st and March 1st, 2020 to Nightscout:
@@ -372,3 +465,15 @@ python3 main.py --start-date 2020-01-01 --end-date 2020-03-01
In order to bulk-import a lot of data, you may need to use shorter intervals, and invoke tconnectsync multiple times. Tandem's API endpoints occasionally return invalid data if you request too large of a data window which causes tconnectsync to error out mid-way through.
One oddity when backfilling data is that the Control:IQ specific API endpoints return errors if they are queried before you updated your pump to utilize Control:IQ. This is [partially worked around in tconnectsync's code](https://github.com/jwoglom/tconnectsync/blob/d841c3811aeff3671d941a7d3ff4b80cce6a219e/main.py#L238), but you might need to update the logic if you did not switch to a Control:IQ enabled pump immediately after launch.
## Tandem Source API Testing
To test Tandem Source API endpoints in a Python shell, you can do something like the following:
```python
import tconnectsync
tconnectsync.util.cli.enable_logging()
api = tconnectsync.util.cli.get_api()
# Make API calls, e.g.
pumps = api.tandemsource.pump_event_metadata()
```
+225
View File
@@ -0,0 +1,225 @@
#!/usr/bin/env python3
"""
Sync event definitions from Tandem's official webapp and regenerate event classes.
Extracts the complete events.json from the JSON.parse() statement embedded in
Tandem's reports module JavaScript, updates local events.json, and regenerates
events.py with all event class definitions.
Usage:
python3 scripts/sync_tandem_events.py [--output FILE] <URL>
Example:
python3 scripts/sync_tandem_events.py \\
https://modules.us.tandemdiabetes.com/webapp/modules/reports-module/v1.8.0/2451.97042bc1.chunk.js
"""
import sys
import json
import subprocess
import requests
from pathlib import Path
DEFAULT_EVENTS_FILE = "tconnectsync/eventparser/events.json"
DEFAULT_GENERATOR = "build_events.py"
def fetch_module(url):
"""Fetch the minified JavaScript module from Tandem."""
print(f"Fetching Tandem module...", file=sys.stderr)
response = requests.get(url, timeout=30)
response.raise_for_status()
content = response.text
print(f"Fetched {len(content):,} bytes", file=sys.stderr)
return content
def extract_events_json_from_parse(js_content):
"""
Extract the complete events.json from the JSON.parse() statement.
Finds: JSON.parse('{"events":{...}}')
And returns the parsed events dictionary.
"""
start = js_content.find("JSON.parse('")
if start < 0:
return None
start += len("JSON.parse('")
# Find the matching closing brace
brace_count = 0
end = start
escape_next = False
for i in range(start, len(js_content)):
char = js_content[i]
if escape_next:
escape_next = False
continue
if char == '\\':
escape_next = True
continue
if char == '{':
brace_count += 1
elif char == '}':
brace_count -= 1
if brace_count == 0:
end = i + 1
break
if brace_count != 0:
return None
json_str = js_content[start:end]
# Unescape the string
json_str = json_str.replace('\\"', '"')
try:
return json.loads(json_str)
except json.JSONDecodeError:
return None
def load_existing_events(filepath):
"""Load the existing events.json file."""
if not Path(filepath).exists():
return {"events": {}}
try:
with open(filepath, 'r') as f:
data = json.load(f)
print(f"Loaded {len(data.get('events', {}))} existing events", file=sys.stderr)
return data
except Exception as e:
print(f"Warning: Could not load existing events.json: {e}", file=sys.stderr)
return {"events": {}}
def merge_events(existing_data, extracted_data):
"""
Merge extracted events with existing events.
Keeps all existing events and updates/adds with extracted ones.
"""
existing = existing_data.get('events', {})
extracted = extracted_data.get('events', {})
before_count = len(existing)
# Add/update extracted events
existing.update(extracted)
after_count = len(existing)
added = after_count - before_count
if added > 0:
print(f"Added {added} new events from Tandem module", file=sys.stderr)
else:
print(f"Updated {len(extracted)} events from Tandem module", file=sys.stderr)
return existing_data
def write_events_file(filepath, data):
"""Write events.json with proper formatting."""
if 'events' in data:
data['events'] = {
k: data['events'][k]
for k in sorted(data['events'].keys(), key=lambda x: int(x))
}
filepath = Path(filepath)
filepath.parent.mkdir(parents=True, exist_ok=True)
with open(filepath, 'w') as f:
json.dump(data, f, indent=2)
print(f"Wrote {len(data.get('events', {}))} events to {filepath}", file=sys.stderr)
def regenerate_events_py(events_json_path, generator_name):
"""Regenerate events.py from updated events.json."""
events_dir = Path(events_json_path).parent
generator_path = events_dir / generator_name
if not generator_path.exists():
print(f"⚠ Generator not found at {generator_path}", file=sys.stderr)
return False
print(f"Regenerating events.py...", file=sys.stderr)
try:
result = subprocess.run(
[sys.executable, generator_name],
cwd=str(events_dir),
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
# Write generated code to events.py
events_py = events_dir / 'events.py'
events_py.write_text(result.stdout)
print(f"✓ events.py regenerated ({len(result.stdout):,} bytes)", file=sys.stderr)
return True
else:
print(f"✗ Generator failed: {result.stderr}", file=sys.stderr)
return False
except subprocess.TimeoutExpired:
print("✗ Generator timed out", file=sys.stderr)
return False
except Exception as e:
print(f"✗ Error running generator: {e}", file=sys.stderr)
return False
def main():
import argparse
parser = argparse.ArgumentParser(
description='Sync event definitions from Tandem and regenerate events.py'
)
parser.add_argument('url', help='URL to Tandem JavaScript module')
parser.add_argument('--output', default=DEFAULT_EVENTS_FILE, help='Output events.json path')
parser.add_argument('--no-generate', action='store_true', help='Skip events.py regeneration')
args = parser.parse_args()
try:
js_content = fetch_module(args.url)
extracted_data = extract_events_json_from_parse(js_content)
if not extracted_data:
print("✗ Could not extract events.json from Tandem module", file=sys.stderr)
sys.exit(1)
extracted_events = extracted_data.get('events', {})
print(f"✓ Extracted {len(extracted_events)} events from Tandem module", file=sys.stderr)
existing_data = load_existing_events(args.output)
merged_data = merge_events(existing_data, extracted_data)
write_events_file(args.output, merged_data)
if not args.no_generate:
regenerate_events_py(args.output, DEFAULT_GENERATOR)
print(f"\n✓ Done", file=sys.stderr)
except requests.exceptions.RequestException as e:
print(f"✗ Network error: {e}", file=sys.stderr)
sys.exit(1)
except Exception as e:
print(f"✗ Error: {e}", file=sys.stderr)
sys.exit(1)
if __name__ == '__main__':
main()
+25 -4
View File
@@ -1,9 +1,9 @@
[metadata]
name = tconnectsync
version = 0.6.2
author = James Woglom
version = 3.0.1
author = James Woglom
author_email = j@wogloms.net
description = Syncs Tandem t:connect pump data to Nightscout for the t:slim X2
description = Syncs Tandem Source (formerly t:connect) insulin pump data to Nightscout for the t:slim X2 and Tandem Mobi
long_description = file: README.md
long_description_content_type = text/markdown
url = https://github.com/jwoglom/tconnectsync
@@ -18,13 +18,25 @@ classifiers =
package_dir =
= .
packages = find:
python_requires = >=3.6
python_requires = >=3.7
install_requires =
requests
bs4
arrow
lxml
python-dotenv
requests-mock
pysocks
urllib3
requests
requests-oidc
PyJWT==2.8.0
cryptography==43.0.1; python_version < "3.9"
cryptography; python_version >= "3.9"
dataclasses-json
cffi
typing-extensions
importlib-metadata; python_version < "3.8"
[options.packages.find]
where = .
@@ -35,3 +47,12 @@ exclude =
[options.entry_points]
console_scripts =
tconnectsync = tconnectsync:main
[mypy]
files =
tconnectsync
follow_imports = silent
ignore_missing_imports = True
# Third-party deps such as requests ship no type stubs; treat them as untyped
# instead of failing (older mypy does not silence this via ignore_missing_imports).
disable_error_code = import-untyped
+58 -18
View File
@@ -3,11 +3,20 @@ import datetime
import arrow
import argparse
import logging
import pkg_resources
import typing
# Required for cryptography lib in python 3.7
if sys.version_info < (3, 8):
import typing_extensions
typing.Protocol = typing_extensions.Protocol
from importlib_metadata import PackageNotFoundError, version
else:
from importlib.metadata import PackageNotFoundError, version
from .api import TConnectApi
from .process import process_time_range
from .autoupdate import process_auto_update
from .sync.tandemsource.autoupdate import TandemSourceAutoupdate
from .sync.tandemsource.choose_device import ChooseDevice as TandemSourceChooseDevice
from .sync.tandemsource.process import ProcessTimeRange as TandemSourceProcessTimeRange
from .check import check_login
from .nightscout import NightscoutApi
from .features import DEFAULT_FEATURES, ALL_FEATURES
@@ -16,21 +25,26 @@ try:
from .secret import (
TCONNECT_EMAIL,
TCONNECT_PASSWORD,
TCONNECT_REGION,
NS_URL,
NS_SECRET
NS_SECRET,
NS_SKIP_TLS_VERIFY,
PUMP_SERIAL_NUMBER,
NS_IGNORE_CONN_ERRORS
)
except Exception:
print('Unable to read secret.py')
from . import secret
except Exception as e:
print('Unable to read secrets from secret.py', e)
sys.exit(1)
try:
__version__ = pkg_resources.require("tconnectsync")[0].version
except Exception:
__version__ = version("tconnectsync")
except PackageNotFoundError:
__version__ = "UNKNOWN"
def parse_args(*args, **kwargs):
parser = argparse.ArgumentParser(description="Syncs bolus, basal, and IOB data from Tandem Diabetes t:connect to Nightscout.")
parser = argparse.ArgumentParser(description="Syncs bolus, basal, and IOB data from Tandem Diabetes t:connect to Nightscout.", epilog="Version %s" % __version__)
parser.add_argument('--version', action='version', version='tconnectsync %s' % __version__)
parser.add_argument('--pretend', dest='pretend', action='store_const', const=True, default=False, help='Pretend mode: do not upload any data to Nightscout.')
parser.add_argument('-v', '--verbose', dest='verbose', action='store_const', const=True, default=False, help='Verbose mode: show extra logging details')
@@ -40,6 +54,8 @@ def parse_args(*args, **kwargs):
parser.add_argument('--auto-update', dest='auto_update', action='store_const', const=True, default=False, help='If set, continuously checks for updates from t:connect and syncs with Nightscout.')
parser.add_argument('--check-login', dest='check_login', action='store_const', const=True, default=False, help='If set, checks that the provided t:connect credentials can be used to log in.')
parser.add_argument('--features', dest='features', nargs='+', default=DEFAULT_FEATURES, choices=ALL_FEATURES, help='Specifies what data should be synchronized between tconnect and Nightscout.')
parser.add_argument('--tandem-source', dest='tandem_source', action='store_const', const=True, default=True, help=argparse.SUPPRESS) # no longer used
parser.add_argument('--region', dest='region', type=str, choices=['US', 'EU'], default=None, help='Tandem t:connect server region (US or EU). If not specified, uses TCONNECT_REGION from configuration or defaults to US.')
return parser.parse_args(*args, **kwargs)
@@ -71,20 +87,44 @@ def main(*args, **kwargs):
if time_end < time_start:
raise Exception('time_start must be before time_end')
tconnect = TConnectApi(TCONNECT_EMAIL, TCONNECT_PASSWORD)
# Determine region: command line arg takes precedence, then config, then default to US
region = args.region if args.region else TCONNECT_REGION
nightscout = NightscoutApi(NS_URL, NS_SECRET)
if TCONNECT_EMAIL == 'email@email.com':
logging.warn('NO USERNAME WAS PROVIDED. Ensure you have set TCONNECT_EMAIL appropriately.')
if TCONNECT_PASSWORD == 'password':
logging.warn('NO PASSWORD WAS PROVIDED. Ensure you have set TCONNECT_PASSWORD appropriately.')
if NS_URL == 'https://yournightscouturl/':
logging.warn('NO NIGHTSCOUT URL WAS PROVIDED. Ensure your have set NS_URL appropriately.')
if PUMP_SERIAL_NUMBER == '11111111':
if args.tandem_source:
secret.PUMP_SERIAL_NUMBER = None
else:
logging.warn('NO PUMP SERIAL NUMBER WAS PROVIDED. Ensure you have set PUMP_SERIAL_NUMBER appropriately.')
tconnect = TConnectApi(TCONNECT_EMAIL, TCONNECT_PASSWORD, region)
nightscout = NightscoutApi(NS_URL, NS_SECRET, skip_verify=NS_SKIP_TLS_VERIFY, ignore_conn_errors=NS_IGNORE_CONN_ERRORS)
if args.check_login:
return check_login(tconnect, time_start, time_end)
logging.warning("THIS VERSION OF TCONNECTSYNC READS DATA FROM TANDEM SOURCE, AND MAY CONTAIN BUGS!")
logging.info("You may notice different behavior compared to older versions which utilized t:connect data sources.")
logging.info("To report a bug or to get help, see https://github.com/jwoglom/tconnectsync/issues")
logging.info(f"Using Tandem t:connect region: {region}")
logging.info("Enabled features: " + ", ".join(args.features))
if args.auto_update:
print("Starting auto-update between", time_start, "and", time_end, "(PRETEND)" if args.pretend else "")
process_auto_update(tconnect, nightscout, time_start, time_end, args.pretend, features=args.features)
else:
print("Processing data between", time_start, "and", time_end, "(PRETEND)" if args.pretend else "")
added = process_time_range(tconnect, nightscout, time_start, time_end, args.pretend, features=args.features)
print("Added", added, "items")
if args.check_login:
args.pretend = True
if args.auto_update:
u = TandemSourceAutoupdate(secret)
sys.exit(u.process(tconnect, nightscout, args.pretend, features=args.features))
else:
tconnectDevice = TandemSourceChooseDevice(secret, tconnect).choose()
added, last_event_id = TandemSourceProcessTimeRange(tconnect, nightscout, tconnectDevice, pretend=args.pretend, secret=secret, features=args.features).process(time_start, time_end)
# return exit code 0 if processed events
sys.exit(0 if added>0 else 1)
+4
View File
@@ -0,0 +1,4 @@
from . import main
if __name__ == "__main__":
main()
+15 -41
View File
@@ -1,56 +1,30 @@
import logging
from .android import AndroidApi
from .controliq import ControlIQApi
from .ws2 import WS2Api
from .tandemsource import TandemSourceApi
from .. import secret
logger = logging.getLogger(__name__)
"""A wrapper for the three different t:connect API types."""
"""A wrapper for the Tandem Source API."""
class TConnectApi:
email = None
password = None
_ciq = None
_ws2 = None
_android = None
def __init__(self, email, password):
def __init__(self, email, password, region=None):
self.email = email
self.password = password
# A caller which does not pass a region (e.g. tconnectsync-heroku)
# must get the configured TCONNECT_REGION, not a hardcoded US
# default which would send EU accounts to the US endpoints (#152).
self.region = region or secret.TCONNECT_REGION
self._tandemsource = None
@property
def controliq(self):
if self._ciq and not self._ciq.needs_relogin():
return self._ciq
def tandemsource(self):
if self._tandemsource and not self._tandemsource.needs_relogin():
return self._tandemsource
logger.debug("Instantiating new ControlIQApi")
self._ciq = ControlIQApi(self.email, self.password)
return self._ciq
@property
def ws2(self):
if self._ws2:
return self._ws2
logger.debug("Instantiating new WS2Api")
# Trigger login or re-login via controliq api if necessary
# so userGuid can be accessed from it
self.controliq
self._ws2 = WS2Api(self._ciq.userGuid)
return self._ws2
@property
def android(self):
if self._android and not self._android.needs_relogin():
return self._android
logger.debug("Instantiating new AndroidApi")
self._android = AndroidApi(self.email, self.password)
return self._android
logger.debug(f"Instantiating new TandemSourceApi for region {self.region}")
self._tandemsource = TandemSourceApi(self.email, self.password, self.region)
return self._tandemsource
-169
View File
@@ -1,169 +0,0 @@
import requests
import json
import urllib
import datetime
import csv
import base64
import arrow
import time
import logging
from bs4 import BeautifulSoup
from ..util import timeago
from .common import ApiException, ApiLoginException, parse_date
logger = logging.getLogger(__name__)
"""
The AndroidApi class contains methods which are queried in the t:connect
Android application. These methods are a part of the tdc API which require
Android specific credentials.
"""
class AndroidApi:
BASE_URL = 'https://tdcservices.tandemdiabetes.com/'
OAUTH_TOKEN_PATH = 'cloud/oauth2/token'
OAUTH_SCOPES = 'cloud.account cloud.upload cloud.accepttcpp cloud.email cloud.password'
# These credentials are found in source code
ANDROID_API_USERNAME = base64.b64decode('QzIzMzFDRDYtRDQ1MC00OTVFLTlDMTktNjcyMTUyMzBDODVD').decode()
ANDROID_API_PASSWORD = base64.b64decode('dHo0MzNLVzVRREM5VjdmIXo2QF4ybyZZNlNHR1lo').decode()
# These tokens are separate from the "standard" tdcservices API
accessToken = None
accessTokenExpiresAt = None
refreshToken = None
refreshTokenExpiresAt = None
userId = None
patientObjectId = None
def __init__(self, email, password):
self.login(email, password)
self._email = email
self._password = password
def login(self, email, password):
r = requests.post(
self.BASE_URL + self.OAUTH_TOKEN_PATH,
{
'username': email,
'password': password,
'grant_type': 'password',
'scope': self.OAUTH_SCOPES
},
headers={'Content-Type': 'application/x-www-form-urlencoded'},
auth=requests.auth.HTTPBasicAuth(self.ANDROID_API_USERNAME, self.ANDROID_API_PASSWORD)
)
if r.status_code != 200:
raise ApiLoginException(r.status_code, 'Received HTTP %s during login: %s' % (r.status_code, r.text))
j = r.json()
if "user" not in j or not j["user"]:
raise ApiException(r.status_code, 'No user details present in AndroidApi oauth response: %s' % r.text)
self.accessToken = j["accessToken"]
self.accessTokenExpiresAt = j["accessTokenExpiresAt"]
# NOTE: the refresh token is currently unused, instead a new access
# token is obtained from scratch by re-logging in when it expires.
self.refreshToken = j["refreshToken"]
self.refreshTokenExpiresAt = j["refreshTokenExpiresAt"]
self.userId = j["user"]["id"]
logger.info("Logged in to AndroidApi successfully (expiration: %s, %s)" % (self.accessTokenExpiresAt, timeago(self.accessTokenExpiresAt)))
def needs_relogin(self):
diff = (arrow.get(self.accessTokenExpiresAt) - arrow.get())
return (diff.seconds <= 5 * 60)
def api_headers(self):
if not self.accessToken:
raise Exception('No access token')
return {'Authorization': 'Bearer %s' % self.accessToken}
def _get(self, endpoint, query={}, **kwargs):
r = requests.get(self.BASE_URL + endpoint, query, headers=self.api_headers(), **kwargs)
if r.status_code != 200:
raise ApiException(r.status_code, "Android API HTTP %s response: %s" % (str(r.status_code), r.text))
return r.json()
def get(self, endpoint, query={}, tries=0, **kwargs):
try:
return self._get(endpoint, query, **kwargs)
except ApiException as e:
if tries > 0:
raise ApiException(e.status_code, "Android API HTTP %s on retry #%d: %s" % (e.status_code, tries, e))
# Trigger automatic re-login, and try again once
if e.status_code == 401:
self.accessTokenExpiresAt = time.time()
self.login(self._email, self._password)
return self.get(endpoint, query, tries=tries+1, **kwargs)
if e.status_code == 500:
return self.get(endpoint, query, tries=tries+1, **kwargs)
raise e
def post(self, endpoint, query={}, **kwargs):
r = requests.post(self.BASE_URL + endpoint, query, headers=self.api_headers(), **kwargs)
if r.status_code != 200:
raise ApiException(r.status_code, "Internal API HTTP %s response: %s" % (str(r.status_code), r.text))
return r.json()
"""
Returns the most recent event ID that was uploaded for the given pump.
{'maxPumpEventIndex': <integer>, 'processingStatus': 1}
"""
def last_event_uploaded(self, pump_serial_number):
return self.get('cloud/upload/getlasteventuploaded?sn=%d' % pump_serial_number)
"""
Returns user login information about a tconnect account.
{'firstName': <string>, 'lastName': <string>, 'birthDate': 'YYYY-MM-DDT00:00:00.000Z',
'emailAddress': <string>, 'secretQuestion': <string>, 'secretAnswer': <string>,
'secretQuestionId': <integer>}
"""
def patient_info(self):
return self.get('cloud/account/patient_info')
# TODO: these methods are used in the web app, not the Android app,
# but support the same auth tokens and are on this domain. They should
# be moved to a new Api class.
"""
Returns BG and pump threshold values.
{'targetBGHigh': <integer>, 'targetBGLow': <integer>, 'hypoThreshold': <integer>,
'hyperThreshold': <integer>, 'siteChangeThreshold': <integer>,
'cartridgeChangeThreshold': <integer>, 'tubingChangeThreshold': <integer>}
"""
def therapy_thresholds(self):
return self.get('cloud/usersettings/api/therapythresholds?userId=%s' % self.userId)
"""
Returns therapy-related user information about a tconnect account.
{'userID': <string>, 'targetBgHigh': <integer>, 'targetBgLow': <integer>,
'hypoThreshold': <integer>, 'hyperThreshold': <integer>,
'dateOfBirth': 'YYYY-MM-DDT00:00:00', 'age': <integer>,
'patientFullName': <string>, 'caregiverDateOfBirth': <string>,
'hasCGM': <bool>, 'hasBASALIQ': <bool>, 'hasControlIQ': <bool>}
"""
def user_profile(self):
return self.get('cloud/usersettings/api/UserProfile?userId=%s' % self.userId)
"""
Returns therapy events, used by the webui Therapy Timeline.
{'event': [
{'type': 'Basal', 'basalRate': ...},
{'type': 'Bolus', 'standard': ...},
{'type': 'CGM', 'egv': ...}
]}
"""
def therapy_events(self, start_date=None, end_date=None):
startDate = parse_date(start_date)
endDate = parse_date(end_date)
return self.get('tconnect/therapyevents/api/TherapyEvents/%s/%s/false?userId=%s' % (startDate, endDate, self.userId))
+123 -2
View File
@@ -1,17 +1,138 @@
import datetime
from typing import List, Tuple
import requests
import random
import arrow
from tconnectsync import secret
def parse_date(date):
if type(date) == str:
return date
return (date or datetime.datetime.now()).strftime('%m-%d-%Y')
def parse_ymd_date(date):
if type(date) == str:
date = arrow.get(date)
return (date or datetime.datetime.now()).strftime('%Y-%m-%d')
def parsed_date_to_arrow(date):
return arrow.get(datetime.datetime.strptime(date, '%m-%d-%Y'))
USER_AGENTS = [
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.1 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.3 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.4 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.5 Safari/605.1.15',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:100.0) Gecko/20100101 Firefox/100.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:101.0) Gecko/20100101 Firefox/101.0',
'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:102.0) Gecko/20100101 Firefox/102.0',
'Mozilla/5.0 (Windows NT 10.0; rv:91.0) Gecko/20100101 Firefox/91.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 OPR/86.0.4363.64',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36 OPR/86.0.4363.70',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.54 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.47',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36 Edg/101.0.1210.53',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.67 Safari/537.36 OPR/87.0.4390.45',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.124 Safari/537.36 Edg/102.0.1245.41',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.124 Safari/537.36 Edg/102.0.1245.44',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.62 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.30',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.33',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.63 Safari/537.36 Edg/102.0.1245.39',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/99.0.4844.84 Safari/537.36 OPR/85.0.4341.71',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:102.0) Gecko/20100101 Firefox/102.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:91.0) Gecko/20100101 Firefox/91.0',
'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:99.0) Gecko/20100101 Firefox/99.0',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:100.0) Gecko/20100101 Firefox/100.0',
'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:101.0) Gecko/20100101 Firefox/101.0',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.41 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/101.0.4951.64 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.0.0 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.61 Safari/537.36',
'Mozilla/5.0 (X11; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:101.0) Gecko/20100101 Firefox/101.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:91.0) Gecko/20100101 Firefox/91.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:95.0) Gecko/20100101 Firefox/95.0',
'Mozilla/5.0 (X11; Linux x86_64; rv:99.0) Gecko/20100101 Firefox/99.0',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:100.0) Gecko/20100101 Firefox/100.0',
'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:101.0) Gecko/20100101 Firefox/101.0'
]
# Consistent for entire runtime
random_ua = random.choice(USER_AGENTS)
def base_headers():
return {'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/88.0.4324.182 Safari/537.36'}
return {'user-agent': random_ua}
def base_session():
s = requests.Session()
if secret.REQUESTS_PROXY:
def wrapped_request(self, *args, **kwargs):
if not kwargs:
kwargs = {}
kwargs['proxies'] = {
'http': secret.REQUESTS_PROXY,
'https': secret.REQUESTS_PROXY
}
return self._original_request(*args, **kwargs)
s._original_request = s.request
s.request = wrapped_request.__get__(s, requests.Session)
return s
def days_between(start, end) -> int:
diff = arrow.get(end) - arrow.get(start)
return diff.days
# both inclusive
def split_days_range(start_a, end_a, days: int = 5) -> List[Tuple[arrow.Arrow, arrow.Arrow]]:
ranges = []
start = arrow.get(start_a)
end = arrow.get(end_a)
cur_s = start
cur = start
while cur <= end:
if (cur - cur_s).days >= days-1:
ranges.append((cur_s, cur))
cur_s = cur + datetime.timedelta(days=1)
cur += datetime.timedelta(days=1)
if len(ranges) > 0 and (end - ranges[-1][-1]).days > 0:
ranges.append((cur_s, end))
return ranges
class ApiException(Exception):
def __init__(self, status_code, text, *args, **kwargs):
self.status_code = status_code
super().__init__('%s (HTTP %s)' % (text, status_code), *args, **kwargs)
super().__init__('%s%s' % (text, ' (HTTP %s)' % status_code if status_code else ''), *args, **kwargs)
class ApiLoginException(ApiException):
pass
-135
View File
@@ -1,135 +0,0 @@
import requests
import urllib
import datetime
import arrow
import time
import logging
from bs4 import BeautifulSoup
from ..util import timeago
from .common import parse_date, base_headers, ApiException, ApiLoginException
logger = logging.getLogger(__name__)
class ControlIQApi:
BASE_URL = 'https://tdcservices.tandemdiabetes.com/tconnect/controliq/api/'
LOGIN_URL = 'https://tconnect.tandemdiabetes.com/login.aspx?ReturnUrl=%2f'
userGuid = None
accessToken = None
accessTokenExpiresAt = None
def __init__(self, email, password):
self.login(email, password)
self._email = email
self._password = password
def login(self, email, password):
logger.info("Logging in to ControlIQApi...")
with requests.Session() as s:
initial = s.get(self.LOGIN_URL, headers=base_headers())
soup = BeautifulSoup(initial.content, features='lxml')
data = self._build_login_data(email, password, soup)
req = s.post(self.LOGIN_URL, data=data, headers={'Referer': self.LOGIN_URL, **base_headers()}, allow_redirects=False)
if req.status_code != 302:
raise ApiLoginException(req.status_code, 'Error logging in to t:connect. Check your login credentials.')
fwd = s.post(urllib.parse.urljoin(self.LOGIN_URL, req.headers['Location']), cookies=req.cookies, headers=base_headers())
if fwd.status_code != 200:
raise ApiException(fwd.status_code, 'Error retrieving t:connect login cookies.')
self.userGuid = req.cookies['UserGUID']
self.accessToken = req.cookies['accessToken']
self.accessTokenExpiresAt = req.cookies['accessTokenExpiresAt']
logger.info("Logged in to ControlIQApi successfully (expiration: %s, %s)" % (self.accessTokenExpiresAt, timeago(self.accessTokenExpiresAt)))
return True
def _build_login_data(self, email, password, soup):
return {
"__LASTFOCUS": "",
"__EVENTTARGET": "ctl00$ContentBody$LoginControl$linkLogin",
"__EVENTARGUMENT": "",
"__VIEWSTATE": soup.select_one("#__VIEWSTATE")["value"],
"__VIEWSTATEGENERATOR": soup.select_one("#__VIEWSTATEGENERATOR")["value"],
"__EVENTVALIDATION": soup.select_one("#__EVENTVALIDATION")["value"],
"ctl00$ContentBody$LoginControl$txtLoginEmailAddress": email,
"txtLoginEmailAddress_ClientState": '{"enabled":true,"emptyMessage":"","validationText":"%s","valueAsString":"%s","lastSetTextBoxValue":"%s"}' % (email, email, email),
"ctl00$ContentBody$LoginControl$txtLoginPassword": password,
"txtLoginPassword_ClientState": '{"enabled":true,"emptyMessage":"","validationText":"%s","valueAsString":"%s","lastSetTextBoxValue":"%s"}' % (password, password, password)
}
def needs_relogin(self):
diff = (arrow.get(self.accessTokenExpiresAt) - arrow.get())
return (diff.seconds <= 5 * 60)
def api_headers(self):
if not self.accessToken:
raise Exception('No access token provided')
return {'Authorization': 'Bearer %s' % self.accessToken, **base_headers()}
def _get(self, endpoint, query):
r = requests.get(self.BASE_URL + endpoint, query, headers=self.api_headers())
if r.status_code != 200:
raise ApiException(r.status_code, "ControlIQ API HTTP %s response: %s" % (str(r.status_code), r.text))
return r.json()
def get(self, endpoint, query, tries=0):
try:
return self._get(endpoint, query)
except ApiException as e:
logger.warning("Received ApiException in ControlIQApi with endpoint '%s' (tries %d): %s" % (endpoint, tries, e))
if tries > 0:
raise ApiException(e.status_code, "ControlIQ API HTTP %d on retry #%d: %s", e.status_code, tries, e)
# Trigger automatic re-login, and try again once
if e.status_code == 401:
logger.info("Performing automatic re-login after HTTP 401 for ControlIQApi")
self.accessTokenExpiresAt = time.time()
self.login(self._email, self._password)
return self.get(endpoint, query, tries=tries+1)
if e.status_code == 500:
return self.get(endpoint, query, tries=tries+1)
raise e
"""
Returns detailed basal event information and reasons for delivery suspension.
"""
def therapy_timeline(self, start=None, end=None):
startDate = parse_date(start)
endDate = parse_date(end)
return self.get('therapytimeline/users/%s' % (self.userGuid), {
"startDate": startDate,
"endDate": endDate
})
"""
Returns a summary of pump and cgm activity.
{'averageReading': <integer>, 'timeInUseMinutes': <integer>, 'controlIqSetToOffMinutes': <integer>,
'cgmInactiveMinutes': <integer>, 'pumpInactiveMinutes': <integer>, 'averageDailySleepMinutes': <integer>,
'weeklyExerciseEvents': <integer>, 'timeInUsePercent': <integer>, 'controlIqOffPercent': <integer>,
'cgmInactivePercent': <integer>, 'pumpInactivePercent': <integer>, 'totalDays': <integer>}
"""
def dashboard_summary(self, start, end):
startDate = parse_date(start)
endDate = parse_date(end)
return self.get('summary/users/%s' % (self.userGuid), {
"startDate": startDate,
"endDate": endDate
})
"""
Returns active account features, including the date when ControlIQ was enabled.
[{"serialNumber": "11111111", "features": {"controlIQ": {"feature": 1, "dateTimeFirstDetected": "YYYY-MM-DD:THH:MM:SS", "unixTimestamp": 1111111111}}}]
"""
def pumpfeatures(self):
return self.get('pumpfeatures/users/%s' % self.userGuid, {})
+707
View File
@@ -0,0 +1,707 @@
import urllib
import arrow
import time
import logging
import json
import base64
import hashlib
import os
import jwt
import pickle
from typing import Any, Dict, Iterator, List, Optional, Tuple
try:
from typing import TypedDict
except ImportError: # Python 3.7
from typing_extensions import TypedDict
from requests_oidc import make_auth_code_session
from requests_oidc.plugins import OSCachedPlugin
from requests_oidc.utils import ServerDetails
from requests_oauthlib import OAuth2Session
from jwt.algorithms import RSAAlgorithm
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from ..util import timeago, cap_length
from .common import parse_ymd_date, base_headers, base_session, ApiException, ApiLoginException
from .. import secret
from ..secret import CACHE_CREDENTIALS, CACHE_CREDENTIALS_PATH, TIMEZONE_NAME
from ..eventparser.generic import Events
logger = logging.getLogger(__name__)
def naive_local_to_utc(value: Optional[str]) -> Optional[str]:
"""Normalize a BFF pump-local naive wall-clock timestamp to a true UTC
ISO-8601 string.
The BFF sends maxDateOfEvents / availableDataRange.start with no tz
(e.g. "2022-02-16T22:45:58") even though they are the pump's local
wall-clock time. Downstream consumers parse them with arrow.get(...),
which assumes UTC, and compare against arrow.utcnow() / time.time()
(real UTC), so we shift them here by interpreting the naive value in the
configured TIMEZONE_NAME and converting to UTC. Values that already
carry a tz (defensive; not seen for these two fields) are passed
through unchanged so we never double-shift. None passes through as None
(never-uploaded pumps).
"""
if not value:
return value
# If the string already carries a tz (a trailing 'Z' or a +HH:MM /
# -HH:MM offset after the time portion), trust it and never double-shift.
# Otherwise it's a naive pump-local wall-clock value: interpret it in the
# configured TIMEZONE_NAME. (Per the BFF data these two fields are always
# naive; the has-tz branch is purely defensive.)
time_part = value.split('T', 1)[-1]
has_tz = value.endswith('Z') or '+' in time_part or '-' in time_part
if has_tz:
parsed = arrow.get(value)
else:
parsed = arrow.get(value, tzinfo=TIMEZONE_NAME)
return parsed.to('UTC').isoformat()
class JwtClaims(TypedDict, total=False):
"""Decoded OIDC id_token claims stored on TandemSourceApi.jwtData.
pumperId and accountId are UUID strings (not ints); the *time/iat/exp/nbf
fields are unix timestamps.
"""
iss: str
nbf: int
iat: int
exp: int
aud: str
amr: List[str]
at_hash: str
sid: str
sub: str
auth_time: int
idp: str
email: str
tandem_roles: List[str]
roles: List[str]
accountId: str
pumperId: str
countrySubdivision: str
preferredLanguage: str
family_name: str
given_name: str
preferred_username: str
name: str
email_verified: bool
class AvailableDataRange(TypedDict):
"""`availableDataRange` on a BffPump. start/end are ISO-8601 datetime
strings, or null for a pump that has never uploaded."""
start: Optional[str]
end: Optional[str]
class PumpSettingsEnvelope(TypedDict):
"""`settings` on a BffPump. `details` is the full pump settings blob,
parsed by tconnectsync.domain.tandemsource.pump_settings.PumpSettings."""
id: str
deviceAssignmentId: str
uploadedTimeStamp: str
settingsHash: str
uploadId: str
details: dict
class BffPumpRequired(TypedDict):
"""Fields always present on a BffPump, even for a never-uploaded pump
(verified against a real captured GET api/reports/bff/pumper/{pumperId}
response).
`assignmentId` is the pump's UUID device id used as the path segment for
the pump-logs endpoint (replaces the old numeric tconnectDeviceId).
"""
assignmentId: str
serialNumber: str
modelNumber: str
modelName: str
softwareVersion: str
class BffPump(BffPumpRequired, total=False):
"""One element of BffPumper.pumps, from GET api/reports/bff/pumper/{pumperId}.
Extends BffPumpRequired with fields that are null or absent for
never-uploaded or retired pumps (settings, *Date*, lastUploadClientType,
glucoseUnit, availableDataRange.start/end), hence total=False. `algorithm`
is optional in the canonical BFF source (PumpAlgorithm | undefined) and so
must be accessed defensively.
"""
algorithm: Optional[str]
availableDataRange: AvailableDataRange
glucoseUnit: Optional[str]
lastUploadDate: Optional[str]
maxDateOfEvents: Optional[str]
partNumber: str
lastUploadClientType: Optional[str]
settings: Optional[PumpSettingsEnvelope]
class BffPumper(TypedDict, total=False):
"""Response of GET api/reports/bff/pumper/{pumperId} (the BFF device list
that replaces pumpeventmetadata)."""
firstName: str
lastName: str
name: str
dateOfBirth: str
lowGlucoseThreshold: int
highGlucoseThreshold: int
country: str
pumps: List[BffPump]
class PumpLogEvent(TypedDict):
"""One entry in a PumpLogsResponse (events[] or clockChanges[]) from
GET api/reports/bff/pump-logs/{deviceAssignmentId}. The server pre-decodes
each event, so eventProperties holds already-decoded per-event fields
(values are int/float/list/str keyed by camelCase field name).
pumpDateTime is the pump's local wall-clock time (ISO-8601, no tz);
estimatedDateTime is the same value with a 'Z' suffix. eventCode matches
the numeric event id in EVENT_IDS; sequenceNumber is the old seqNum.
"""
deviceAssignmentId: str
eventCode: int
sequenceGroup: int
sequenceNumber: int
pumpDateTime: str
eventProperties: Dict[str, Any]
estimatedDateTime: str
class PumpLogsResponse(TypedDict):
"""Response of GET api/reports/bff/pump-logs/{deviceAssignmentId}. Replaces
the old base64 reportsfacade/pumpevents payload. clockChanges (eventCodes
13/14) are returned separately and span the device's full history."""
events: List[PumpLogEvent]
clockChanges: List[PumpLogEvent]
class TandemSourceApi:
# Common URLs that are shared between regions
LOGIN_PAGE_URL = 'https://sso.tandemdiabetes.com/'
TDC_AUTH_CALLBACK_URL = 'https://sso.tandemdiabetes.com/auth/callback'
# US Region URLs (default)
_US_URLS = {
'LOGIN_API_URL': 'https://tdcservices.tandemdiabetes.com/accounts/api/login',
'TDC_OAUTH_AUTHORIZE_URL': 'https://tdcservices.tandemdiabetes.com/accounts/api/oauth2/v1/authorize',
'TDC_OIDC_JWKS_URL': 'https://tdcservices.tandemdiabetes.com/accounts/api/.well-known/openid-configuration/jwks',
'TDC_OIDC_ISSUER': 'https://tdcservices.tandemdiabetes.com/accounts/api',
'TDC_OIDC_CLIENT_ID': '0oa4wnbvtladeyVZX4h7',
'SOURCE_URL': 'https://source.tandemdiabetes.com/',
'REDIRECT_URI': 'https://sso.tandemdiabetes.com/auth/callback',
'TOKEN_ENDPOINT': 'https://tdcservices.tandemdiabetes.com/accounts/api/connect/token',
'AUTHORIZATION_ENDPOINT': 'https://tdcservices.tandemdiabetes.com/accounts/api/connect/authorize'
}
# EU Region URLs
_EU_URLS = {
'LOGIN_API_URL': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api/login',
'TDC_OAUTH_AUTHORIZE_URL': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api/oauth2/v1/authorize',
'TDC_OIDC_JWKS_URL': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api/.well-known/openid-configuration/jwks',
'TDC_OIDC_ISSUER': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api',
'TDC_OIDC_CLIENT_ID': '1519e414-eeec-492e-8c5e-97bea4815a10',
'SOURCE_URL': 'https://source.eu.tandemdiabetes.com/',
'REDIRECT_URI': 'https://source.eu.tandemdiabetes.com/authorize/callback',
'TOKEN_ENDPOINT': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api/connect/token',
'AUTHORIZATION_ENDPOINT': 'https://tdcservices.eu.tandemdiabetes.com/accounts/api/connect/authorize'
}
def __init__(self, email: str, password: str, region: Optional[str] = None) -> None:
# No region means "use the configured TCONNECT_REGION": a hardcoded
# US default would send EU accounts to the US endpoints (#152).
if not region:
region = secret.TCONNECT_REGION
if not region:
raise ValueError("No region configured. Set TCONNECT_REGION to 'US' or 'EU'.")
self.region = region.upper()
if self.region not in ['US', 'EU']:
raise ValueError(f"Invalid region '{region}'. Must be 'US' or 'EU'.")
self._region_urls = self._US_URLS if self.region == 'US' else self._EU_URLS
self.login(email, password)
self._email = email
self._password = password
@property
def LOGIN_API_URL(self) -> str:
return self._region_urls['LOGIN_API_URL']
@property
def TDC_OAUTH_AUTHORIZE_URL(self) -> str:
return self._region_urls['TDC_OAUTH_AUTHORIZE_URL']
@property
def TDC_OIDC_JWKS_URL(self) -> str:
return self._region_urls['TDC_OIDC_JWKS_URL']
@property
def TDC_OIDC_ISSUER(self) -> str:
return self._region_urls['TDC_OIDC_ISSUER']
@property
def TDC_OIDC_CLIENT_ID(self) -> str:
return self._region_urls['TDC_OIDC_CLIENT_ID']
@property
def SOURCE_URL(self) -> str:
return self._region_urls['SOURCE_URL']
def login(self, email: str, password: str) -> bool:
logger.info(f"Logging in to TandemSourceApi ({self.region} region)...")
if self.try_load_cached_creds(email):
logger.info("Successfully used cached credentials")
return True
with base_session() as s:
initial = s.get(self.LOGIN_PAGE_URL, headers=base_headers())
data = {
"username": email,
"password": password
}
req = s.post(self.LOGIN_API_URL, json=data, headers={'Referer': self.LOGIN_PAGE_URL, **base_headers()}, allow_redirects=False)
logger.debug("1. made POST to LOGIN_API")
# {"redirectUrl":"/","status":"SUCCESS"}
if req.status_code != 200:
raise ApiException(req.status_code, 'Error sending POST to login_api_url: %s' % req.text)
req_json = req.json()
login_ok = req_json.get('status', '') == 'SUCCESS'
if not login_ok:
raise ApiException(req.status_code, 'Error parsing login_api_url: %s' % json.dumps(req_json))
logger.debug("2. starting OIDC")
# oidc
client_id = self.TDC_OIDC_CLIENT_ID
redirect_uri = self._region_urls['REDIRECT_URI']
scope = 'openid profile email'
token_endpoint = self._region_urls['TOKEN_ENDPOINT']
def generate_code_verifier() -> str:
"""Generates a high-entropy code verifier."""
code_verifier = base64.urlsafe_b64encode(os.urandom(64)).decode('utf-8').rstrip('=')
return code_verifier
def generate_code_challenge(verifier: str) -> str:
"""Generates a code challenge from the code verifier."""
sha256_digest = hashlib.sha256(verifier.encode('utf-8')).digest()
code_challenge = base64.urlsafe_b64encode(sha256_digest).decode('utf-8').rstrip('=')
return code_challenge
code_verifier = generate_code_verifier()
code_challenge = generate_code_challenge(code_verifier)
authorization_endpoint = self._region_urls['AUTHORIZATION_ENDPOINT']
oidc_step1_params = {
'client_id': client_id,
'response_type': 'code',
'scope': scope,
'redirect_uri': redirect_uri,
'code_challenge': code_challenge,
'code_challenge_method': 'S256',
}
logger.debug("3. calling oidc_step1 with %s" % json.dumps(oidc_step1_params))
oidc_step1 = s.get(
authorization_endpoint + '?' + urllib.parse.urlencode(oidc_step1_params),
headers={'Referer': self.LOGIN_PAGE_URL, **base_headers()},
allow_redirects=True
)
if oidc_step1.status_code // 100 != 2:
raise ApiException(oidc_step1.status_code, 'Got unexpected status code for oidc step1: %s' % oidc_step1.text)
oidc_step1_loc = oidc_step1.url
oidc_step1_query = urllib.parse.parse_qs(urllib.parse.urlparse(oidc_step1_loc).query)
if 'code' not in oidc_step1_query:
raise ApiException(oidc_step1.status_code, 'No code for oidc step1 ReturnUrl (%s): %s' % (oidc_step1_loc, json.dumps(oidc_step1_query)))
oidc_step1_callback_code = oidc_step1_query['code'][0]
oidc_step2_token_data = {
'grant_type': 'authorization_code',
'client_id': client_id,
'code': oidc_step1_callback_code,
'redirect_uri': redirect_uri,
'code_verifier': code_verifier,
}
logger.debug("4. calling oidc_step2 with %s" % json.dumps(oidc_step2_token_data))
oidc_step2 = s.post(token_endpoint, data=oidc_step2_token_data, headers={
'Content-Type': 'application/x-www-form-urlencoded',
**base_headers()
})
if oidc_step2.status_code//100 != 2:
raise ApiException(oidc_step1.status_code, 'Got unexpected status code for oidc step2: %s' % oidc_step1.text)
oidc_json = oidc_step2.json()
logger.debug("5. parsing oidc_step2 json response: %s" % json.dumps(oidc_json))
if not 'access_token' in oidc_json:
raise ApiException(oidc_step1.status_code, 'Missing access_token in oidc_step2 json: %s' % json.dumps(oidc_json))
if not 'id_token' in oidc_json:
raise ApiException(oidc_step1.status_code, 'Missing id_token in oidc_step2 json: %s' % json.dumps(oidc_json))
self.loginSession = s
self.idToken = oidc_json['id_token']
self.extract_jwt()
self.accessToken = oidc_json['access_token']
self.accessTokenExpiresAt = arrow.get(arrow.get().int_timestamp + oidc_json['expires_in'])
self.cache_creds(email)
return True
def extract_jwt(self) -> None:
logger.debug("6. extracting JWT from %s" % self.idToken)
id_token = self.idToken
jwks_response = self.loginSession.get(self.TDC_OIDC_JWKS_URL)
jwks = jwks_response.json()
public_keys = {}
for jwk in jwks['keys']:
kid = jwk['kid']
public_keys[kid] = RSAAlgorithm.from_jwk(json.dumps(jwk))
# Get the key ID (kid) from the headers of the ID Token
unverified_header = jwt.get_unverified_header(id_token)
kid = unverified_header['kid']
key = public_keys.get(kid)
if not key:
raise ApiException(0, 'Public key not found for JWT: %s' % kid)
# A JWKS endpoint publishes public keys; from_jwk() is typed as possibly
# returning a private key, so narrow it before passing to jwt.decode().
if not isinstance(key, RSAPublicKey):
raise ApiException(0, 'JWK is not an RSA public key for JWT: %s' % kid)
audience = self.TDC_OIDC_CLIENT_ID
issuer = self.TDC_OIDC_ISSUER
# Decode and verify the ID Token. Per OIDC the id_token's `aud` equals
# the client_id, so validate it. But if Tandem ever issues an id_token
# with a different audience, fall back to skipping only the audience
# check (signature + issuer are still verified) rather than failing
# login outright.
id_token_claims: JwtClaims
try:
id_token_claims = jwt.decode(
id_token,
key=key,
algorithms=['RS256'],
audience=audience,
issuer=issuer,
)
except jwt.InvalidAudienceError:
logger.warning(
"id_token audience did not match client_id %s; decoding without audience verification",
audience,
)
id_token_claims = jwt.decode(
id_token,
key=key,
algorithms=['RS256'],
issuer=issuer,
options={"verify_aud": False},
)
logger.info("Decoded JWT: %s" % json.dumps(id_token_claims))
self.jwtData: JwtClaims = id_token_claims
self.pumperId: str = id_token_claims['pumperId']
self.accountId: str = id_token_claims['accountId']
def try_load_cached_creds(self, email: str) -> bool:
if not CACHE_CREDENTIALS:
return False
if not os.path.exists(CACHE_CREDENTIALS_PATH):
logger.info("No cached credentials exist")
return False
_saved_blob = {}
try:
with open(CACHE_CREDENTIALS_PATH, 'rb') as f:
_saved_blob = pickle.load(f)
except Exception as e:
logger.warning(f"Could not load cached credentials at {CACHE_CREDENTIALS_PATH}: {e}")
return False
if not _saved_blob:
logger.warning(f"Could not load cached credentials at {CACHE_CREDENTIALS_PATH}: empty dict")
return False
if _saved_blob.get('cache_creds_version') != 1.0:
logger.warning(f"Unexpected cache_creds_version at {CACHE_CREDENTIALS_PATH}: {_saved_blob['cache_creds_version']}, expected 1.0")
return False
if _saved_blob.get('cache_creds_email') != email:
logger.warning(f"Cached credentials are for a different email ({_saved_blob['cache_creds_email']} in cache, but using {email}), skipping")
return False
# Check if cached region matches current region
cached_region = _saved_blob.get('cache_creds_region', 'US') # Default to US for backward compatibility
if cached_region != self.region:
logger.warning(f"Cached credentials are for a different region ({cached_region} in cache, but using {self.region}), skipping")
return False
at_expiry = _saved_blob['accessTokenExpiresAt']
if arrow.get().int_timestamp >= arrow.get(at_expiry).int_timestamp:
logger.info(f"Cached credentials have expired ({_saved_blob['accessTokenExpiresAt']}), skipping")
return False
self.jwtData = _saved_blob['jwtData']
self.pumperId = _saved_blob['pumperId']
self.accountId = _saved_blob['accountId']
self.idToken = _saved_blob['idToken']
self.accessToken = _saved_blob['accessToken']
self.accessTokenExpiresAt = _saved_blob['accessTokenExpiresAt']
self.loginSession = _saved_blob['loginSession']
def est_time(t: arrow.Arrow) -> str:
now = arrow.get()
if now < t:
sec = (t - now).seconds
else:
sec = (now - t).seconds
min = sec//60
hr = min//60
min = min % 60
sec = sec % 60
r = ''
if hr:
r += f'{hr} hr '
if min:
r += f'{min} min '
if sec:
r += f'{sec} sec '
if not r:
return 'now'
elif now < t:
return 'in '+r.strip()
else:
return r.strip()+' ago'
sa = _saved_blob['cache_creds_saved_at']
ex = _saved_blob['accessTokenExpiresAt']
logger.info(f"Loaded cached credentials from {CACHE_CREDENTIALS_PATH}: saved at {sa} ({est_time(sa)}), access token expiry {ex} ({est_time(ex)})")
return True
def cache_creds(self, email: str) -> None:
if not CACHE_CREDENTIALS:
logger.info("Credentials caching is disabled, skipping save")
return
_saved_blob = {
'cache_creds_version': 1.0,
'cache_creds_saved_at': arrow.get(),
'cache_creds_email': email,
'cache_creds_region': self.region, # Store the region in cache
'jwtData': self.jwtData,
'pumperId': self.pumperId,
'accountId': self.accountId,
'idToken': self.idToken,
'accessToken': self.accessToken,
'accessTokenExpiresAt': self.accessTokenExpiresAt,
'loginSession': self.loginSession
}
if not os.path.exists(CACHE_CREDENTIALS_PATH):
mkdir = os.path.dirname(CACHE_CREDENTIALS_PATH)
logger.debug(f"Running mkdir on {mkdir}")
os.makedirs(mkdir, exist_ok=True)
with open(CACHE_CREDENTIALS_PATH, 'wb') as f:
pickle.dump(_saved_blob, f)
logger.info(f"Saved cached credentials to {CACHE_CREDENTIALS_PATH}")
def needs_relogin(self) -> bool:
if not self.accessTokenExpiresAt:
return False
diff = (arrow.get(self.accessTokenExpiresAt) - arrow.get())
return (diff.seconds <= 5 * 60)
def api_headers(self) -> Dict[str, str]:
if not self.accessToken:
raise Exception('No access token provided')
return {
'Authorization': 'Bearer %s' % self.accessToken,
# The WAF enforces same-origin: Origin/Referer must match SOURCE_URL
# (source.tandemdiabetes.com / source.eu.tandemdiabetes.com), otherwise
# it returns HTTP 403 ("The request is blocked").
'Origin': self.SOURCE_URL.rstrip('/'),
'Referer': self.SOURCE_URL,
**base_headers()
}
def _get(self, endpoint: str, query: dict) -> Any:
r = base_session().get(self.SOURCE_URL + endpoint, data=query, headers=self.api_headers())
if r.status_code != 200:
raise ApiException(r.status_code, "TandemSourceApi HTTP %s response: %s" % (str(r.status_code), r.text))
return r.json()
def get(self, endpoint: str, query: dict, tries: int = 0) -> Any:
try:
return self._get(endpoint, query)
except ApiException as e:
logger.warning("Received ApiException in TandemSourceApi with endpoint '%s' (tries %d): %s" % (endpoint, tries, e))
if tries > 0:
raise ApiException(e.status_code, "TandemSourceApi HTTP %d on retry #%d: %s", e.status_code, tries, e)
# Trigger automatic re-login, and try again once
if e.status_code == 401:
logger.info("Performing automatic re-login after HTTP 401 for TandemSourceApi")
self.accessTokenExpiresAt = arrow.get()
self.login(self._email, self._password)
return self.get(endpoint, query, tries=tries+1)
if e.status_code == 500:
return self.get(endpoint, query, tries=tries+1)
raise e
"""
Returns information about the user and available pumps.
"""
# Response shape is undocumented and unused by callers, so it stays Any.
def pumper_info(self) -> Any:
return self.get('api/pumpers/pumpers/%s' % (self.pumperId), {})
def get_pumper(self) -> BffPumper:
"""Returns the pumper's profile plus the list of pumps on the account
(BffPumper.pumps) from the new BFF endpoint. Replaces the old
reportsfacade pump-event-metadata endpoint: pumps[].assignmentId is the
UUID device id used by the pump-logs endpoint, and
pumps[].settings.details carries the pump settings blob."""
return self.get('api/reports/bff/pumper/%s' % (self.pumperId), {})
# Matches the Tandem Source web app's getLogIDList() (55 IDs) as observed in
# the live GET api/reports/bff/pump-logs request. Includes FSL3 ids 477/480/486.
DEFAULT_EVENT_IDS: List[int] = [229,5,28,4,26,99,279,3,16,59,21,55,20,280,64,65,66,61,33,371,171,369,460,172,370,461,372,480,399,256,213,406,477,394,212,404,214,405,486,447,313,60,14,6,90,230,140,12,11,53,13,63,203,307,191]
def get_pump_logs(self, device_id: str, min_date: Optional[str] = None, max_date: Optional[str] = None, event_ids_filter: Optional[List[int]] = DEFAULT_EVENT_IDS) -> PumpLogsResponse:
"""Fetch pre-decoded pump events for a single date window from the BFF
endpoint GET api/reports/bff/pump-logs/{device_id}. device_id is the
UUID assignmentId (BffPump.assignmentId from get_pumper()). Returns
{events, clockChanges}.
The server caps the window at ~4 weeks; callers needing a longer range
must page by date window (see pump_events).
Note: the server currently ignores eventIds and returns every event in
the window regardless of the filter (verified against live accounts), so
the effective filtering happens client-side via EventClass dispatch. We
still send eventIds to mirror the web app and stay forward-compatible."""
minDate = parse_ymd_date(min_date)
maxDate = parse_ymd_date(max_date)
logger.debug(f'get_pump_logs({device_id}, {minDate}, {maxDate})')
query = urllib.parse.urlencode({
'pumperId': self.pumperId,
'startDate': '%sT00:00:00Z' % minDate,
'endDate': '%sT23:59:59Z' % maxDate,
'eventIds': ','.join(map(str, event_ids_filter)) if event_ids_filter else '',
})
return self.get('api/reports/bff/pump-logs/%s?%s' % (device_id, query), {})
# The pump-logs endpoint caps each request at roughly four weeks, so a
# longer range is paged in windows no larger than this.
PUMP_LOGS_WINDOW_DAYS = 28
@classmethod
def _pump_log_windows(cls, min_date: Optional[str], max_date: Optional[str]) -> List[Tuple[str, str]]:
"""Split the (min_date, max_date) range into inclusive date windows no
larger than PUMP_LOGS_WINDOW_DAYS. A None bound defaults to today (via
parse_ymd_date), so an unset range yields a single one-day window."""
start = arrow.get(parse_ymd_date(min_date))
end = arrow.get(parse_ymd_date(max_date))
if end < start:
start, end = end, start
windows = []
cur = start
while cur <= end:
win_end = min(cur.shift(days=cls.PUMP_LOGS_WINDOW_DAYS - 1), end)
windows.append((cur.format('YYYY-MM-DD'), win_end.format('YYYY-MM-DD')))
cur = win_end.shift(days=1)
return windows
"""
Fetch and parse pump events from the pump-logs endpoint.
Default of fetch_all_event_types=False will filter to the same event ids used in the Tandem Source backend.
If fetch_all_event_types=True, then all event types from the history log will be returned.
tconnect_device_id is the UUID assignmentId from get_pumper() pumps (BffPump.assignmentId).
"""
def pump_events(self, tconnect_device_id: str, min_date: Optional[str] = None, max_date: Optional[str] = None, fetch_all_event_types: bool = False) -> Iterator:
event_ids_filter = None if fetch_all_event_types else self.DEFAULT_EVENT_IDS
# Page across date windows, deduplicating events that appear in more
# than one window by their (sequenceGroup, sequenceNumber) identity.
seen = set()
events = []
clock_change_count = 0
for window_start, window_end in self._pump_log_windows(min_date, max_date):
resp = self.get_pump_logs(tconnect_device_id, window_start, window_end, event_ids_filter)
clock_change_count += len(resp.get('clockChanges') or [])
for event in resp.get('events') or []:
key = (event.get('sequenceGroup'), event.get('sequenceNumber'))
if key in seen:
continue
seen.add(key)
events.append(event)
# clockChanges (LID_TIME_CHANGED/LID_DATE_CHANGED) are not consumed by any
# processor, so they are counted for visibility but not parsed.
logger.info(f"Read {len(events)} events ({clock_change_count} clock changes skipped)")
return Events(events)
def pump_clock_changes(self, tconnect_device_id: str, min_date: Optional[str] = None, max_date: Optional[str] = None) -> Iterator:
"""Fetch the pump-logs clockChanges (LID_TIME_CHANGED/LID_DATE_CHANGED)
across the date range, deduplicated by (sequenceGroup, sequenceNumber).
tconnect_device_id is the UUID assignmentId from get_pumper() pumps."""
seen = set()
clock_changes = []
for window_start, window_end in self._pump_log_windows(min_date, max_date):
resp = self.get_pump_logs(tconnect_device_id, window_start, window_end)
for event in resp.get('clockChanges') or []:
key = (event.get('sequenceGroup'), event.get('sequenceNumber'))
if key in seen:
continue
seen.add(key)
clock_changes.append(event)
logger.info(f"Read {len(clock_changes)} clock changes")
return Events(clock_changes)
-143
View File
@@ -1,143 +0,0 @@
import requests
import datetime
import csv
import logging
import time
import json
from .common import parse_date, base_headers, ApiException
logger = logging.getLogger(__name__)
class WS2Api:
BASE_URL = 'https://tconnectws2.tandemdiabetes.com/'
MAX_RETRIES = 2
SLEEP_SECONDS_INCREMENT = 60
userGuid = None
def __init__(self, userGuid):
self.userGuid = userGuid
def get(self, endpoint, query):
r = requests.get(self.BASE_URL + endpoint, query, headers=base_headers())
if r.status_code != 200:
raise ApiException(r.status_code, "WS2 API HTTP %s response: %s" % (str(r.status_code), r.text))
return r.text
def get_jsonp(self, endpoint):
r = requests.get(self.BASE_URL + endpoint, {'callback': 'cb'}, headers=base_headers())
if r.status_code != 200:
raise ApiException(r.status_code, "WS2 API HTTP %s response: %s" % (str(r.status_code), r.text))
t = r.text.strip()
if t.startswith('cb('):
t = t[3:]
if t.endswith(')'):
t = t[:-1]
return json.loads(t)
def _split_empty_sections(self, text):
sections = [[]]
sectionIndex = 0
for line in text.splitlines():
if len(line.strip()) > 0:
sections[sectionIndex].append(line)
else:
sections.append([])
sectionIndex += 1
return sections + [None] * (4 - len(sections))
def _csv_to_dict(self, rawdata):
data = []
if not rawdata or len(rawdata) == 0:
return data
headers = rawdata[0].split(",")
for row in csv.reader(rawdata[1:]):
data.append({headers[i]: row[i] for i in range(len(row)) if i < len(headers)})
return data
"""
Returns information on therapy, displayed in the therapy timeline on the
t:connect website.
Contains BG reading (CGM), IOB, basal, and bolus data.
Basal data does NOT appear for the specified time range if using Control-IQ.
The ControlIQ API endpoints must be used for basal data instead.
However, all other fields are still accessed via this endpoint.
"""
def therapy_timeline_csv(self, start=None, end=None, tries=0):
startDate = parse_date(start)
endDate = parse_date(end)
try:
req_text = self.get('therapytimeline2csv/%s/%s/%s?format=csv' % (self.userGuid, startDate, endDate), {})
except ApiException as e:
# This seems to occur as some kind of soft rate-limit.
logger.warning("Received ApiException in therapy_timeline_csv: (retry count %d) %s" % (tries, e))
if e.status_code == 500:
sleep_seconds = (tries+1) * self.SLEEP_SECONDS_INCREMENT
logger.error("Retrying in %d seconds after HTTP 500 in therapy_timeline_csv (retry count %d): %s" % (sleep_seconds, tries, e))
time.sleep(sleep_seconds)
if tries < self.MAX_RETRIES:
return self.therapy_timeline_csv(start, end, tries+1)
raise e
sections = self._split_empty_sections(req_text)
readingData = None
iobData = None
basalData = None
bolusData = None
for s in sections:
if s and len(s) > 2:
firstrow = s[1].replace('"', '').strip()
if firstrow.startswith("t:slim X2 Insulin Pump"):
readingData = s
elif firstrow.startswith("IOB"):
iobData = s
elif firstrow.startswith("Basal"):
basalData = s
elif firstrow.startswith("Bolus"):
bolusData = s
return {
"readingData": self._csv_to_dict(readingData),
"iobData": self._csv_to_dict(iobData),
"basalData": self._csv_to_dict(basalData),
"bolusData": self._csv_to_dict(bolusData)
}
"""
Returns information on basal suspension. The filterbasal option only returns site/cartridge changes.
SuspendReason values are:
- "site-cart"
- "basal-profile"
- "manual"
- "previous"
- "alarm"
{"BasalSuspension":[{"EventDateTime":"/Date(EPOCH_MS-0000)/", "SuspendReason": "reason"}]}
"""
def basalsuspension(self, start=None, end=None, filterbasal=False):
startDate = parse_date(start)
endDate = parse_date(end)
arg = "filterbasal/1" if filterbasal else ""
return self.get_jsonp('basalsuspension/%s/%s/%s/%s' % (self.userGuid, startDate, endDate, arg))
"""
Returns info on BasalIQ in JSONP format.
"""
def basaliqtech(self, start=None, end=None):
startDate = parse_date(start)
endDate = parse_date(end)
return self.get_jsonp('basaliqtech/%s/%s/%s' % (self.userGuid, startDate, endDate))
-95
View File
@@ -1,95 +0,0 @@
import time
import logging
import sys
from .process import process_time_range
from .features import DEFAULT_FEATURES
from .secret import (
PUMP_SERIAL_NUMBER,
AUTOUPDATE_DEFAULT_SLEEP_SECONDS,
AUTOUPDATE_MAX_SLEEP_SECONDS,
AUTOUPDATE_USE_FIXED_SLEEP,
AUTOUPDATE_FAILURE_MINUTES,
AUTOUPDATE_RESTART_ON_FAILURE
)
logger = logging.getLogger(__name__)
"""
Performs the auto-update functionality. Runs indefinitely in a loop
until stopped (ctrl+c).
"""
def process_auto_update(tconnect, nightscout, time_start, time_end, pretend, features=DEFAULT_FEATURES):
# Read from android api, find exact interval to cut down on API calls
# Refresh API token. If failure, die, have wrapper script re-run.
last_event_index = None
last_event_time = None
last_process_time_range = None
time_diffs = []
while True:
last_event = tconnect.android.last_event_uploaded(PUMP_SERIAL_NUMBER)
if not last_event_index or last_event['maxPumpEventIndex'] > last_event_index:
now = time.time()
logger.info('New reported t:connect data. (event index: %s last: %s)' % (last_event['maxPumpEventIndex'], last_event_index))
if pretend:
logger.info('Would update now if not in pretend mode')
else:
added = process_time_range(tconnect, nightscout, time_start, time_end, pretend, features=features)
logger.info('Added %d items from process_time_range' % added)
if added == 0:
if last_event_index:
logger.error('An event index change was recorded, but no new data was found via the API. ' +
'If this error reoccurs, try restarting tconnectsync.')
else:
last_process_time_range = now
if last_event_index:
time_diffs.append(now - last_event_time)
logger.debug('Updating tracking of time since last update: %s' % time_diffs)
last_event_index = last_event['maxPumpEventIndex']
last_event_time = now
else:
logger.info('No new reported t:connect data. (last event index: %s)' % last_event['maxPumpEventIndex'])
now = time.time()
if last_event_time and (now - last_event_time) >= 60 * AUTOUPDATE_FAILURE_MINUTES:
logger.error(AutoupdateFailureException("No new data event indexes have been detected for over %d minutes. " % AUTOUPDATE_FAILURE_MINUTES +
"The t:connect app might no longer be functioning."))
if AUTOUPDATE_RESTART_ON_FAILURE:
sys.exit(1)
elif last_process_time_range and (now - last_process_time_range) >= 60 * AUTOUPDATE_FAILURE_MINUTES:
logger.error(AutoupdateFailureException("No new data has been found via the API for over %d minutes. " % AUTOUPDATE_FAILURE_MINUTES +
"tconnectsync might not be functioning properly."))
if AUTOUPDATE_RESTART_ON_FAILURE:
sys.exit(1)
if len(time_diffs) > 2:
logger.info('Sleeping 60 seconds after unexpected no index change. (New data might be delayed.)')
time.sleep(60)
continue
sleep_secs = AUTOUPDATE_DEFAULT_SLEEP_SECONDS
if AUTOUPDATE_USE_FIXED_SLEEP != 1:
if len(time_diffs) > 10:
time_diffs = time_diffs[1:]
if len(time_diffs) > 2:
sleep_secs = sum(time_diffs) / len(time_diffs)
if sleep_secs > AUTOUPDATE_MAX_SLEEP_SECONDS:
sleep_secs = AUTOUPDATE_MAX_SLEEP_SECONDS
# Sleep for a rolling average of time between updates
logger.info('Sleeping for %d sec' % sleep_secs)
time.sleep(sleep_secs)
class AutoupdateFailureException(RuntimeError):
pass
+192 -36
View File
@@ -1,58 +1,214 @@
import sys
import time
import arrow
import logging
import traceback
import collections
from datetime import datetime
from pprint import pformat as pformat_base
if sys.version_info < (3, 8):
from importlib_metadata import PackageNotFoundError, version
else:
from importlib.metadata import PackageNotFoundError, version
from .nightscout import NightscoutApi
from .parser.nightscout import BASAL_EVENTTYPE, BOLUS_EVENTTYPE
from .domain.tandemsource.event_class import EventClass
from .sync.tandemsource.choose_device import ChooseDevice
try:
__version__ = version("tconnectsync")
except PackageNotFoundError:
__version__ = "UNKNOWN"
"""
Attempts to authenticate with each t:connect API,
and returns the output of a sample API call from each.
Also attempts to connect to the Nightscout API.
"""
def check_login(tconnect, time_start, time_end):
def check_login(tconnect, time_start, time_end, verbose=False, sanitize=True):
errors = 0
print("Logging in to t:connect ControlIQ API...")
loglines = []
def log(*args):
print(*args)
loglines.append(" ".join([str(i) for i in args]) + "\n")
def log_err(e):
try:
out = ''.join(list(traceback.TracebackException.from_exception(e).format()))
log(out)
except Exception:
log("could not log exception traceback: {}".format(e))
def debug(*args):
if verbose:
print(*args)
loglines.append(" ".join([str(i) for i in args]) + "\n")
log("tconnectsync version %s" % __version__)
log("Python version %s" % sys.version)
log("System platform %s" % sys.platform)
log("Running checks with time range %s to %s" % (time_start, time_end))
log("Current time: %s" % datetime.now())
log("time.tzname: %s" % str(time.tzname))
log("Loading secrets...")
try:
summary = tconnect.controliq.dashboard_summary(time_start, time_end)
print("ControlIQ dashboard summary: %s" % summary)
except Exception as e:
print("Error occurred querying ControlIQ API: %s" % e)
from .secret import TCONNECT_EMAIL, TCONNECT_PASSWORD, TCONNECT_REGION, PUMP_SERIAL_NUMBER, NS_URL, NS_SECRET, TIMEZONE_NAME
from . import secret
except ImportError as e:
log("Error: Unable to load config file. Please check your .env file or environment variables")
log_err(e)
# Config never loaded; the names below are unbound, so stop here instead
# of crashing with a NameError.
return
log(f"Using {TCONNECT_REGION=}")
if not TCONNECT_EMAIL or TCONNECT_EMAIL == 'email@email.com':
log("Error: You have not specified a TCONNECT_EMAIL")
errors += 1
print("\nLogging in to t:connect WS2 API...")
try:
summary = tconnect.ws2.basaliqtech(time_start, time_end)
print("WS2 basaliq status: %s" % summary)
except Exception as e:
print("Error occurred querying WS2 API: %s" % e)
if not TCONNECT_PASSWORD or TCONNECT_PASSWORD == 'password':
log("Error: You have not specified a TCONNECT_PASSWORD")
errors += 1
print("\nLogging in to t:connect Android API...")
try:
summary = tconnect.android.user_profile()
print("Android user profile: %s" % summary)
if not PUMP_SERIAL_NUMBER or PUMP_SERIAL_NUMBER == '11111111':
log("Warning: You have not specified a PUMP_SERIAL_NUMBER, so the pump with most recent activity will be automatically used.")
from .secret import PUMP_SERIAL_NUMBER
event = tconnect.android.last_event_uploaded(PUMP_SERIAL_NUMBER)
print("\nAndroid last uploaded event: %s" % event)
except ImportError:
print("Error: Unable to load config file.")
except Exception as e:
print("Error occurred querying Android API: %s" % e)
if not NS_URL or NS_URL == 'https://yournightscouturl/':
log("Error: You have not specified a NS_URL")
errors += 1
print("\nLogging in to Nightscout...")
try:
from .secret import NS_URL, NS_SECRET
status = NightscoutApi(NS_URL, NS_SECRET).api_status()
print("\nNightscout status: %s" % status)
except ImportError:
print("Error: Unable to load config file.")
except Exception as e:
print("Error occurred querying Nightscout API: %s" % e)
if not NS_SECRET or NS_SECRET == 'apisecret':
log("Error: You have not specified a NS_SECRET")
errors += 1
log("TIMEZONE_NAME: %s" % TIMEZONE_NAME)
log("-----")
serialNumberToPump = None
try:
log("Fetching pump metadata...")
pumpEventMetadata = tconnect.tandemsource.get_pumper().get('pumps', [])
serialNumberToPump = {p['serialNumber']: p for p in pumpEventMetadata}
log(f'Found {len(serialNumberToPump)} pumps: {serialNumberToPump.keys()}')
for pumpSerial, pumpDetails in serialNumberToPump.items():
log(f'Pump {pumpSerial=}: {pumpDetails=}')
log("Running ChooseDevice...")
tconnectDevice = ChooseDevice(secret, tconnect).choose()
log(f'ChooseDevice selected: {tconnectDevice}')
deviceId = tconnectDevice['assignmentId']
log(f'Fetching pump events for {deviceId=} {time_start=} {time_end=} fetch_all_event_types=False')
events = tconnect.tandemsource.pump_events(deviceId, time_start, time_end, fetch_all_event_types=False)
events = list(events)
log(f"Found raw events count: {len(events)}")
events_first_time = None
events_last_time = None
last_event_seqnum = None
for_eventclass = collections.defaultdict(list)
for event in events:
if not events_first_time:
events_first_time = event.eventTimestamp
if not events_last_time:
events_last_time = event.eventTimestamp
if not last_event_seqnum:
last_event_seqnum = event.seqNum
events_first_time = min(events_first_time, event.eventTimestamp)
events_last_time = max(events_last_time, event.eventTimestamp)
last_event_seqnum = max(event.seqNum, last_event_seqnum)
clazz = EventClass.for_event(event)
if clazz:
for_eventclass[clazz.name].append(event)
count_by_eventclass = {k: len(v) for k,v in for_eventclass.items()}
log(f"Found events count: {count_by_eventclass}")
log(f"Found first event time: {events_first_time}")
log(f"Found last event time: {events_last_time}")
log(f"Found last event sequence number: {last_event_seqnum}")
except Exception as e:
log("Error occurred querying Tandem Source:")
log_err(e)
errors += 1
log("-----")
log("Logging in to Nightscout...")
try:
nightscout = NightscoutApi(NS_URL, NS_SECRET)
status = nightscout.api_status()
debug("Nightscout status: \n%s" % pformat(status))
last_upload_basal = nightscout.last_uploaded_entry(BASAL_EVENTTYPE)
debug("Nightscout last uploaded basal: \n%s" % pformat(last_upload_basal))
last_upload_bolus = nightscout.last_uploaded_entry(BOLUS_EVENTTYPE)
debug("Nightscout last uploaded bolus: \n%s" % pformat(last_upload_bolus))
except Exception as e:
log("Error occurred querying Nightscout API:")
log_err(e)
errors += 1
log("-----")
def time_ago(t):
return '%s ago' % (arrow.now() - arrow.get(t)) if t else 'n/a'
if errors == 0:
print("\nNo API errors returned!")
log("No API errors returned!")
else:
print("\nAPI errors occurred. Please check the errors above.")
log("API errors occurred. Please check the errors above.")
with open('tconnectsync-check-output.log', 'w') as f:
if sanitize:
sanitizedData = {
'TCONNECT_EMAIL': TCONNECT_EMAIL,
'TCONNECT_PASSWORD': TCONNECT_PASSWORD,
'PUMP_SERIAL_NUMBER': PUMP_SERIAL_NUMBER,
'NS_URL': NS_URL,
'NS_SECRET': NS_SECRET
}
if serialNumberToPump:
for i, (pumpSerial, pumpDetails) in enumerate(serialNumberToPump.items()):
sanitizedData[f'PUMP_SERIAL_{i}'] = pumpSerial
sanitizedData[f'TCONNECT_DEVICE_ID_{i}'] = pumpDetails['assignmentId']
loglines = [run_sanitize(i, sanitizedData) for i in loglines]
f.writelines(loglines)
print("Created file tconnectsync-check-output.log containing additional debugging information.")
print("For support, you can upload this file to https://github.com/jwoglom/tconnectsync/issues/new")
if sanitize:
print("The file -- but NOT the output printed above -- has been sanitized to remove sensitive data.")
print("Please verify and remove any sensitive data, such as your Nightscout URL/secret and pump serial number,")
print("as necessary.")
def run_sanitize(s, sanitizedData):
ret = str(s)
for k, v in sanitizedData.items():
if v and len(str(v)) > 0:
ret = ret.replace(str(v), '[%s]' % k)
return ret
def pformat(*args, **kwargs):
kwargs['width'] = 160
return pformat_base(*args, **kwargs)
View File
@@ -0,0 +1,40 @@
from enum import Enum
from ...eventparser import events
class EventClass(set, Enum): # type: ignore[misc] # set/Enum both define __hash__; the combination works at runtime
# LidBasalDelivery = every 5min entry
# LidBasalRateChange = only when basal rate changes
BASAL = {events.LidBasalDelivery} # , LidBasalRateChange
BASAL_SUSPENSION = {events.LidPumpingSuspended}
BASAL_RESUME = {events.LidPumpingResumed}
ALARM = {events.LidAlarmActivated, events.LidMalfunctionActivated}
BOLUS = {
events.LidBolusRequestedMsg1, # carb amount, bg, iob
events.LidBolusRequestedMsg2, # more robust bolus type
events.LidBolusRequestedMsg3, # total bolus requested amount
events.LidBolusCompleted, # final event showing amount delivered
events.LidBolexCompleted # extended bolus
}
CARTRIDGE = {events.LidCartridgeFilled, events.LidCannulaFilled, events.LidTubingFilled}
CGM_ALERT = {events.LidCgmAlertActivated, events.LidCgmAlertActivatedDex, events.LidCgmAlertActivatedFsl2}
_CGM_START = {events.LidCgmStartSessionGx, events.LidCgmStartSessionFsl2}
_CGM_JOIN = {events.LidCgmJoinSessionGx, events.LidCgmJoinSessionG7, events.LidCgmJoinSessionFsl2, events.LidCgmJoinSessionFsl3}
_CGM_STOP = {events.LidCgmStopSessionGx, events.LidCgmStopSessionG7, events.LidCgmStopSessionFsl2, events.LidCgmStopSessionFsl3}
CGM_START_JOIN_STOP = {*_CGM_START, *_CGM_JOIN, *_CGM_STOP}
CGM_READING = {events.LidCgmDataGxb, events.LidCgmDataG7, events.LidCgmDataFsl2, events.LidCgmDataFsl3}
USER_MODE = {events.LidAaUserModeChange}
DEVICE_STATUS = {events.LidDailyBasal}
@staticmethod
def for_event(evt):
for typ, vals in EventClass.__members__.items():
if typ.startswith('_'):
continue
if type(evt) == type and evt in vals:
return EventClass.__members__[typ]
elif type(evt) in vals:
return EventClass.__members__[typ]
return None
@@ -0,0 +1,57 @@
from dataclasses import dataclass
from dataclasses_json import dataclass_json, DataClassJsonMixin
from typing import List
# These dataclasses model the `settings.details` blob from the Tandem Source
# bff/pumper endpoint (BffPump.settings.details). Only the fields the
# profile sync consumes are declared; dataclasses_json ignores the rest.
@dataclass_json
@dataclass
class PumpProfileSegment:
startTime: int # minutes
basalRate: int # milliunits
isf: int
carbRatio: int # milliunits
targetBg: int
@property
def skip(self):
return self.startTime == 0 and self.basalRate == 0 and self.isf == 0 and self.carbRatio == 0 and self.targetBg == 0
@dataclass_json
@dataclass
class PumpProfile:
name: str
idp: int
timeDependentSegments: List[PumpProfileSegment]
insulinDuration: int # minutes
carbEntry: str # e.g. "UnitsAsCarbs"
maxBolus: int # milliunits
def __post_init__(self):
self.timeDependentSegments = [i for i in self.timeDependentSegments if not i.skip]
@property
def tDependentSegs(self) -> List[PumpProfileSegment]:
# Back-compat alias for the pre-BFF field name.
return self.timeDependentSegments
@dataclass_json
@dataclass
class PumpProfiles:
activeIdp: int
profile: List[PumpProfile]
@dataclass_json
@dataclass
class PumpCgmSettings:
# The bff/pumper cgmSettings block is flat (no nested per-alert object).
highGlucoseAlertMgPerDl: int
lowGlucoseAlertMgPerDl: int
@dataclass_json
@dataclass
class PumpSettings(DataClassJsonMixin):
profiles: PumpProfiles
cgmSettings: PumpCgmSettings
+243
View File
@@ -0,0 +1,243 @@
import re
def _norm(s):
return re.sub(r'[^a-z0-9]', '', s.lower())
header = '''# THIS FILE IS AUTOGENERATED. DO NOT EDIT.
import struct
import logging
import re
from dataclasses import dataclass
from enum import Enum, IntFlag
from .raw_event import RawEvent, BaseEvent
logger = logging.getLogger(__name__)
EVENT_LEN = 26
def _norm(s):
return re.sub(r'[^a-z0-9]', '', s.lower())
def _bitmask_arr_to_int(v):
# pump-logs bitmask fields arrive as arrays of set-bit indices; convert to the
# int the generated IntFlag / bitmask_to_list expects. Tolerate an int too.
if isinstance(v, (list, tuple)):
r = 0
for i in v:
r |= (1 << int(i))
return r
return int(v) if v is not None else 0
'''
TYPE_TO_STRUCT = {
'uint8': '>B',
'int8': '>b',
'uint16': '>H',
'int16': '>h',
'uint32': '>I',
'float32': '>f',
}
for k, v in TYPE_TO_STRUCT.items():
header += f"{k.upper()} = '{v}'\n"
TYPE_TO_PYOBJ = {
'uint8': 'int',
'int8': 'int',
'uint16': 'int',
'int16': 'int',
'uint32': 'int',
'float32': 'float',
}
HEADER_SIZE = 10
def unpack_command_for(field_def):
return f'struct.unpack_from({field_def["type"].upper()}, raw[:EVENT_LEN], {HEADER_SIZE + field_def["offset"]})'
TEMPLATE = '''
@dataclass
class {name}(BaseEvent):
"""{id}: {raw_name}"""
ID = {id}
NAME = "{raw_name}"
raw: RawEvent
{fields}
{transform_funcs}
@staticmethod
def build(raw):
{build_p1}
return {name}(
raw = RawEvent.build(raw),
{build_p2}
)
@staticmethod
def build_from_json(event):
props = {{_norm(k): v for k, v in event.get("eventProperties", {{}}).items()}}
return {name}(
raw = RawEvent.build_from_json(event),
{build_json}
)
@property
def eventTimestamp(self):
return self.raw.timestamp
@property
def seqNum(self):
return self.raw.seqNum
@property
def eventId(self):
return self.ID
def todict(self):
return dict(
id=self.ID,
name=self.NAME,
seqNum=self.seqNum,
eventTimestamp=str(self.eventTimestamp),
{fields_dict}
)
'''
def firstLower(text):
if not text:
return text
return f'{text[0].lower()}{text[1:]}'
def eventNameFormat(text):
if not text:
return text
return text.replace('_', ' ').title().replace(' ', '')
def fieldNameFormat(text):
if not text or all([i.isupper() for i in text]):
return text
if '_' in text or ' ' in text:
# snake_case / space-separated -> CamelCase, then lowercase first char
return firstLower(text.replace('_', ' ').title().replace(' ', '')).replace('raw', 'Raw')
# already camelCase (schema keys): preserve internal capitalization, only
# lowercase the first character (don't .title() it away)
return firstLower(text)
def build_fields(event_def):
ret = []
for name, field in event_def["data"].items():
suffix = 'Raw' if "transform" in field and name[-3:] != 'Raw' else ''
f = f'{fieldNameFormat(name)}{suffix}: {TYPE_TO_PYOBJ[field["type"]]}'
if "uom" in field:
f += ' # ' + field['uom']
ret.append(f)
return '\n'.join([f'{" "*4}{f}' for f in ret])
def build_fields_dict(event_def):
ret = []
for name, field in event_def["data"].items():
suffix = 'Raw' if "transform" in field and name[-3:] != 'Raw' else ''
f = f'{fieldNameFormat(name)}{suffix}=self.{fieldNameFormat(name)}{suffix},'
ret.append(f)
return '\n'.join([f'{" "*12}{f}' for f in ret])
def build_decode(event_def):
p1s = []
p2s = []
for name, field in event_def["data"].items():
p1 = f'{fieldNameFormat(name)}, = {unpack_command_for(field)}'
p1s.append(p1)
suffix = 'Raw' if "transform" in field and name[-3:] != 'Raw' else ''
p2 = f'{fieldNameFormat(name)}{suffix} = {fieldNameFormat(name)},'
p2s.append(p2)
return '\n'.join([f'{" "*8}{f}' for f in p1s]), '\n'.join([f'{" "*12}{f}' for f in p2s])
def build_json_kwargs(event_def):
lines = []
for name, field in event_def["data"].items():
suffix = 'Raw' if "transform" in field and name[-3:] != 'Raw' else ''
attr = f'{fieldNameFormat(name)}{suffix}'
key = _norm(name)
is_bitmask = "transform" in field and any(tx[0] == 'bitmask' for tx in field["transform"])
if is_bitmask:
lines.append(f'{attr} = _bitmask_arr_to_int(props.get("{key}", 0)),')
else:
lines.append(f'{attr} = props.get("{key}", None),')
return '\n'.join([f'{" "*12}{l}' for l in lines])
def build_transform_funcs(event_def):
try:
from transforms import TRANSFORMS
except ImportError:
from .transforms import TRANSFORMS
ret = []
for name, field in event_def["data"].items():
if not "transform" in field:
continue
for tx in field["transform"]:
ret += TRANSFORMS[tx[0]](event_def, name, fieldNameFormat(name), field, tx[1])
return '\n'.join([f'{" "*4}{f}' if f else '' for f in ret])
def build_event(event_id, event_def):
return TEMPLATE.format(
name = eventNameFormat(event_def["name"]),
fields = build_fields(event_def),
fields_dict = build_fields_dict(event_def),
build_p1 = build_decode(event_def)[0],
build_p2 = build_decode(event_def)[1],
build_json = build_json_kwargs(event_def),
transform_funcs = build_transform_funcs(event_def),
id = event_id,
raw_name = event_def["name"]
)
def build_events_map(events):
ret = ['EVENT_IDS = {']
for event_id, event_def in events.items():
ret += [f'{" "*4}{event_id}: {eventNameFormat(event_def["name"])},']
ret += ['}', '']
ret += ['EVENT_NAMES = {']
for event_id, event_def in events.items():
ret += [f'{" "*4}"{event_def["name"]}": {eventNameFormat(event_def["name"])},']
ret += ['}', '']
return '\n'.join(ret)
if __name__ == '__main__':
import json
merged_events = {}
output = f'{header}'
with open("events.json", "r") as f:
j = json.loads(f.read())
merged_events.update(j["events"])
with open("custom_events.json", "r") as f:
j = json.loads(f.read())
merged_events.update(j["events"])
for event_id, event_def in merged_events.items():
output += build_event(event_id, event_def)
output += build_events_map(merged_events)
print(output)
@@ -0,0 +1,68 @@
{
"events": {
"81": {
"name": "LID_DAILY_BASAL",
"data": {
"dailyTotalBasal": {
"type": "float32",
"offset": 0,
"uom": "units"
},
"lastBasalRate": {
"type": "float32",
"offset": 4,
"uom": "units/hour"
},
"iob": {
"type": "float32",
"offset": 8,
"uom": "units"
},
"batteryLipoMilliVolts": {
"type": "uint16",
"offset": 12,
"uom": "millivolts"
},
"batteryChargePercent": {
"type": "uint8",
"offset": 14,
"uom": "percent"
},
"finalEventForDay": {
"type": "uint8",
"offset": 15
}
}
},
"48": {
"name": "LID_CARBS_ENTERED",
"data": {
"carbs": {
"type": "float32",
"offset": 0,
"uom": "carbs"
}
}
},
"36": {
"name": "LID_USB_CONNECTED",
"data": {
"negotiatedCurrent": {
"type": "float32",
"offset": 0,
"uom": "mA"
}
}
},
"37": {
"name": "LID_USB_DISCONNECTED",
"data": {
"negotiatedCurrent": {
"type": "float32",
"offset": 0,
"uom": "mA"
}
}
}
}
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+41
View File
@@ -0,0 +1,41 @@
import struct
import base64
import logging
from dataclasses import dataclass
from .raw_event import RawEvent, EVENT_LEN
from .events import EVENT_IDS
from .utils import batched
logger = logging.getLogger(__name__)
def Event(x):
# Accepts either a 26-byte binary event or a pump-logs JSON event (dict).
if isinstance(x, dict):
raw_event = RawEvent.build_from_json(x)
if not raw_event.id in EVENT_IDS:
# Log unknown events with their property keys for reverse-engineering
props = ' '.join(x['eventProperties'].keys())
logger.debug(f"UNKNOWN_JSON_EVENT | id={raw_event.id} | seqNum={raw_event.seqNum} | timestamp={raw_event.timestamp.isoformat()} | props={props}")
return raw_event
return EVENT_IDS[raw_event.id].build_from_json(x)
raw_event = RawEvent.build(x)
if not raw_event.id in EVENT_IDS:
# Log unknown events with full hex dump for reverse-engineering
hex_dump = ' '.join(f'{b:02x}' for b in x[:EVENT_LEN])
logger.debug(f"UNKNOWN_EVENT | id={raw_event.id} | seqNum={raw_event.seqNum} | timestamp={raw_event.timestamp.isoformat()} | bytes={hex_dump}")
return raw_event
return EVENT_IDS[raw_event.id].build(x)
def Events(x):
# Accepts either a raw binary event stream or an iterable of pump-logs JSON events.
if isinstance(x, (bytes, bytearray)):
return (Event(bytearray(e)) for e in batched(x, EVENT_LEN))
return (Event(e) for e in x)
def decode_raw_events(raw):
return base64.b64decode(raw)
+90
View File
@@ -0,0 +1,90 @@
import struct
import arrow
from ..secret import TIMEZONE_NAME
from dataclasses import dataclass
EVENT_LEN = 26
# Big endian
UINT16 = '>H'
UINT32 = '>I'
TANDEM_EPOCH = 1199145600
@dataclass
class BaseEvent:
@staticmethod
def build(raw):
raise NotImplemented
@property
def eventTimestamp(self):
raise NotImplemented
@property
def eventId(self):
raise NotImplemented
@dataclass
class RawEvent:
source: int
id: int
timestampRaw: int
seqNum: int
raw: bytearray
@staticmethod
def build(raw):
source_and_id, = struct.unpack_from(UINT16, raw[:EVENT_LEN], 0)
timestampRaw, = struct.unpack_from(UINT32, raw[:EVENT_LEN], 2)
seqNum, = struct.unpack_from(UINT32, raw[:EVENT_LEN], 6)
return RawEvent(
source = (source_and_id & 0xF000) >> 12,
id = source_and_id & 0x0FFF,
timestampRaw = timestampRaw,
seqNum = seqNum,
raw = raw
)
@staticmethod
def build_from_json(event):
# pump-logs JSON events carry pumpDateTime (naive local wall-clock,
# no tz). Reproduce the byte path: store timestampRaw as seconds since
# TANDEM_EPOCH parsed AS IF UTC, so the .timestamp property re-forces
# the same wall-clock into TIMEZONE_NAME. source is unused; raw bytes
# are absent on the JSON path.
timestampRaw = arrow.get(event["pumpDateTime"]).int_timestamp - TANDEM_EPOCH
return RawEvent(
source = 0,
id = event["eventCode"],
timestampRaw = timestampRaw,
seqNum = event["sequenceNumber"],
raw = b''
)
@property
def timestamp(self):
# Event timestamps do not have TZ data attached to them when parsed,
# but represent the user's time zone setting. So we keep the time
# referenced on them, but force the timezone to what the user
# requests via the TZ secret.
return arrow.get(TANDEM_EPOCH + self.timestampRaw, tzinfo='UTC').replace(tzinfo=TIMEZONE_NAME)
@property
def eventId(self):
return self.id
@property
def eventTimestamp(self):
return self.timestamp
def todict(self):
return dict(
id=self.id,
name="RawEvent",
seqNum=self.seqNum,
eventTimestamp=str(self.eventTimestamp),
raw=''.join('{:02x}'.format(x) for x in self.raw),
)
+155
View File
@@ -0,0 +1,155 @@
ALERTS_DICT = {
"0": "LOW_INSULIN_ALERT",
"1": "USB_CONNECTION_ALERT",
"2": "LOW_POWER_ALERT",
"3": "LOW_POWER_ALERT2",
"4": "DATA_ERROR_ALERT",
"5": "AUTO_OFF_ALERT",
"6": "MAX_BASAL_RATE_ALERT",
"7": "POWER_SOURCE_ALERT",
"8": "MIN_BASAL_ALERT",
"9": "CONNECTION_ERROR_ALERT",
"10": "CONNECTION_ERROR_ALERT2",
"11": "INCOMPLETE_BOLUS_ALERT",
"12": "INCOMPLETE_TEMP_RATE_ALERT",
"13": "INCOMPLETE_CARTRIDGE_CHANGE_ALERT",
"14": "INCOMPLETE_FILL_TUBING_ALERT",
"15": "INCOMPLETE_FILL_CANNULA_ALERT",
"16": "INCOMPLETE_SETTING_ALERT",
"17": "LOW_INSULIN_ALERT2",
"18": "MAX_BASAL_ALERT",
"19": "LOW_TRANSMITTER_ALERT",
"20": "TRANSMITTER_ALERT",
"21": "DEFAULT_ALERT_21",
"22": "SENSOR_EXPIRING_ALERT",
"23": "PUMP_REBOOTING_ALERT",
"24": "DEVICE_CONNECTION_ERROR",
"25": "CGM_GRAPH_REMOVED",
"26": "MIN_BASAL_ALERT2",
"27": "INCOMPLETE_CALIBRATION",
"28": "CALIBRATION_TIMEOUT",
"29": "INVALID_TRANSMITTER_ID",
"30": "DEFAULT_ALERT_30",
"32": "DEFAULT_ALERT_32",
"33": "BUTTON_ALERT",
"34": "QUICK_BOLUS_ALERT",
"35": "BASAL_IQ_ALERT",
"36": "DEFAULT_ALERT_36",
"37": "DEFAULT_ALERT_37",
"38": "DEFAULT_ALERT_38",
"39": "TRANSMITTER_END_OF_LIFE",
"40": "CGM_ERROR",
"41": "CGM_ERROR2",
"42": "CGM_ERROR3",
"43": "DEFAULT_ALERT_43",
"44": "TRANSMITTER_EXPIRING_ALERT",
"45": "TRANSMITTER_EXPIRING_ALERT2",
"46": "TRANSMITTER_EXPIRING_ALERT3",
"47": "DEFAULT_ALERT_47",
"48": "CGM_UNAVAILABLE",
"49": "FILL_TUBING_STILL_IN_PROGRESS",
"50": "DEFAULT_ALERT_50",
"51": "CONTROL_IQ_LOW",
"52": "DEFAULT_ALERT_52",
"53": "DEFAULT_ALERT_53",
"54": "DEVICE_PAIRED",
"55": "DEFAULT_ALERT_55",
"56": "DEFAULT_ALERT_56",
"57": "DEFAULT_ALERT_57",
"58": "DEFAULT_ALERT_58",
"59": "DEFAULT_ALERT_59",
"60": "DEFAULT_ALERT_60",
"61": "DEFAULT_ALERT_61",
"62": "DEFAULT_ALERT_62",
"63": "DEFAULT_ALERT_63",
}
ALARMS_DICT = {
"0": "CARTRIDGE_ALARM",
"1": "CARTRIDGE_ALARM2",
"2": "OCCLUSION_ALARM",
"3": "PUMP_RESET_ALARM",
"4": "DEFAULT_ALARM_4",
"5": "CARTRIDGE_ALARM3",
"6": "CARTRIDGE_ALARM4",
"7": "AUTO_OFF_ALARM",
"8": "EMPTY_CARTRIDGE_ALARM",
"9": "CARTRIDGE_ALARM5",
"10": "TEMPERATURE_ALARM",
"11": "TEMPERATURE_ALARM2",
"12": "BATTERY_SHUTDOWN_ALARM",
"13": "DEFAULT_ALARM_13",
"14": "INVALID_DATE_ALARM",
"15": "TEMPERATURE_ALARM3",
"16": "CARTRIDGE_ALARM6",
"17": "DEFAULT_ALARM_17",
"18": "RESUME_PUMP_ALARM",
"19": "DEFAULT_ALARM_19",
"20": "CARTRIDGE_ALARM7",
"21": "ALTITUDE_ALARM",
"22": "STUCK_BUTTON_ALARM",
"23": "RESUME_PUMP_ALARM2",
"24": "ATMOSPHERIC_PRESSURE_OUT_OF_RANGE_ALARM",
"25": "CARTRIDGE_REMOVED_ALARM",
"26": "OCCLUSION_ALARM2",
"27": "DEFAULT_ALARM_27",
"28": "DEFAULT_ALARM_28",
"29": "CARTRIDGE_ALARM10",
"30": "CARTRIDGE_ALARM11",
"31": "CARTRIDGE_ALARM12",
"32": "DEFAULT_ALARM_32",
"33": "DEFAULT_ALARM_33",
"34": "DEFAULT_ALARM_34",
"35": "DEFAULT_ALARM_35",
"36": "DEFAULT_ALARM_36",
"37": "DEFAULT_ALARM_37",
"38": "DEFAULT_ALARM_38",
"39": "DEFAULT_ALARM_39",
"40": "DEFAULT_ALARM_40",
"41": "DEFAULT_ALARM_41",
"42": "DEFAULT_ALARM_42",
"43": "DEFAULT_ALARM_43",
"44": "DEFAULT_ALARM_44",
"45": "DEFAULT_ALARM_45",
"46": "DEFAULT_ALARM_46",
"47": "DEFAULT_ALARM_47",
"48": "DEFAULT_ALARM_48",
"49": "DEFAULT_ALARM_49",
"50": "DEFAULT_ALARM_50",
"51": "DEFAULT_ALARM_51",
"52": "DEFAULT_ALARM_52",
"53": "DEFAULT_ALARM_53",
"54": "DEFAULT_ALARM_54",
"55": "DEFAULT_ALARM_55",
"56": "DEFAULT_ALARM_56",
"57": "DEFAULT_ALARM_57",
"58": "DEFAULT_ALARM_58",
"59": "DEFAULT_ALARM_59",
"60": "DEFAULT_ALARM_60",
"61": "DEFAULT_ALARM_61",
"62": "DEFAULT_ALARM_62",
"63": "DEFAULT_ALARM_63",
}
# CGM alert codes from pump history verification (verified from pump display)
CGM_ALERTS_DICT = {
"1": "CGM Fixed Low",
"2": "CGM High",
"3": "CGM Low",
"8": "CGM Rapid Fall",
"11": "CGM Sensor Fail",
"12": "CGM Sensor Expiring Soon",
"13": "CGM Sensor Expired",
"14": "CGM Out Of Range",
"20": "CGM Transmitter Error",
"22": "CGM Sensor Expiring 2",
"25": "CGM Replace Sensor",
"26": "CGM Temperature",
"27": "CGM Failed Connection",
"39": "CGM Transmitter Expired",
"40": "Pump Bluetooth Error",
"45": "CGM Transmitter Expiring Soon",
"46": "CGM Transmitter Expiring 2",
"48": "CGM Unavailable"
}
+145
View File
@@ -0,0 +1,145 @@
import json
try:
from static_dicts import ALERTS_DICT, ALARMS_DICT, CGM_ALERTS_DICT
except ImportError:
from .static_dicts import ALERTS_DICT, ALARMS_DICT, CGM_ALERTS_DICT
def enumNameFormat(text):
if not text:
return text
t = text.replace('_', ' ').title().replace(' ', '')
if t.startswith('no,'):
return 'No'
if t.startswith('yes,'):
return 'Yes'
rem = None
for i in '-,.':
spl = t.split(i)
t = spl[0]
if len(spl) > 1:
rem = rem or spl[1]
for i in '()/"\u201c\u201d':
t = t.replace(i, '')
if t.lower() == 'false':
return 'FalseVal'
if t.lower() == 'true':
return 'TrueVal'
if t.lower() == 'none':
return 'NoneVal'
if t.lower() == 'reserved':
return None
if t.lower() == 'unused':
return None
if t.lower() == 'unavailable' and rem:
suffix = enumNameFormat(rem)
t += f'{suffix[0].lower()}{suffix[1:]}'
return f'{t[0].upper()}{t[1:]}'
def uniqueMemberNames(tx):
names = {}
for key, value in tx.items():
name = enumNameFormat(value)
if not name:
continue
names.setdefault(name, []).append(str(key))
unique_names = {}
for key, value in tx.items():
name = enumNameFormat(value)
if not name:
continue
if len(names[name]) == 1:
unique_names[key] = name
continue
unique_names[key] = f'{name}_{key}'
return unique_names
def transform_enum(event_def, name, name_fmt, field, tx):
out = []
member_names = uniqueMemberNames(tx)
lines_for_out = json.dumps(tx, indent=4).splitlines()
out += [f'{enumNameFormat(name_fmt)}Map = {lines_for_out[0]}']
out += lines_for_out[1:]
out += ['']
out += [f'class {enumNameFormat(name_fmt)}Enum(Enum):']
out += [
f' {member_names[k]} = {k}' for k, v in tx.items() if k in member_names
]
out += ['']
out += [
'@property',
f'def {name_fmt}(self):',
f' try:',
f' return self.{enumNameFormat(name_fmt)}Enum(self.{name_fmt}Raw)',
f' except ValueError as e:',
f' logger.error("Invalid {name_fmt}Raw in {enumNameFormat(name_fmt)} for "+str(self))',
f' logger.error(e)',
f' return None',
''
]
return out
def transform_dictionary(event_def, name, name_fmt, field, tx):
if tx == 'alerts':
return transform_enum(event_def, name, name_fmt, field, ALERTS_DICT)
if tx == 'alarms':
return transform_enum(event_def, name, name_fmt, field, ALARMS_DICT)
if tx == 'dalerts':
return transform_enum(event_def, name, name_fmt, field, CGM_ALERTS_DICT)
return [f'# Dictionary unknown: {tx}']
def transform_bitmask(event_def, name, name_fmt, field, tx):
out = []
member_names = uniqueMemberNames(tx)
lines_for_out = json.dumps(tx, indent=4).splitlines()
out += [f'{enumNameFormat(name_fmt)}Map = {lines_for_out[0]}']
out += lines_for_out[1:]
out += ['']
out += [f'class {enumNameFormat(name_fmt)}Bitmask(IntFlag):',]
out += [
f' {member_names[k]} = 2**{k}' for k, v in tx.items() if k in member_names
]
out += ['']
out += [
'@property',
f'def {name_fmt}(self):',
f' try:',
f' return self.{enumNameFormat(name_fmt)}Bitmask(self.{name_fmt}Raw)',
f' except ValueError as e:',
f' logger.error("Invalid {name_fmt}Raw in {enumNameFormat(name_fmt)}Bitmask for "+str(self))',
f' logger.error(e)',
f' return None',
f''
]
return out
def transform_ratio(event_def, name, name_fmt, field, tx):
out = []
out += [
'@property',
f'def {name_fmt}(self):',
f' return self.{name_fmt}Raw * {tx}',
''
]
return out
TRANSFORMS = {
'enum': transform_enum,
'dictionary': transform_dictionary,
'bitmask': transform_bitmask,
'ratio': transform_ratio,
}
+23
View File
@@ -0,0 +1,23 @@
import itertools
def batched(iterable, n):
"""
Batch data into iterators of length n. The last batch may be shorter.
This is a polyfill for itertools.batched() in Python 3.12+
"""
if n < 1:
raise ValueError('n must be at least one')
it = iter(iterable)
while True:
chunk_it = itertools.islice(it, n)
try:
first_el = next(chunk_it)
except StopIteration:
return
yield itertools.chain((first_el,), chunk_it)
def bitmask_to_list(intflag):
n = type(intflag).__name__
if not str(intflag).startswith(n):
return []
return str(intflag)[len(n)+1:].split('|')
+13 -4
View File
@@ -7,24 +7,33 @@ IOB = "IOB"
BOLUS_BG = "BOLUS_BG"
CGM = "CGM"
PUMP_EVENTS = "PUMP_EVENTS"
PUMP_EVENTS_BASAL_SUSPENSION = "PUMP_EVENTS_BASAL_SUSPENSION"
PROFILES = "PROFILES"
CGM_ALERTS = "CGM_ALERTS"
DEVICE_STATUS = "DEVICE_STATUS"
DEFAULT_FEATURES = [
BASAL,
BOLUS,
IOB
PUMP_EVENTS,
PROFILES
]
ALL_FEATURES = [
BASAL,
BOLUS,
IOB,
PUMP_EVENTS
PUMP_EVENTS,
PUMP_EVENTS_BASAL_SUSPENSION,
PROFILES,
CGM,
CGM_ALERTS,
DEVICE_STATUS,
]
# These modes are not yet ready for wide use.
if ENABLE_TESTING_MODES:
ALL_FEATURES += [
BOLUS_BG,
CGM
BOLUS_BG
]
+130 -49
View File
@@ -1,88 +1,155 @@
import sys
import datetime
import requests
import hashlib
import time
import urllib.parse
import arrow
import logging
from urllib.parse import urljoin
from typing import Optional, Union
from .api.common import ApiException
from .parser.nightscout import ENTERED_BY
# try:
# from .secret import NS_URL, NS_SECRET
# except Exception:
# print('Unable to import Nightscout secrets from secret.py')
# sys.exit(1)
# Anything arrow.get() accepts for the date filters / timestamps passed around
# in this module (ISO strings, datetimes, or already-parsed Arrow objects).
DateLike = Union[str, datetime.datetime, arrow.Arrow]
def format_datetime(date: DateLike) -> str:
return arrow.get(date).isoformat()
def time_range(field_name: str, start_time: Optional[DateLike], end_time: Optional[DateLike]) -> str:
def fmt(date: DateLike) -> str:
ret = format_datetime(date)
# URL-encode so the '+' in offsets like '+02:00' is not decoded
# to a space by the server, which would mangle the ISO-8601 value.
# Upstream instead retries with 'T' replaced by a space (t_to_space);
# encoding the value fixes the cause, so that fallback is not carried.
return urllib.parse.quote(ret, safe='')
arg = ''
if start_time:
arg += '&find[%s][$gte]=%s' % (field_name, fmt(start_time))
if end_time:
arg += '&find[%s][$lte]=%s' % (field_name, fmt(end_time))
return arg
logger = logging.getLogger(__name__)
class NightscoutApi:
def __init__(self, url, secret):
def __init__(self, url: str, secret: str, skip_verify: bool = False, ignore_conn_errors: bool = False) -> None:
self.url = url
self.secret = secret
self.verify = False if skip_verify else None
self.ignore_conn_errors = ignore_conn_errors
def upload_entry(self, ns_format, entity='treatments'):
def upload_entry(self, ns_format: dict, entity: str = 'treatments') -> None:
r = requests.post(urljoin(self.url, 'api/v1/' + entity + '?api_secret=' + self.secret), json=ns_format, headers={
'Accept': 'application/json',
'Content-Type': 'application/json',
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
}, verify=self.verify)
if r.status_code != 200:
raise ApiException(r.status_code, "Nightscout upload response: %s" % r.text)
raise ApiException(r.status_code, "Nightscout upload %s response: %s" % (r.status_code, r.text))
def delete_entry(self, entity):
def delete_entry(self, entity: str) -> None:
r = requests.delete(urljoin(self.url, 'api/v1/' + entity + '?api_secret=' + self.secret), json={}, headers={
'Accept': 'application/json',
'Content-Type': 'application/json',
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
}, verify=self.verify)
if r.status_code != 200:
raise ApiException(r.status_code, "Nightscout delete response: %s" % r.text)
raise ApiException(r.status_code, "Nightscout delete %s response: %s" % (r.status_code, r.text))
def put_entry(self, ns_format, entity):
def put_entry(self, ns_format: dict, entity: str) -> None:
r = requests.put(urljoin(self.url, 'api/v1/' + entity + '?api_secret=' + self.secret), json=ns_format, headers={
'Accept': 'application/json',
'Content-Type': 'application/json',
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
}, verify=self.verify)
if r.status_code != 200:
raise ApiException(r.status_code, "Nightscout put response: %s" % r.text)
raise ApiException(r.status_code, "Nightscout put %s response: %s" % (r.status_code, r.text))
def last_uploaded_entry(self, eventType):
latest = requests.get(urljoin(self.url, 'api/v1/treatments?count=1&find[enteredBy]=' + urllib.parse.quote(ENTERED_BY) + '&find[eventType]=' + urllib.parse.quote(eventType) + '&ts=' + str(time.time())), headers={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout last_uploaded_entry response: %s" % latest.text)
def last_uploaded_entry(self, eventType: str, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
dateFilter = time_range('created_at', time_start, time_end)
try:
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={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
}, verify=self.verify)
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout last_uploaded_entry %s response: %s" % (latest.status_code, latest.text))
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
def last_uploaded_bg_entry(self):
latest = requests.get(urljoin(self.url, 'api/v1/entries.json?count=1&find[device]=' + urllib.parse.quote(ENTERED_BY) + '&ts=' + str(time.time())), headers={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout last_uploaded_bg_entry response: %s" % latest.text)
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
except requests.exceptions.ConnectionError as e:
if self.ignore_conn_errors:
logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
return None
else:
raise e
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
def last_uploaded_bg_entry(self, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
dateFilter = time_range('dateString', time_start, time_end)
try:
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={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
}, verify=self.verify)
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout last_uploaded_bg_entry %s response: %s" % (latest.status_code, latest.text))
def last_uploaded_activity(self, activityType):
latest = requests.get(urljoin(self.url, 'api/v1/activity?find[enteredBy]=' + urllib.parse.quote(ENTERED_BY) + '&find[activityType]=' + urllib.parse.quote(activityType) + '&ts=' + str(time.time())), headers={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout activity response: %s" % latest.text)
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
except requests.exceptions.ConnectionError as e:
if self.ignore_conn_errors:
logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
return None
else:
raise e
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
def last_uploaded_activity(self, activityType: str, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
dateFilter = time_range('created_at', time_start, time_end)
try:
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={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
}, verify=self.verify)
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout activity %s response: %s" % (latest.status_code, latest.text))
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
except requests.exceptions.ConnectionError as e:
if self.ignore_conn_errors:
logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
return None
else:
raise e
def last_uploaded_devicestatus(self, time_start: Optional[DateLike] = None, time_end: Optional[DateLike] = None) -> Optional[dict]:
dateFilter = time_range('created_at', time_start, time_end)
try:
latest = requests.get(urljoin(self.url, 'api/v1/devicestatus?find[device]=' + urllib.parse.quote(ENTERED_BY) + dateFilter + '&ts=' + str(time.time())), headers={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
}, verify=self.verify)
if latest.status_code != 200:
raise ApiException(latest.status_code, "Nightscout devicestatus %s response: %s" % (latest.status_code, latest.text))
j = latest.json()
if j and len(j) > 0:
return j[0]
return None
except requests.exceptions.ConnectionError as e:
if self.ignore_conn_errors:
logger.warn('Ignoring ConnectionError because ignore_conn_errors=true', e)
return None
else:
raise e
"""
Returns general status information about the Nightscout server.
@@ -90,7 +157,21 @@ class NightscoutApi:
def api_status(self):
status = requests.get(urljoin(self.url, 'api/v1/status.json'), headers={
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
})
}, verify=self.verify)
if status.status_code != 200:
raise Exception('HTTP error status code (%d) from Nightscout: %s' % (status.status_code, status.text))
return status.json()
return status.json()
"""
Returns information on the currently configured Nightscout profile data store
(contains all profiles in Nightscout under one mongo object).
"""
def current_profile(self, time_start=None, time_end=None):
r = requests.get(urljoin(self.url, 'api/v1/profile/current?api_secret=' + self.secret), json={}, headers={
'Accept': 'application/json',
'Content-Type': 'application/json',
'api-secret': hashlib.sha1(self.secret.encode()).hexdigest()
}, verify=self.verify)
if r.status_code != 200:
raise ApiException(r.status_code, "Nightscout current_profile %s response: %s" % (r.status_code, r.text))
return r.json()
+186 -18
View File
@@ -1,14 +1,23 @@
import arrow
from ..domain.tandemsource.pump_settings import PumpProfile, PumpSettings
from ..secret import TIMEZONE_NAME, NIGHTSCOUT_PROFILE_CARBS_HR_VALUE, NIGHTSCOUT_PROFILE_DELAY_VALUE
ENTERED_BY = "Pump (tconnectsync)"
BASAL_EVENTTYPE = "Temp Basal"
BOLUS_EVENTTYPE = "Combo Bolus"
SITECHANGE_EVENTTYPE = "Site Change"
BASALSUSPENSION_EVENTTYPE = "Basal Suspension"
BASALRESUME_EVENTTYPE = "Basal Resume"
ACTIVITY_EVENTTYPE = "Activity"
EXERCISE_EVENTTYPE = "Exercise"
SLEEP_EVENTTYPE = "Sleep"
ALARM_EVENTTYPE = "Alarm"
CGM_ALERT_EVENTTYPE = "CGM Alert"
CGM_START_EVENTTYPE = "Sensor Start"
CGM_JOIN_EVENTTYPE = "Sensor Start"
CGM_STOP_EVENTTYPE = "Sensor Stop"
IOB_ACTIVITYTYPE = "tconnect_iob"
@@ -18,7 +27,7 @@ Conversion methods for parsing data into Nightscout objects.
"""
class NightscoutEntry:
@staticmethod
def basal(value, duration_mins, created_at, reason=""):
def basal(value, duration_mins, created_at, reason="", pump_event_id=""):
return {
"eventType": BASAL_EVENTTYPE,
"reason": reason,
@@ -28,7 +37,8 @@ class NightscoutEntry:
"created_at": created_at,
"carbs": None,
"insulin": None,
"enteredBy": ENTERED_BY
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
# Note that Nightscout is not consistent and uses "Sensor"/"Finger"
@@ -37,23 +47,29 @@ class NightscoutEntry:
FINGER = "Finger"
@staticmethod
def bolus(bolus, carbs, created_at, notes="", bg="", bg_type=""):
def bolus(bolus, carbs, created_at, notes="", bg="", bg_type="", pump_event_id=""):
data = {
"eventType": BOLUS_EVENTTYPE,
"created_at": created_at,
"carbs": int(carbs),
"carbs": int(carbs) if carbs else 0,
"insulin": float(bolus),
"notes": notes,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
if bg:
if bg_type not in (NightscoutEntry.SENSOR, NightscoutEntry.FINGER):
raise InvalidBolusTypeException
if bg_type:
if bg_type not in (NightscoutEntry.SENSOR, NightscoutEntry.FINGER):
raise InvalidBolusTypeException("bg_type: %s (%s)" % (bg_type, data))
data.update({
"glucose": str(bg),
"glucoseType": bg_type
})
data.update({
"glucose": str(bg),
"glucoseType": bg_type
})
else:
data.update({
"glucose": str(bg)
})
return data
@staticmethod
@@ -64,48 +80,200 @@ class NightscoutEntry:
"created_at": created_at,
"enteredBy": ENTERED_BY
}
@staticmethod
def entry(sgv, created_at):
def entry(sgv, created_at, pump_event_id=""):
return {
"type": "sgv",
"sgv": int(sgv),
"date": int(1000 * arrow.get(created_at).timestamp()),
"dateString": arrow.get(created_at).strftime('%Y-%m-%dT%H:%M:%S%z'),
"device": ENTERED_BY,
"pump_event_id": pump_event_id,
# delta, direction are undefined
}
@staticmethod
def sitechange(created_at, reason=""):
def sitechange(created_at, reason="", pump_event_id=""):
return {
"eventType": SITECHANGE_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def basalsuspension(created_at, reason=""):
def basalsuspension(created_at, reason="", pump_event_id=""):
return {
"eventType": BASALSUSPENSION_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def activity(created_at, duration, reason="", event_type=ACTIVITY_EVENTTYPE):
def basalresume(created_at, pump_event_id=""):
return {
"eventType": BASALRESUME_EVENTTYPE,
"reason": "Basal resumed",
"notes": "Basal resumed",
"created_at": created_at,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def alarm(created_at, reason="", pump_event_id=""):
return {
"eventType": ALARM_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def cgm_alert(created_at, reason="", pump_event_id=""):
return {
"eventType": CGM_ALERT_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def cgm_start(created_at, reason="", pump_event_id=""):
return {
"eventType": CGM_START_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def cgm_join(created_at, reason="", pump_event_id=""):
return {
"eventType": CGM_JOIN_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def cgm_stop(created_at, reason="", pump_event_id=""):
return {
"eventType": CGM_STOP_EVENTTYPE,
"reason": reason,
"notes": reason,
"created_at": created_at,
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def activity(created_at, duration, reason="", event_type=ACTIVITY_EVENTTYPE, pump_event_id=""):
return {
"eventType": event_type,
"reason": reason,
"notes": reason,
"duration": float(duration),
"created_at": created_at,
"enteredBy": ENTERED_BY
"enteredBy": ENTERED_BY,
"pump_event_id": pump_event_id
}
@staticmethod
def devicestatus(created_at, batteryVoltage, batteryPercent, pump_event_id=""):
return {
"device": ENTERED_BY,
"created_at": created_at,
"pump": {
"clock": created_at,
"battery": {
"voltage": float(batteryVoltage),
"percent": int(batteryPercent) if batteryPercent else None,
"status": "%.0f%s" % (batteryPercent, '%')
},
},
"pump_event_id": pump_event_id
}
# TandemSource profile to Nightscout profile store entry
@staticmethod
def tandemsource_profile_store(profile: PumpProfile, pump_settings: PumpSettings) -> dict:
return {
# insulin duration in hours; Nightscout JS bug requires all top-level fields to be strings
"dia": "%s" % (profile.insulinDuration / 60),
# Sort by the typed segment.startTime (monotonic with timeAsSeconds)
# so the sort key is a well-typed int rather than an untyped dict value.
"carbratio": [
{
"time": minutes_to_ns_time(segment.startTime),
"timeAsSeconds": segment.startTime * 60,
"value": segment.carbRatio / 1000 # milliunits->units
} for segment in sorted(
(s for s in profile.tDependentSegs if not s.skip),
key=lambda s: s.startTime)
],
"carbs_hr": NIGHTSCOUT_PROFILE_CARBS_HR_VALUE,
"delay": NIGHTSCOUT_PROFILE_DELAY_VALUE,
"sens": [ # Correction factor / isf
{
"time": minutes_to_ns_time(segment.startTime),
"timeAsSeconds": segment.startTime * 60,
"value": segment.isf
} for segment in sorted(
(s for s in profile.tDependentSegs if not s.skip),
key=lambda s: s.startTime)
],
"basal": [
{
"time": minutes_to_ns_time(segment.startTime),
"timeAsSeconds": segment.startTime * 60,
"value": segment.basalRate / 1000 # milliunits->units
} for segment in sorted(
profile.tDependentSegs,
key=lambda s: s.startTime)
],
"target_low": [
{
"time": "00:00",
"timeAsSeconds": 0,
"value": pump_settings.cgmSettings.lowGlucoseAlertMgPerDl
}
],
"target_high": [
{
"time": "00:00",
"timeAsSeconds": 0,
"value": pump_settings.cgmSettings.highGlucoseAlertMgPerDl
}
],
"timezone": TIMEZONE_NAME, # tconnectsync settings timezone
"startDate": "1970-01-01T00:00:00.000Z",
"units": "mg/dl"
}
def minutes_to_ns_time(minutes_time: int) -> str:
hr = minutes_time // 60
mn = minutes_time % 60
return "%02d:%02d" % (hr, mn)
class InvalidBolusTypeException(RuntimeError):
pass
-194
View File
@@ -1,194 +0,0 @@
from os import stat
import sys
import arrow
try:
from ..secret import TIMEZONE_NAME
except Exception:
print('Unable to import parser secrets from secret.py')
sys.exit(1)
"""
Conversion methods for parsing raw t:connect data into
a more digestable format, which is used internally.
"""
class TConnectEntry:
BASAL_EVENTS = { 0: "Suspension", 1: "Profile", 2: "TempRate", 3: "Algorithm" }
@staticmethod
def _epoch_parse(x):
# data["x"] is an integer epoch timestamp which, when read as an equivalent timestamp
# stored in Pacific time (America/Los_Angeles), contains the user's local time, but
# with the wrong timezone data attached.
#
# For example, data["x"] references UTC timestamp 2020-09-01T13:00:00+00:00,
# which when read in Pacific time is equivalent to 2020-09-01T06:00:00-07:00.
# However, the user's timezone is Eastern time, so the timezone of America/Los_Angeles
# is overwritten with America/New_York, resulting in 2020-09-01T06:00:00-04:00, the
# correct timestamp.
return arrow.get(x, tzinfo="America/Los_Angeles").replace(tzinfo=TIMEZONE_NAME)
@staticmethod
def _jsonp_epoch_parse(x):
return TConnectEntry._epoch_parse(int(x.replace('/Date(', '').replace('-0000)/', '')))
@staticmethod
def parse_ciq_basal_entry(data, delivery_type=""):
time = TConnectEntry._epoch_parse(data["x"])
duration_mins = data["duration"] / 60
basal_rate = data["y"]
return {
"time": time.format(),
"delivery_type": delivery_type,
"duration_mins": duration_mins,
"basal_rate": basal_rate,
}
@staticmethod
def manual_suspension_to_basal_entry(parsedSuspension, seconds):
duration_mins = seconds / 60
return {
"time": parsedSuspension["time"],
"delivery_type": "%s suspension" % parsedSuspension["suspendReason"],
"duration_mins": duration_mins,
"basal_rate": 0.0
}
@staticmethod
def parse_suspension_entry(data):
time = TConnectEntry._epoch_parse(data["x"])
return {
"time": time.format(),
"continuation": data["continuation"],
"suspendReason": data["suspendReason"],
}
@staticmethod
def _datetime_parse(date):
return arrow.get(date, tzinfo=TIMEZONE_NAME)
@staticmethod
def parse_cgm_entry(data):
# EventDateTime is stored in the user's timezone.
return {
"time": TConnectEntry._datetime_parse(data["EventDateTime"]).format(),
"reading": data["Readings (CGM / BGM)"],
"reading_type": data["Description"],
}
@staticmethod
def parse_iob_entry(data):
# EventDateTime is stored in the user's timezone.
return {
"time": TConnectEntry._datetime_parse(data["EventDateTime"]).format(),
"iob": data["IOB"],
"event_id": data["EventID"],
}
@staticmethod
def parse_csv_basal_entry(data, duration_mins=None):
# EventDateTime is stored in the user's timezone.
return {
"time": TConnectEntry._datetime_parse(data["EventDateTime"]).format(),
"delivery_type": "Unknown",
"duration_mins": duration_mins,
"basal_rate": data["BasalRate"],
}
@staticmethod
def parse_bolus_entry(data):
# All DateTime's are stored in the user's timezone.
def is_complete(s):
return s and int(s) == 1
complete = is_complete(data["ExtendedBolusIsComplete"]) or is_complete(data["BolusIsComplete"])
extended_bolus = ("extended" in data["Description"].lower())
return {
"description": data["Description"],
"complete": "1" if complete else "",
"completion": data["CompletionStatusDesc"] if not extended_bolus else data["BolexCompletionStatusDesc"],
"request_time": TConnectEntry._datetime_parse(data["RequestDateTime"]).format() if not extended_bolus else None,
"completion_time": TConnectEntry._datetime_parse(data["CompletionDateTime"]).format() if not extended_bolus else None,
"insulin": data["InsulinDelivered"],
"requested_insulin": data["ActualTotalBolusRequested"],
"carbs": data["CarbSize"],
"bg": data["BG"], # Note: can be empty string for automatic Control-IQ boluses
"user_override": data["UserOverride"],
"extended_bolus": "1" if extended_bolus else "",
# Note: completion time can be empty if the extended bolus is in progress
"bolex_completion_time": TConnectEntry._datetime_parse(data["BolexCompletionDateTime"]).format() if data["BolexCompletionDateTime"] and complete and extended_bolus else None,
"bolex_start_time": TConnectEntry._datetime_parse(data["BolexStartDateTime"]).format() if data["BolexStartDateTime"] and complete and extended_bolus else None,
}
@staticmethod
def parse_reading_entry(data):
return {
"time": TConnectEntry._datetime_parse(data["EventDateTime"]).format(),
"bg": data["Readings (CGM / BGM)"],
"type": data["Description"]
}
ACTIVITY_EVENTS = { 1: "Sleep", 2: "Exercise", 3: "AutoBolus", 4: "CarbOnly" }
@staticmethod
def parse_ciq_activity_event(data):
if data["eventType"] not in TConnectEntry.ACTIVITY_EVENTS.keys():
raise UnknownCIQActivityEventException(data)
time = TConnectEntry._epoch_parse(data["x"])
return {
"time": time.format(),
"duration_mins": data["duration"] / 60,
"event_type": TConnectEntry.ACTIVITY_EVENTS[data["eventType"]]
}
BASALSUSPENSION_EVENTS = {
# site-cart corresponds to a Site or Cartridge change,
# specifically a Tubing Filled: Norm AND a Cannula Filled: Norm alert.
# (This means that a typical changing of a cartridge and then a site
# will result in two consecutive events of this type.)
"site-cart": "Site/Cartridge Change",
# alarm corresponds to one of the following:
# - an Empty Cartridge alarm
# - a Pump shutdown
"alarm": "Empty Cartridge/Pump Shutdown",
# manual corresponds to a Pumping Suspended by User event
"manual": "User Suspended"
}
BASALSUSPENSION_SKIPPED_EVENTS = {
# basal-profile events are not very useful; with ControlIQ enabled,
# Tandem does not show them in the tconnect UI.
"basal-profile",
# If an event continues to occur after the date switches over to the next
# day, then the pump generates a "previous" event. This isn't useful to
# us, so we skip them.
"previous",
}
@staticmethod
def parse_basalsuspension_event(data):
if data["SuspendReason"] in TConnectEntry.BASALSUSPENSION_SKIPPED_EVENTS:
return None
if data["SuspendReason"] not in TConnectEntry.BASALSUSPENSION_EVENTS.keys():
raise UnknownBasalSuspensionEventException(data)
time = TConnectEntry._jsonp_epoch_parse(data["EventDateTime"])
return {
"time": time.format(),
"event_type": TConnectEntry.BASALSUSPENSION_EVENTS[data["SuspendReason"]]
}
class UnknownCIQActivityEventException(Exception):
def __init__(self, data):
super().__init__("Unknown CIQ activity event type: %s" % data)
class UnknownBasalSuspensionEventException(Exception):
def __init__(self, data):
super().__init__("Unknown basal suspension event type: %s" % data)
-113
View File
@@ -1,113 +0,0 @@
import logging
import datetime
import arrow
import time
from .util import timeago
from .api.common import ApiException
from .sync.basal import (
process_ciq_basal_events,
add_csv_basal_events,
ns_write_basal_events
)
from .sync.bolus import (
process_bolus_events,
ns_write_bolus_events
)
from .sync.iob import (
process_iob_events,
ns_write_iob_events
)
from .sync.cgm import (
process_cgm_events,
ns_write_cgm_events
)
from .sync.pump_events import (
process_ciq_activity_events,
process_basalsuspension_events,
ns_write_pump_events
)
from .parser.tconnect import TConnectEntry
from .features import BASAL, BOLUS, IOB, BOLUS_BG, CGM, DEFAULT_FEATURES, PUMP_EVENTS
logger = logging.getLogger(__name__)
"""
Given a TConnectApi object and start/end range, performs a single
cycle of synchronizing data within the time range.
If pretend is true, then doesn't actually write data to Nightscout.
"""
def process_time_range(tconnect, nightscout, time_start, time_end, pretend, features=DEFAULT_FEATURES):
logger.info("Downloading t:connect ControlIQ data")
try:
ciqTherapyTimelineData = tconnect.controliq.therapy_timeline(time_start, time_end)
except ApiException as e:
# The ControlIQ API returns a 404 if the user did not have a ControlIQ enabled
# device in the time range which is queried. Since it launched in early 2020,
# ignore 404's before February.
if e.status_code == 404 and time_start.date() < datetime.date(2020, 2, 1):
logger.warning("Ignoring HTTP 404 for ControlIQ API request before Feb 2020")
ciqTherapyTimelineData = None
else:
raise e
logger.info("Downloading t:connect CSV data")
csvdata = tconnect.ws2.therapy_timeline_csv(time_start, time_end)
readingData = csvdata["readingData"]
iobData = csvdata["iobData"]
csvBasalData = csvdata["basalData"]
bolusData = csvdata["bolusData"]
if readingData and len(readingData) > 0:
lastReading = readingData[-1]['EventDateTime'] if 'EventDateTime' in readingData[-1] else 0
lastReading = TConnectEntry._datetime_parse(lastReading)
logger.debug(readingData[-1])
logger.info("Last CGM reading from t:connect: %s (%s)" % (lastReading, timeago(lastReading)))
else:
logger.warning("No last CGM reading is able to be determined")
added = 0
cgmData = None
if CGM in features or BOLUS_BG in features:
logger.debug("Processing CGM events")
cgmData = process_cgm_events(readingData)
if CGM in features:
logger.debug("Writing CGM events")
added += ns_write_cgm_events(nightscout, cgmData, pretend)
if BASAL in features:
basalEvents = process_ciq_basal_events(ciqTherapyTimelineData)
if csvBasalData:
logger.debug("CSV basal data found: processing it")
add_csv_basal_events(basalEvents, csvBasalData)
else:
logger.debug("No CSV basal data found")
added += ns_write_basal_events(nightscout, basalEvents, pretend=pretend)
if PUMP_EVENTS in features:
pumpEvents = process_ciq_activity_events(ciqTherapyTimelineData)
logger.debug("CIQ activity events: %s" % pumpEvents)
ws2BasalSuspension = tconnect.ws2.basalsuspension(time_start, time_end)
bsPumpEvents = process_basalsuspension_events(ws2BasalSuspension)
logger.debug("basalsuspension events: %s" % bsPumpEvents)
pumpEvents += bsPumpEvents
added += ns_write_pump_events(nightscout, pumpEvents, pretend=pretend)
if BOLUS in features:
bolusEvents = process_bolus_events(bolusData)
added += ns_write_bolus_events(nightscout, bolusEvents, pretend=pretend, include_bg=(BOLUS_BG in features))
if IOB in features:
iobEvents = process_iob_events(iobData)
added += ns_write_iob_events(nightscout, iobEvents, pretend=pretend)
logger.info("Wrote %d events to Nightscout this process cycle" % added)
return added
+48 -3
View File
@@ -4,6 +4,9 @@ from dotenv import dotenv_values
cwd_path = os.path.join(os.getcwd(), '.env')
global_path = os.path.join(pathlib.Path.home(), '.config/tconnectsync/.env')
cwd_creds_path = os.path.join(os.getcwd(), '.creds_cache')
global_creds_path = os.path.join(pathlib.Path.home(), '.config/tconnectsync/.creds_cache')
values = {}
if os.path.exists(cwd_path):
@@ -16,10 +19,18 @@ else:
def get(val, default=None):
return os.environ.get(val, values.get(val, default))
def get_one_of(name, default=None, options=[]):
val = get(name, default)
if val not in options:
print("Error: %s must be one of: %s" % (name, options))
print("Current value: %s" % val)
sys.exit(1)
return val
def get_number(name, default):
val = get(name, default)
try:
return int(val)
return float(val)
except ValueError:
print("Error: %s must be a number." % name)
print("Current value: %s" % val)
@@ -30,24 +41,58 @@ def get_bool(name, default):
TCONNECT_EMAIL = get('TCONNECT_EMAIL', 'email@email.com')
TCONNECT_PASSWORD = get('TCONNECT_PASSWORD', 'password')
TCONNECT_REGION = get_one_of('TCONNECT_REGION', 'US', ['US', 'EU'])
PUMP_SERIAL_NUMBER = get_number('PUMP_SERIAL_NUMBER', '11111111')
PUMP_SERIAL_NUMBER = int(get_number('PUMP_SERIAL_NUMBER', '11111111'))
NS_URL = get('NS_URL', 'https://yournightscouturl/')
NS_SECRET = get('NS_SECRET', 'apisecret')
if not get('NS_SECRET') and get('API_SECRET'):
print('API_SECRET environment variable is set, overriding NS_SECRET')
NS_SECRET = get('API_SECRET')
NS_SKIP_TLS_VERIFY = get_bool('NS_SKIP_TLS_VERIFY', 'false')
NS_IGNORE_CONN_ERRORS = get_bool('NS_IGNORE_CONN_ERRORS', 'false')
# This should be the timezone your pump is set to.
TIMEZONE_NAME = get('TIMEZONE_NAME', 'America/New_York')
if not get('TIMEZONE_NAME') and get('TZ'):
print('TZ environment variable is set, overriding TIMEZONE_NAME')
TIMEZONE_NAME = get('TZ')
# Optional configuration
CACHE_CREDENTIALS = get_bool('CACHE_CREDENTIALS', 'true')
CACHE_CREDENTIALS_PATH = get('CACHE_CREDENTIALS', cwd_creds_path if os.path.exists(cwd_creds_path) else global_creds_path)
AUTOUPDATE_DEFAULT_SLEEP_SECONDS = get_number('AUTOUPDATE_DEFAULT_SLEEP_SECONDS', '300') # 5 minutes
AUTOUPDATE_MAX_SLEEP_SECONDS = get_number('AUTOUPDATE_MAX_SLEEP_SECONDS', '1500') # 25 minutes
AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS = get_number('AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS', '60') # 1 minute
AUTOUPDATE_USE_FIXED_SLEEP = get_bool('AUTOUPDATE_USE_FIXED_SLEEP', 'false')
AUTOUPDATE_FAILURE_MINUTES = get_number('AUTOUPDATE_FAILURE_MINUTES', '180') # 3 hours
AUTOUPDATE_NO_DATA_FAILURE_MINUTES = get_number('AUTOUPDATE_NO_DATA_FAILURE_MINUTES', '180') # 3 hours
AUTOUPDATE_FAILURE_MINUTES = get_number('AUTOUPDATE_FAILURE_MINUTES', '75') # 75 minutes
AUTOUPDATE_RESTART_ON_FAILURE = get_bool('AUTOUPDATE_RESTART_ON_FAILURE', 'false')
# Give up and exit non-zero after this many minutes of unbroken API/network
# failure, so the container platform notices (and, if configured, notifies).
# Distinct from AUTOUPDATE_RESTART_ON_FAILURE, which covers the pump not
# uploading -- a case where restarting achieves nothing. Set 0 to never exit.
AUTOUPDATE_API_FAILURE_MINUTES = get_number('AUTOUPDATE_API_FAILURE_MINUTES', '45') # 45 minutes
AUTOUPDATE_MAX_LOOP_INVOCATIONS = get_number('AUTOUPDATE_MAX_LOOP_INVOCATIONS', '-1')
NIGHTSCOUT_PROFILE_UPLOAD_MODE = get_one_of('NIGHTSCOUT_PROFILE_UPLOAD_MODE', 'add', ['add', 'replace'])
# When set, all possible history log event types are fetched from Tandem Source
FETCH_ALL_EVENT_TYPES = get_bool('FETCH_ALL_EVENT_TYPES', 'false')
# Default Nightscout profile segment fields which aren't stored by Tandem
NIGHTSCOUT_PROFILE_CARBS_HR_VALUE = get('NIGHTSCOUT_PROFILE_CARBS_HR_VALUE', '20')
NIGHTSCOUT_PROFILE_DELAY_VALUE = get('NIGHTSCOUT_PROFILE_DELAY_VALUE', '20')
IGNORE_ZERO_UNIT_BASAL = get_bool('IGNORE_ZERO_UNIT_BASAL', 'false')
ENABLE_TESTING_MODES = get_bool('ENABLE_TESTING_MODES', 'false')
SKIP_NS_LAST_UPLOADED_CHECK = get_bool('SKIP_NS_LAST_UPLOADED_CHECK', 'false')
REQUESTS_PROXY = get('REQUESTS_PROXY', '')
if __name__ == '__main__':
for k in locals():
-161
View File
@@ -1,161 +0,0 @@
import arrow
import logging
from ..parser.nightscout import (
BASAL_EVENTTYPE,
NightscoutEntry
)
from ..parser.tconnect import TConnectEntry
from ..secret import SKIP_NS_LAST_UPLOADED_CHECK
logger = logging.getLogger(__name__)
"""
Merges together input from the therapy timeline API
into a digestable format of basal data.
"""
def process_ciq_basal_events(data):
if data is None:
return []
suspensionEvents = {}
for s in data["suspensionDeliveryEvents"]:
entry = TConnectEntry.parse_suspension_entry(s)
suspensionEvents[entry["time"]] = entry
basalEvents = []
for b in data["basal"]["tempDeliveryEvents"]:
basalEvents.append(TConnectEntry.parse_ciq_basal_entry(b, delivery_type="tempDelivery"))
for b in data["basal"]["algorithmDeliveryEvents"]:
basalEvents.append(TConnectEntry.parse_ciq_basal_entry(b, delivery_type="algorithmDelivery"))
for b in data["basal"]["profileDeliveryEvents"]:
basalEvents.append(TConnectEntry.parse_ciq_basal_entry(b, delivery_type="profileDelivery"))
# Suspensions with suspendReason 'control-iq' will match a basal event found above.
for i in basalEvents:
if i["time"] in suspensionEvents:
i["delivery_type"] += " (" + suspensionEvents[i["time"]]["suspendReason"] + " suspension)"
del suspensionEvents[i["time"]]
# Suspensions with suspendReason 'manual' do not have an associated basal event,
# and require extra processing.
basalEvents.sort(key=lambda x: arrow.get(x["time"]))
unprocessedSuspensions = list(suspensionEvents.values())
unprocessedSuspensions.sort(key=lambda x: arrow.get(x["time"]))
# For the remaining suspensions which did not match with an existing basal event,
# add a new event manually. This means we need to calculate the duration of the
# suspension.
newEvents = []
for i in range(len(basalEvents)):
if len(unprocessedSuspensions) == 0:
break
existingTime = arrow.get(basalEvents[i]["time"])
unprocessedTime = arrow.get(unprocessedSuspensions[0]["time"])
# If we've found an event which occurs after the suspension, then the
# difference in their timestamps is the duration of the suspension.
if i > 0 and existingTime > unprocessedTime:
suspension = unprocessedSuspensions.pop(0)
# TConnect's internal duration object tracks the duration in seconds
seconds = (existingTime - unprocessedTime).seconds
newEvent = TConnectEntry.manual_suspension_to_basal_entry(suspension, seconds)
logger.debug("Creating basal event for unprocessed suspension: %s" % newEvent)
newEvents.append(newEvent)
# Any remaining suspensions which have not been processed have not ended,
# which means we do not know their duration; so we will skip them (for now)
# Add any new events and re-sort
if newEvents:
basalEvents += newEvents
basalEvents.sort(key=lambda x: arrow.get(x["time"]))
return basalEvents
"""
Processes basal data input from the therapy timeline CSV (which only
exists for pre Control-IQ data) into a digestable format.
"""
def add_csv_basal_events(basalEvents, data):
last_entry = {}
for row in data:
entry = TConnectEntry.parse_csv_basal_entry(row)
if last_entry:
diff_mins = (arrow.get(entry["time"]) - arrow.get(last_entry["time"])).seconds // 60
entry["duration_mins"] = diff_mins
basalEvents.append(entry)
last_entry = entry
basalEvents.sort(key=lambda x: arrow.get(x["time"]))
return basalEvents
"""
Given processed basal data, adds basal events to Nightscout.
"""
def ns_write_basal_events(nightscout, basalEvents, pretend=False):
logger.debug("ns_write_basal_events: querying for last uploaded entry")
last_upload = nightscout.last_uploaded_entry(BASAL_EVENTTYPE)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout basal upload: %s" % last_upload_time)
if SKIP_NS_LAST_UPLOADED_CHECK:
logger.warning("Overriding last upload check")
last_upload = None
last_upload_time = None
add_count = 0
for event in basalEvents:
if last_upload_time and arrow.get(event["time"]) < last_upload_time:
if pretend:
logger.info("Skipping basal event before last upload time: %s" % event)
continue
recent_needs_update = False
if last_upload_time and arrow.get(event["time"]) == last_upload_time:
# If this entry has the same time as the most recent upload, but
# has newer info, then delete and recreate it.
recent_needs_update = (round(last_upload["duration"]) < round(event["duration_mins"]))
# If the timestamps are identical, and the duration is identical,
# then don't upload a duplicate entry of what we already have.
if not recent_needs_update:
continue
reason = event["delivery_type"]
if "suspendReason" in reason:
reason += " (" + reason["suspendReason"] + ")"
entry = NightscoutEntry.basal(
value=event["basal_rate"],
duration_mins=event["duration_mins"],
created_at=event["time"],
reason=reason
)
add_count += 1
logger.info(" Processing basal: %s entry: %s" % (event, entry))
if recent_needs_update:
logger.info("Replacing last uploaded entry: %s" % last_upload)
if not pretend:
entry['_id'] = last_upload['_id']
nightscout.put_entry(entry, entity='treatments')
elif not pretend:
nightscout.upload_entry(entry)
logger.debug("ns_write_basal_events: added %d events" % add_count)
return add_count
-104
View File
@@ -1,104 +0,0 @@
import arrow
import logging
from tconnectsync.sync.cgm import find_event_at
from ..parser.nightscout import (
BOLUS_EVENTTYPE,
NightscoutEntry
)
from ..parser.tconnect import TConnectEntry
from ..secret import SKIP_NS_LAST_UPLOADED_CHECK
logger = logging.getLogger(__name__)
"""
Given bolus data input from the therapy timeline CSV, converts it into a digestable format.
"""
def process_bolus_events(bolusdata, cgmEvents=None):
bolusEvents = []
for b in bolusdata:
parsed = TConnectEntry.parse_bolus_entry(b)
if parsed["completion"] != "Completed":
if parsed["insulin"] and float(parsed["insulin"]) > 0:
# Count non-completed bolus if any insulin was delivered (vs. the amount of insulin requested)
parsed["description"] += " (%s: requested %s units)" % (parsed["completion"], parsed["requested_insulin"])
else:
logger.warning("Skipping non-completed bolus data (was a bolus in progress?): %s parsed: %s" % (b, parsed))
continue
if parsed["bg"] and cgmEvents:
requested_at = parsed["request_time"] if not parsed["extended_bolus"] else parsed["bolex_start_time"]
parsed["bg_type"] = guess_bolus_bg_type(parsed["bg"], requested_at, cgmEvents)
bolusEvents.append(parsed)
bolusEvents.sort(key=lambda event: arrow.get(event["request_time"] if not event["extended_bolus"] else event["bolex_start_time"]))
return bolusEvents
"""
Determine whether the given BG specified in the bolus is identical to the
most recent CGM reading at that time. If it is, return SENSOR.
Otherwise, return FINGER.
"""
def guess_bolus_bg_type(bg, created_at, cgmEvents):
if not cgmEvents:
return NightscoutEntry.FINGER
event = find_event_at(cgmEvents, created_at)
if event and str(event["bg"]) == str(bg):
return NightscoutEntry.SENSOR
return NightscoutEntry.FINGER
"""
Given processed bolus data, adds bolus events to Nightscout.
"""
def ns_write_bolus_events(nightscout, bolusEvents, pretend=False, include_bg=False, reading_events=None):
logger.debug("ns_write_bolus_events: querying for last uploaded entry")
last_upload = nightscout.last_uploaded_entry(BOLUS_EVENTTYPE)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout bolus upload: %s" % last_upload_time)
if SKIP_NS_LAST_UPLOADED_CHECK:
logger.warning("Overriding last upload check")
last_upload = None
last_upload_time = None
add_count = 0
for event in bolusEvents:
created_at = event["completion_time"] if not event["extended_bolus"] else event["bolex_start_time"]
if last_upload_time and arrow.get(created_at) <= last_upload_time:
if pretend:
logger.info("Skipping basal event before last upload time: %s" % event)
continue
if include_bg and event["bg"]:
entry = NightscoutEntry.bolus(
bolus=event["insulin"],
carbs=event["carbs"],
created_at=created_at,
notes="{}{}{}".format(event["description"], " (Override)" if event["user_override"] == "1" else "", " (Extended)" if event["extended_bolus"] == "1" else ""),
bg=event["bg"],
bg_type=event["bg_type"]
)
else:
entry = NightscoutEntry.bolus(
bolus=event["insulin"],
carbs=event["carbs"],
created_at=created_at,
notes="{}{}{}".format(event["description"], " (Override)" if event["user_override"] == "1" else "", " (Extended)" if event["extended_bolus"] == "1" else "")
)
add_count += 1
logger.info(" Processing bolus: %s entry: %s" % (event, entry))
if not pretend:
nightscout.upload_entry(entry)
return add_count
-69
View File
@@ -1,69 +0,0 @@
import json
import arrow
import logging
from ..parser.tconnect import TConnectEntry
from ..parser.nightscout import NightscoutEntry
logger = logging.getLogger(__name__)
def process_cgm_events(readingData):
data = []
for r in readingData:
data.append(TConnectEntry.parse_reading_entry(r))
return data
"""
Given reading data and a time, finds the BG reading event which would have
been the current one at that time. e.g., it looks before the given time,
not after.
This is a heuristic for checking whether the BG component of a bolus was
manually entered or inferred based on the pump's CGM.
"""
def find_event_at(cgmEvents, find_time):
find_t = arrow.get(find_time)
events = list(map(lambda x: (arrow.get(x["time"]), x), cgmEvents))
events.sort()
closestReading = None
for t, r in events:
if t > find_t:
break
closestReading = r
return closestReading
"""
Given processed CGM data, adds reading entries to Nightscout.
"""
def ns_write_cgm_events(nightscout, cgmEvents, pretend=False):
logger.debug("ns_write_cgm_events: querying for last uploaded entry")
last_upload = nightscout.last_uploaded_bg_entry()
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["dateString"])
logger.info("Last Nightscout CGM upload: %s" % last_upload_time)
add_count = 0
for event in cgmEvents:
created_at = event["time"]
if last_upload_time and arrow.get(created_at) <= last_upload_time:
if pretend:
logger.info("Skipping CGM event before last upload time: %s" % event)
continue
entry = NightscoutEntry.entry(
sgv=event["bg"],
created_at=created_at
)
add_count += 1
logger.info(" Processing cgm reading: %s entry: %s" % (event, entry))
if not pretend:
nightscout.upload_entry(entry, entity='entries')
return add_count
-59
View File
@@ -1,59 +0,0 @@
import arrow
import logging
from ..parser.nightscout import (
IOB_ACTIVITYTYPE,
NightscoutEntry
)
from ..parser.tconnect import TConnectEntry
logger = logging.getLogger(__name__)
"""
Given IOB data input from the therapy timeline CSV, converts it into a digestable format.
"""
def process_iob_events(iobdata):
iobEvents = []
for d in iobdata:
iobEvents.append(TConnectEntry.parse_iob_entry(d))
iobEvents.sort(key=lambda x: arrow.get(x["time"]))
return iobEvents
"""
Given processed IOB data, creates a single Nightscout activity definition to store IOB.
"""
def ns_write_iob_events(nightscout, iobEvents, pretend=False):
logger.debug("ns_write_iob_events: querying for last uploaded entry")
last_upload = nightscout.last_uploaded_activity(IOB_ACTIVITYTYPE)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout iob upload: %s" % last_upload_time)
if not iobEvents or len(iobEvents) == 0:
logger.info("No IOB events present from API: skipping")
return 0
event = iobEvents[-1]
if last_upload_time and arrow.get(event["time"]) <= last_upload_time:
logger.info(" Skipping already uploaded iob event: %s" % event)
return 0
entry = NightscoutEntry.iob(
iob=event["iob"],
created_at=event["time"]
)
logger.info(" Processing iob: %s entry: %s" % (event, entry))
if not pretend:
nightscout.upload_entry(entry, entity='activity')
# Delete the previous activity
if last_upload and '_id' in last_upload:
logger.info(" Deleting old iob entry: %s" % last_upload)
if not pretend:
nightscout.delete_entry('activity/{}'.format(last_upload['_id']))
return 1
-206
View File
@@ -1,206 +0,0 @@
import arrow
import logging
from ..parser.nightscout import (
SITECHANGE_EVENTTYPE,
BASALSUSPENSION_EVENTTYPE,
EXERCISE_EVENTTYPE,
SLEEP_EVENTTYPE,
ACTIVITY_EVENTTYPE,
NightscoutEntry
)
from ..parser.tconnect import TConnectEntry
from ..secret import SKIP_NS_LAST_UPLOADED_CHECK
logger = logging.getLogger(__name__)
"""
Given a list of "activity events" from the CIQ therapy timeline endpoint,
process it into our internal events format.
These events contain a duration.
"""
def process_ciq_activity_events(data):
events = []
for event in data["events"]:
events.append(TConnectEntry.parse_ciq_activity_event(event))
return events
"""
Given a list of "basal suspension events" from the basalsuspension WS2 endpoint,
process it into our internal events format.
These events do NOT contain a duration.
"""
def process_basalsuspension_events(data):
events = []
for event in data['BasalSuspension']:
parsed = TConnectEntry.parse_basalsuspension_event(event)
if parsed:
events.append(parsed)
return events
"""
Given processed pump event data (of various types), write them to Nightscout
"""
def ns_write_pump_events(nightscout, pumpEvents, pretend=False):
count = 0
siteChangeEvents = []
emptyCartEvents = []
userSuspendedEvents = []
exerciseEvents = []
sleepEvents = []
activityEvents = []
for event in pumpEvents:
if event["event_type"] == TConnectEntry.BASALSUSPENSION_EVENTS["site-cart"]:
siteChangeEvents.append(event)
elif event["event_type"] in TConnectEntry.BASALSUSPENSION_EVENTS["alarm"]:
emptyCartEvents.append(event)
elif event["event_type"] in TConnectEntry.BASALSUSPENSION_EVENTS["manual"]:
userSuspendedEvents.append(event)
elif event["event_type"] == "Exercise":
exerciseEvents.append(event)
elif event["event_type"] == "Sleep":
sleepEvents.append(event)
elif event["event_type"] in TConnectEntry.ACTIVITY_EVENTS.values():
activityEvents.append(event)
logger.debug("siteChangeEvents: %s" % siteChangeEvents)
logger.debug("emptyCartEvents: %s" % emptyCartEvents)
logger.debug("userSuspendedEvents: %s" % userSuspendedEvents)
logger.debug("exerciseEvents: %s" % exerciseEvents)
logger.debug("sleepEvents: %s" % sleepEvents)
logger.debug("activityEvents: %s" % activityEvents)
count += ns_write_pump_sitechange_events(nightscout, siteChangeEvents, pretend=pretend)
count += ns_write_empty_cart_events(nightscout, emptyCartEvents, pretend=pretend)
count += ns_write_user_suspended_events(nightscout, userSuspendedEvents, pretend=pretend)
count += ns_write_exercise_activity_events(nightscout, exerciseEvents, pretend=pretend)
count += ns_write_sleep_activity_events(nightscout, sleepEvents, pretend=pretend)
count += ns_write_activity_events(nightscout, activityEvents, pretend=pretend)
return count
def ns_write_pump_sitechange_events(nightscout, siteChangeEvents, pretend=False):
return _ns_write_pump_events(
nightscout,
siteChangeEvents,
lambda event: NightscoutEntry.sitechange(
created_at=event["time"],
reason=event["event_type"]
),
SITECHANGE_EVENTTYPE,
pretend=pretend)
def ns_write_empty_cart_events(nightscout, emptyCartEvents, pretend=False):
return _ns_write_pump_events(
nightscout,
emptyCartEvents,
lambda event: NightscoutEntry.basalsuspension(
created_at=event["time"],
reason=event["event_type"]
),
BASALSUSPENSION_EVENTTYPE,
pretend=pretend)
def ns_write_user_suspended_events(nightscout, userSuspendedEvents, pretend=False):
return _ns_write_pump_events(
nightscout,
userSuspendedEvents,
lambda event: NightscoutEntry.basalsuspension(
created_at=event["time"],
reason=event["event_type"]
),
BASALSUSPENSION_EVENTTYPE,
pretend=pretend)
def ns_write_exercise_activity_events(nightscout, exerciseEvents, pretend=False):
return _ns_write_pump_events(
nightscout,
exerciseEvents,
lambda event: NightscoutEntry.activity(
created_at=event["time"],
reason=event["event_type"],
duration=event["duration_mins"],
event_type=EXERCISE_EVENTTYPE
),
EXERCISE_EVENTTYPE,
pretend=pretend)
def ns_write_sleep_activity_events(nightscout, sleepEvents, pretend=False):
return _ns_write_pump_events(
nightscout,
sleepEvents,
lambda event: NightscoutEntry.activity(
created_at=event["time"],
reason=event["event_type"],
duration=event["duration_mins"],
event_type=SLEEP_EVENTTYPE
),
SLEEP_EVENTTYPE,
pretend=pretend)
def ns_write_activity_events(nightscout, activityEvents, pretend=False):
return _ns_write_pump_events(
nightscout,
activityEvents,
lambda event: NightscoutEntry.activity(
created_at=event["time"],
reason=event["event_type"],
duration=event["duration_mins"]
),
ACTIVITY_EVENTTYPE,
pretend=pretend)
def _ns_write_pump_events(nightscout, events, buildNsEventFunc, eventType, pretend=False):
if len(events) == 0:
logger.debug("No %s events to process" % eventType)
return 0
logger.debug("ns_write_pump_events: querying for last %s" % eventType)
last_upload = nightscout.last_uploaded_entry(eventType)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout %s: %s" % (eventType, last_upload_time))
if SKIP_NS_LAST_UPLOADED_CHECK:
logger.warning("Overriding last upload check")
last_upload = None
last_upload_time = None
add_count = 0
for event in events:
created_at = event["time"]
if last_upload_time and arrow.get(created_at) <= last_upload_time:
skip = True
if "duration_mins" in event.keys() and "duration" in last_upload.keys():
if created_at == last_upload["created_at"] and float(event["duration_mins"]) > float(last_upload["duration"]):
logger.info("Latest %s event needs updating: duration has increased from %s to %s: %s" % (eventType, last_upload["duration"], event["duration_mins"], event))
logger.info("Deleting previous %s: %s" % (eventType, last_upload))
nightscout.delete_entry('treatments/%s' % last_upload["_id"])
skip = False
if skip:
if pretend:
logger.info("Skipping %s event before last upload time: %s" % (eventType, event))
continue
entry = buildNsEventFunc(event)
add_count += 1
logger.info(" Processing %s: %s entry: %s" % (eventType, event, entry))
if not pretend:
nightscout.upload_entry(entry)
return add_count
@@ -0,0 +1,297 @@
import time
import logging
import datetime
import sys
import arrow
import requests
from ...api.common import ApiException, ApiLoginException
from ...features import DEFAULT_FEATURES
from ...api.tandemsource import naive_local_to_utc
from .process import ProcessTimeRange
from .choose_device import ChooseDevice
logger = logging.getLogger(__name__)
# Shortest wait after a failed poll. Doubles per consecutive failure, capped at
# AUTOUPDATE_DEFAULT_SLEEP_SECONDS (5 min by default): 30, 60, 120, 240, 300...
RETRY_INITIAL_SLEEP_SECONDS = 30
# Consecutive failures before the retry log line escalates from WARNING to
# ERROR, so a sustained outage doesn't hide quietly inside the backoff.
RETRY_ESCALATE_AFTER_FAILURES = 3
class TandemSourceAutoupdate:
"""Wrap access to secrets for easier testing."""
def __init__(self, secret):
self.secret = secret
self.autoupdate_invocations = 0
self.consecutive_failures = 0
self.first_failure_time = None
self.last_max_date_with_events = None
self.last_event_time = 0
self.last_attempt_time = 0
self.last_event_seqnum = None
self.last_successful_process_time_range = None
self.time_diffs_between_attempts = []
self.time_diffs_between_updates = []
"""
Performs the auto-update functionality. Runs indefinitely in a loop
until stopped (ctrl+c), or a maximum of AUTOUPDATE_MAX_LOOP_INVOCATIONS times.
Stops if AUTOUPDATE_RESTART_ON_FAILURE is set and an error occurs.
"""
def process(self, tconnect, nightscout, pretend, features=None):
if features is None:
features = DEFAULT_FEATURES
# Query for data, find exact interval to cut down on API calls
# Refresh API token. If failure, die, have wrapper script re-run.
self.autoupdate_start = time.time()
while True:
try:
logger.debug("autoupdate loop")
now = time.time()
time_end = datetime.datetime.now()
time_start = time_end - datetime.timedelta(days=1)
tconnectDevice = ChooseDevice(self.secret, tconnect).choose()
event_seqnum = None
cur_max_date_with_events = arrow.get(naive_local_to_utc(tconnectDevice['maxDateOfEvents'])).float_timestamp
if not self.last_max_date_with_events or cur_max_date_with_events > self.last_max_date_with_events:
logger.info('New reported tandemsource data. (cur_max_date: %s last_max_date: %s)' % (cur_max_date_with_events, self.last_max_date_with_events))
if pretend:
logger.info('Would update now if not in pretend mode')
else:
added, event_seqnum = ProcessTimeRange(tconnect, nightscout, tconnectDevice, pretend, self.secret, features=features).process(time_start, time_end)
logger.info('Added %d items from ProcessTimeRange' % added)
self.last_successful_process_time_range = now
# Track the time it took to find a new event between runs,
# but skip this calculation the first process cycle (since
# we don't know at what exact point the event index changed)
if self.last_event_seqnum:
# A negative diff means the pump's previously-reported maxDateWithEvents
# was in the future of wall-clock `now` — almost always a timezone /
# clock-skew issue (e.g. pump timestamps tagged as UTC but actually
# local time). Recording it would poison the rolling average and
# eventually produce a negative sleep_secs that crashes time.sleep().
diff = now - self.last_max_date_with_events
if diff >= 0:
self.time_diffs_between_updates.append(diff)
logger.debug('Updating tracking of time since last update: %s' % self.time_diffs_between_updates)
else:
logger.warning(
'Skipping negative time diff (%0.1fs) — likely pump clock skew or timezone mismatch' % diff
)
# Mark the last event index uploaded from the pump and timestamp
if event_seqnum:
self.last_event_seqnum = event_seqnum
self.last_event_time = now
self.last_max_date_with_events = cur_max_date_with_events
self.last_attempt_time = now
self.time_diffs_between_attempts = []
else:
logger.info('No new reported tandemsource data. cur_max_date: %s (%s) last_event_time: %s (%s)' % (
arrow.get(cur_max_date_with_events) if cur_max_date_with_events else None,
'%dm ago' % ((now - cur_max_date_with_events)//60) if cur_max_date_with_events else None,
arrow.get(self.last_event_time) if self.last_event_time else None,
'%dm ago' % ((now - self.last_event_time)//60) if self.last_event_time else None
))
# If we haven't seen the pump event index update in AUTOUPDATE_NO_DATA_FAILURE_MINUTES,
# then trigger an error and potentially restart.
# The most likely case here is that the pump isn't uploading right now.
if self.last_event_time and (now - self.last_event_time) >= 60 * self.secret.AUTOUPDATE_NO_DATA_FAILURE_MINUTES:
logger.error(AutoupdateNoEventIndexesDetectedError(
"%s: No new data event indexes have been detected for %d minutes. " % (datetime.datetime.now(), (now - self.last_event_time)//60) +
"New data might not be uploading."))
# TODO: restarting doesn't really help anything here.
# Should we notify the user?
if self.secret.AUTOUPDATE_RESTART_ON_FAILURE:
logger.error("Exiting with error code due to AUTOUPDATE_RESTART_ON_FAILURE")
return 1
# Similarly, if we HAVE seen pump event indexes update but have not successfully
# found any associated data updates from the tconnect API for AUTOUPDATE_NO_DATA_FAILURE_MINUTES,
# trigger an error and potentially restart. This could either be a tconnectsync problem,
# where we can see the indexes increasing, but it takes us until a period of no index
# update to reach our AUTOUPDATE_FAILURE_MINUTES threshold; or, a side effect of the
# above no indexes warning.
elif self.last_successful_process_time_range and (now - self.last_successful_process_time_range) >= 60 * self.secret.AUTOUPDATE_FAILURE_MINUTES:
logger.error(AutoupdateNoNewDataDetectedError(
"%s: No new data has been detected via the API for %d minutes (last: %s). " % (datetime.datetime.now(), (now - self.last_successful_process_time_range)//60, self.last_successful_process_time_range) +
"tconnectsync might not be functioning properly."))
if self.secret.AUTOUPDATE_RESTART_ON_FAILURE:
logger.error("%s: Exiting with error code due to AUTOUPDATE_RESTART_ON_FAILURE" % datetime.datetime.now())
return 1
# Track how long we've been retrying
if self.last_attempt_time:
self.time_diffs_between_attempts.append(now - self.last_attempt_time)
self.last_attempt_time = now
# If it's been 3 loops since the last time we found new data,
# then we're not in sync with the rate at which pump data is being
# uploaded, so
if len(self.time_diffs_between_attempts) >= 3:
# The pump hasn't sent us data that, based on previous cadence, we were expecting
logger.warning(AutoupdateNoIndexChangeWarning("Sleeping %d seconds after unexpected no index change based on previous cadence. (New data might be delayed.)" %
int(self.secret.AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS)))
logger.debug("Last event time: %s, time diffs between attempts: %s" % (self.last_event_time, self.time_diffs_between_attempts))
# The API answered, so any prior outage is over.
self.consecutive_failures = 0
self.first_failure_time = None
time.sleep(self.secret.AUTOUPDATE_UNEXPECTED_NO_INDEX_SLEEP_SECONDS)
# Since we bail early, update the invocations count and potentially exit after sleeping.
self.autoupdate_invocations += 1
if self.secret.AUTOUPDATE_MAX_LOOP_INVOCATIONS > 0 and self.autoupdate_invocations >= self.secret.AUTOUPDATE_MAX_LOOP_INVOCATIONS:
return 0
continue
# The API answered, so any prior outage is over.
self.consecutive_failures = 0
self.first_failure_time = None
sleep_secs = self.secret.AUTOUPDATE_DEFAULT_SLEEP_SECONDS
# Sleep for a rolling average of time between updates
if self.secret.AUTOUPDATE_USE_FIXED_SLEEP != 1:
logger.debug("Time diffs between updates: %s" % self.time_diffs_between_updates)
# Only keep the 10 latest time diffs
if len(self.time_diffs_between_updates) > 10:
self.time_diffs_between_updates = self.time_diffs_between_updates[1:]
# If we have less than 3 data points,
if len(self.time_diffs_between_updates) > 2:
sleep_secs = sum(self.time_diffs_between_updates) / len(self.time_diffs_between_updates)
# At minimum, update every AUTOUPDATE_MAX_SLEEP_SECONDS regardless
# of how often we're seeing new data appear
if sleep_secs > self.secret.AUTOUPDATE_MAX_SLEEP_SECONDS:
sleep_secs = self.secret.AUTOUPDATE_MAX_SLEEP_SECONDS
# Defensive: with the negative-diff filter above, sleep_secs should never be
# negative, but legacy state from before the fix or other unexpected inputs
# could still produce one. Clamp to AUTOUPDATE_DEFAULT_SLEEP_SECONDS so we
# don't crash with ValueError nor tight-loop the API.
if sleep_secs < 0:
logger.warning(
'Computed negative sleep duration (%0.1fs), falling back to default %ds' % (
sleep_secs, self.secret.AUTOUPDATE_DEFAULT_SLEEP_SECONDS
)
)
sleep_secs = self.secret.AUTOUPDATE_DEFAULT_SLEEP_SECONDS
logger.info('Sleeping for %0.01f sec' % sleep_secs)
time.sleep(sleep_secs)
self.autoupdate_invocations += 1
if self.secret.AUTOUPDATE_MAX_LOOP_INVOCATIONS > 0 and self.autoupdate_invocations >= self.secret.AUTOUPDATE_MAX_LOOP_INVOCATIONS:
return 0
except ApiLoginException:
# A credentials failure is not transient: retrying it in-process
# would hammer the login endpoint with attempts that cannot
# succeed, which is the exact ban risk the backoff below exists
# to prevent. Stay fatal so the user notices and fixes config.
raise
except (
ApiException,
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
requests.exceptions.ChunkedEncodingError,
requests.exceptions.RetryError,
) as e:
# Two failure families, one response. Transient network errors
# (DNS, refused connections, timeouts, mid-stream disconnects,
# urllib3 retry-budget exhaustion) and API errors that get()
# does not retry itself (it only handles 401 and 500 — a 404,
# 502 or 503 propagates) both used to exit the process and let
# Docker restart the container.
#
# Restarting is the worst possible response: the credentials
# cache dies with the process, so every restart performs a full
# login. During the 2026-07-16 EU outage that meant a fresh
# login every ~2 minutes for hours from a single IP. Staying in
# the loop keeps the cache warm and the login endpoint untouched.
self.consecutive_failures += 1
if self.first_failure_time is None:
self.first_failure_time = time.time()
sleep_secs = self._retry_sleep_seconds()
log = logger.error if self.consecutive_failures >= RETRY_ESCALATE_AFTER_FAILURES else logger.warning
log(
'Error during autoupdate poll (%d consecutive): %s. Sleeping %ds before retry.' % (
self.consecutive_failures, e, sleep_secs
)
)
time.sleep(sleep_secs)
# Staying alive forever would make a real outage silent on
# deployments whose only alarm is the container dying. Once the
# API has been unreachable for AUTOUPDATE_API_FAILURE_MINUTES,
# exit so the platform can restart us and raise its own alert.
failing_for = time.time() - self.first_failure_time
if self.secret.AUTOUPDATE_API_FAILURE_MINUTES > 0 and failing_for >= 60 * self.secret.AUTOUPDATE_API_FAILURE_MINUTES:
logger.error(
AutoupdateFailureError(
'%s: API has been failing for %d minutes (%d consecutive attempts). '
'Exiting so the container platform restarts and reports it.' % (
datetime.datetime.now(), failing_for // 60, self.consecutive_failures
)
)
)
return 1
self.autoupdate_invocations += 1
if self.secret.AUTOUPDATE_MAX_LOOP_INVOCATIONS > 0 and self.autoupdate_invocations >= self.secret.AUTOUPDATE_MAX_LOOP_INVOCATIONS:
return 0
def _retry_sleep_seconds(self):
"""Exponential backoff for consecutive failed polls: 30, 60, 120, 240,
then held at AUTOUPDATE_DEFAULT_SLEEP_SECONDS (300s default). The cap
reuses the existing poll interval because a failing API should never be
contacted more often than a healthy one."""
backoff = RETRY_INITIAL_SLEEP_SECONDS * (2 ** (self.consecutive_failures - 1))
return min(backoff, self.secret.AUTOUPDATE_DEFAULT_SLEEP_SECONDS)
class AutoupdateError(RuntimeError):
def __str__(self):
return "%s: %s" % (self.__class__.__name__, super().__str__())
class AutoupdateWarning(RuntimeWarning):
def __str__(self):
return "%s: %s" % (self.__class__.__name__, super().__str__())
class AutoupdateFailureError(AutoupdateError):
pass
class AutoupdateFailureWarning(AutoupdateWarning):
pass
class AutoupdateNoEventIndexesDetectedError(AutoupdateError):
pass
class AutoupdateNoNewDataDetectedError(AutoupdateError):
pass
class AutoupdateNoIndexChangeWarning(AutoupdateWarning):
pass
@@ -0,0 +1,78 @@
import arrow
import logging
from ...api.tandemsource import naive_local_to_utc
logger = logging.getLogger(__name__)
class ChooseDevice:
def __init__(self, secret, tconnect):
self.secret = secret
self.tconnect = tconnect
def choose(self):
tconnect = self.tconnect
pumpEventMetadata = tconnect.tandemsource.get_pumper().get('pumps', [])
if not pumpEventMetadata:
raise NoDevicesFound('No pumps are present on your Tandem Source account')
serialNumberToPump = {p['serialNumber']: p for p in pumpEventMetadata}
logger.info(f'Found {len(serialNumberToPump)} pumps: {serialNumberToPump.keys()}')
tconnectDevice = None
if self.secret.PUMP_SERIAL_NUMBER and str(self.secret.PUMP_SERIAL_NUMBER) != '11111111':
if not str(self.secret.PUMP_SERIAL_NUMBER) in serialNumberToPump.keys():
raise InvalidSerialNumber(f'Serial number {self.secret.PUMP_SERIAL_NUMBER} is not present on your account: choose one of {", ".join(serialNumberToPump.keys())}')
tconnectDevice = serialNumberToPump[str(self.secret.PUMP_SERIAL_NUMBER)]
# Warn if pump is stale (no events in >3 days)
try:
max_event_date = arrow.get(naive_local_to_utc(tconnectDevice["maxDateOfEvents"]))
age_days = (arrow.utcnow() - max_event_date).days
if age_days > 3:
logger.warning(
f"The selected pump (serial {tconnectDevice['serialNumber']}) has no events in the last {age_days} days "
f"(last seen: {tconnectDevice['maxDateOfEvents']}). "
"You may have switched to a new pump. Consider removing or updating PUMP_SERIAL_NUMBER in your config."
)
except Exception as e:
logger.debug(f"Could not parse maxDateOfEvents to check for staleness: {e}")
logger.info(f'Using pump with serial: {tconnectDevice["serialNumber"]} (deviceId: {tconnectDevice["assignmentId"]}, last seen: {tconnectDevice["maxDateOfEvents"]})')
else:
# The BFF device list includes pumps that have never uploaded
# (maxDateOfEvents is None); skip those when picking the most
# recent one, and only fall back to one of them if nothing else.
maxDateSeen = None
for pump in pumpEventMetadata:
if not pump.get('maxDateOfEvents'):
continue
pumpMaxDate = arrow.get(naive_local_to_utc(pump['maxDateOfEvents']))
if not tconnectDevice or pumpMaxDate > maxDateSeen:
maxDateSeen = pumpMaxDate
tconnectDevice = pump
# If no pump has any events yet, fall back to the first one.
if not tconnectDevice:
tconnectDevice = pumpEventMetadata[0]
logger.info(f'Using most recent pump (serial: {tconnectDevice["serialNumber"]}, deviceId: {tconnectDevice["assignmentId"]}, last seen: {tconnectDevice["maxDateOfEvents"]})')
return tconnectDevice
class InvalidSerialNumber(RuntimeError):
def __str__(self):
return "%s: %s" % (self.__class__.__name__, super().__str__())
class NoDevicesFound(RuntimeError):
def __str__(self):
return "%s: %s" % (self.__class__.__name__, super().__str__())
@@ -0,0 +1,20 @@
from ...features import DEFAULT_FEATURES
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from .choose_device import ChooseDevice
from .process import ProcessTimeRange
from ...api import TConnectApi
from ... import secret
import datetime
import logging
logger = logging.getLogger(__name__)
def fetch_oneshot(username, password, time_start=None, time_end=None, region=None):
tconnect = TConnectApi(username, password, region)
if not time_start and not time_end:
time_end = datetime.datetime.now()
time_start = time_end - datetime.timedelta(days=1)
tconnectDevice = ChooseDevice(secret, tconnect).choose()
return tconnect.tandemsource.pump_events(tconnectDevice['assignmentId'], time_start, time_end, fetch_all_event_types=secret.FETCH_ALL_EVENT_TYPES)
@@ -0,0 +1,8 @@
def insulin_float_round(amt):
if type(amt) != float:
return amt
return round(amt, 2)
def insulin_milliunits_to_real(amtMilli):
return insulin_float_round(amtMilli / 1000)
@@ -0,0 +1,17 @@
from ...features import DEFAULT_FEATURES
from .choose_device import ChooseDevice
from .process import ProcessTimeRange
from ... import secret
import datetime
def run_oneshot(tconnect, nightscout, pretend=False, features=DEFAULT_FEATURES, secret_arg=None, time_start=None, time_end=None):
if not time_start and not time_end:
time_end = datetime.datetime.now()
time_start = time_end - datetime.timedelta(days=1)
if not secret_arg:
secret_arg = secret
tconnectDevice = ChooseDevice(secret_arg, tconnect).choose()
return ProcessTimeRange(tconnect, nightscout, tconnectDevice, pretend, secret_arg, features).process(time_start, time_end)
+124
View File
@@ -0,0 +1,124 @@
import logging
import collections
import arrow
from types import ModuleType
from typing import Dict, Iterable, List, Optional, Protocol, Tuple, Type, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
from ...api.tandemsource import BffPump
class EventProcessor(Protocol):
"""Structural interface implemented by every Process* event handler."""
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str]) -> None: ...
def enabled(self) -> bool: ...
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]: ...
def write(self, ns_entries: List[dict]) -> int: ...
from ...features import DEVICE_STATUS, DEFAULT_FEATURES
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from .process_basal import ProcessBasal
from .process_basal_suspension import ProcessBasalSuspension
from .process_basal_resume import ProcessBasalResume
from .process_alarm import ProcessAlarm
from .process_bolus import ProcessBolus
from .process_cartridge import ProcessCartridge
from .process_cgm_alert import ProcessCGMAlert
from .process_cgm_start_join_stop import ProcessCGMStartJoinStop
from .process_cgm_reading import ProcessCGMReading
from .process_device_status import ProcessDeviceStatus
from .process_user_mode import ProcessUserMode
from .update_profiles import UpdateProfiles
logger = logging.getLogger(__name__)
class ProcessTimeRange:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnectDevice: "BffPump", pretend: bool, secret: ModuleType, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnectDevice['assignmentId']
self.max_date_with_events = tconnectDevice.get('maxDateOfEvents')
self.pretend = pretend
self.secret = secret
self.features = features
event_classes: Dict[str, Type[EventProcessor]] = {
EventClass.BASAL.name: ProcessBasal,
EventClass.BASAL_SUSPENSION.name: ProcessBasalSuspension,
EventClass.BASAL_RESUME.name: ProcessBasalResume,
EventClass.ALARM.name: ProcessAlarm,
EventClass.BOLUS.name: ProcessBolus,
EventClass.CARTRIDGE.name: ProcessCartridge,
EventClass.CGM_ALERT.name: ProcessCGMAlert,
EventClass.CGM_START_JOIN_STOP.name: ProcessCGMStartJoinStop,
EventClass.CGM_READING.name: ProcessCGMReading,
EventClass.USER_MODE.name: ProcessUserMode,
EventClass.DEVICE_STATUS.name: ProcessDeviceStatus
}
updater_classes = [
UpdateProfiles
]
def process(self, time_start: arrow.Arrow, time_end: arrow.Arrow) -> Tuple[int, Optional[int]]:
fetch_all_event_types = self.secret.FETCH_ALL_EVENT_TYPES or DEVICE_STATUS in self.features
logger.info(f"ProcessTimeRange time_start={time_start} time_end={time_end} tconnect_device_id={self.tconnect_device_id} features={self.features} fetch_all_event_types={fetch_all_event_types}")
events = self.tconnect.tandemsource.pump_events(self.tconnect_device_id, time_start, time_end, fetch_all_event_types=fetch_all_event_types)
events_first_time = None
events_last_time = None
last_event_seqnum = None
for_eventclass = collections.defaultdict(list)
for event in events:
if not events_first_time:
events_first_time = event.eventTimestamp
if not events_last_time:
events_last_time = event.eventTimestamp
if not last_event_seqnum:
last_event_seqnum = event.seqNum
events_first_time = min(events_first_time, event.eventTimestamp)
events_last_time = max(events_last_time, event.eventTimestamp)
last_event_seqnum = max(event.seqNum, last_event_seqnum)
clazz = EventClass.for_event(event)
if clazz:
for_eventclass[clazz.name].append(event)
count_by_eventclass = {k: len(v) for k,v in for_eventclass.items()}
logger.info(f"Found events: {count_by_eventclass}")
processed_count = 0
for clazz, events in for_eventclass.items():
if clazz in self.event_classes.keys():
c = self.event_classes[clazz](self.tconnect, self.nightscout, self.tconnect_device_id, self.pretend, self.features)
if c.enabled():
logger.info("%s is enabled from features %s" % (clazz, self.features))
# Cap events_last_time at time_end to handle pump clock drift
# Ensure time_end is timezone-aware for comparison
time_end_aware = arrow.get(time_end)
capped_time_end = min(events_last_time, time_end_aware) if events_last_time else time_end_aware
# events_first_time is populated whenever for_eventclass has entries
# (i.e. at least one event was seen); fall back to time_start otherwise.
time_start_for_events = events_first_time if events_first_time else time_start
ns_entries = c.process(events, time_start_for_events, capped_time_end)
w = c.write(ns_entries)
if w:
processed_count += w
else:
logger.info("Skipping %s, is not enabled from features %s" % (clazz, self.features))
for updater_class in self.updater_classes:
updater = updater_class(self.tconnect, self.nightscout, self.tconnect_device_id, self.pretend, self.features)
if updater.enabled():
logger.info("%s is enabled from features %s" % (updater_class.__name__, self.features))
done = updater.update(self.pretend)
logger.info("%s completed with update required: %s" % (updater_class.__name__, done))
else:
logger.info("Skipping %s, is not enabled from features %s" % (updater_class.__name__, self.features))
logger.info("Processed %d events. Last event ID seen: %d" % (processed_count if processed_count else 0, last_event_seqnum if last_event_seqnum else -1))
return processed_count, last_event_seqnum
@@ -0,0 +1,96 @@
import logging
import arrow
from typing import Iterable, List, Union, TYPE_CHECKING
from typing_extensions import assert_never
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
ALARM_EVENTTYPE,
NightscoutEntry
)
logger = logging.getLogger(__name__)
AlarmOrMalfunction = Union[eventtypes.LidAlarmActivated, eventtypes.LidMalfunctionActivated]
class ProcessAlarm:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PUMP_EVENTS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessAlarm: querying for last uploaded alarm")
last_upload = self.nightscout.last_uploaded_entry(ALARM_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout alarm upload: %s" % last_upload_time)
ns_entries = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping Alarm event not after last upload time: %s (time range: %s - %s)" % (event, time_start, time_end))
continue
if self.skip_event(event):
continue
ns_entries.append(self.alarm_to_nsentry(event))
return ns_entries
def skip_event(self, event: AlarmOrMalfunction) -> bool:
if not isinstance(event, eventtypes.LidAlarmActivated):
return False
return event.alarmId in (
eventtypes.LidAlarmActivated.AlarmidEnum.ResumePumpAlarm,
eventtypes.LidAlarmActivated.AlarmidEnum.ResumePumpAlarm2
)
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def alarm_to_nsentry(self, event: AlarmOrMalfunction) -> dict:
if isinstance(event, eventtypes.LidAlarmActivated):
alarmId = event.alarmId
reason = alarmId.name if alarmId is not None else "Alarm%s" % event.alarmIdRaw
return NightscoutEntry.alarm(
created_at = event.eventTimestamp.format(),
reason = reason,
pump_event_id = "%s" % event.seqNum
)
elif isinstance(event, eventtypes.LidMalfunctionActivated):
return NightscoutEntry.alarm(
created_at = event.eventTimestamp.format(),
reason = "Malfunction",
pump_event_id = "%s" % event.seqNum
)
assert_never(event)
@@ -0,0 +1,111 @@
import datetime
import logging
import arrow
from ...secret import IGNORE_ZERO_UNIT_BASAL
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from .helpers import insulin_float_round, insulin_milliunits_to_real
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
BASAL_EVENTTYPE,
NightscoutEntry
)
from typing import Iterable, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
logger = logging.getLogger(__name__)
BasalEvent = Union[eventtypes.LidBasalRateChange, eventtypes.LidBasalDelivery]
class ProcessBasal:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.BASAL in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessBasal: querying for last uploaded entry")
last_upload = self.nightscout.last_uploaded_entry(BASAL_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout basal upload: %s" % last_upload_time)
with_duration = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping basal event not after last upload time: %s (time range: %s - %s)" % (event, time_start, time_end))
continue
with_duration.append([event.eventTimestamp, None, event])
if not with_duration:
logger.info("No basal events found to process")
return []
for i in range(len(with_duration)-1):
with_duration[i][1] = with_duration[i+1][0] - with_duration[i][0]
with_duration[-1][1] = time_end - with_duration[-1][0]
ns_entries = []
for item in with_duration:
ns = self.basal_to_nsentry(*item)
if ns:
ns_entries.append(ns)
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def basal_to_nsentry(self, start: arrow.Arrow, duration: datetime.timedelta, event: BasalEvent) -> Optional[dict]:
if type(event) == eventtypes.LidBasalRateChange:
value = insulin_float_round(event.commandedBasalRate)
if IGNORE_ZERO_UNIT_BASAL and value < 0.01:
logger.info("Ignoring basal entry with %.2f unit basal because IGNORE_ZERO_UNIT_BASAL=true: %s" % (value, event))
return None
return NightscoutEntry.basal(
value = value,
duration_mins = duration.total_seconds() / 60,
created_at = start.format(),
reason = ', '.join(bitmask_to_list(event.changeType)),
pump_event_id = "%s" % event.seqNum
)
if type(event) == eventtypes.LidBasalDelivery:
value = insulin_milliunits_to_real(event.commandedRate)
if IGNORE_ZERO_UNIT_BASAL and value < 0.01:
logger.info("Ignoring basal entry with %.2f unit basal because IGNORE_ZERO_UNIT_BASAL=true: %s" % (value, event))
return None
return NightscoutEntry.basal(
value = value,
duration_mins = duration.total_seconds() / 60,
created_at = start.format(),
reason = ', '.join(bitmask_to_list(event.commandedRateSource)),
pump_event_id = "%s" % event.seqNum
)
return None
@@ -0,0 +1,75 @@
import logging
import arrow
from typing import Iterable, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
BASALRESUME_EVENTTYPE,
NightscoutEntry
)
logger = logging.getLogger(__name__)
class ProcessBasalResume:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PUMP_EVENTS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessBasalResume: querying for last uploaded resume-suspension")
last_upload = self.nightscout.last_uploaded_entry(BASALRESUME_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout BasalResume upload: %s" % last_upload_time)
ns_entries = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping BasalResume event not after last upload time: %s (time range: %s - %s)" % (event, time_start, time_end))
continue
ns = self.resume_to_nsentry(event)
if ns:
ns_entries.append(ns)
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def resume_to_nsentry(self, event: eventtypes.LidPumpingResumed) -> Optional[dict]:
if type(event) == eventtypes.LidPumpingResumed:
return NightscoutEntry.basalresume(
created_at = event.eventTimestamp.format(),
pump_event_id = "%s" % event.seqNum
)
return None
@@ -0,0 +1,76 @@
import logging
import arrow
from typing import Iterable, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
BASALSUSPENSION_EVENTTYPE,
NightscoutEntry
)
logger = logging.getLogger(__name__)
class ProcessBasalSuspension:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PUMP_EVENTS in self.features or features.BASAL in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessBasalSuspension: querying for last uploaded suspension")
last_upload = self.nightscout.last_uploaded_entry(BASALSUSPENSION_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout basalsuspension upload: %s" % last_upload_time)
ns_entries = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping basalsuspension event not after last upload time: %s (time range: %s - %s)" % (event, time_start, time_end))
continue
ns = self.suspension_to_nsentry(event)
if ns:
ns_entries.append(ns)
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def suspension_to_nsentry(self, event: eventtypes.LidPumpingSuspended) -> Optional[dict]:
if type(event) == eventtypes.LidPumpingSuspended:
return NightscoutEntry.basalsuspension(
created_at = event.eventTimestamp.format(),
reason = ', '.join(bitmask_to_list(event.suspendReason)),
pump_event_id = "%s" % event.seqNum
)
return None
@@ -0,0 +1,133 @@
import logging
import arrow
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from .helpers import insulin_float_round
from ...parser.nightscout import (
BOLUS_EVENTTYPE,
NightscoutEntry
)
from typing import Iterable, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
logger = logging.getLogger(__name__)
class ProcessBolus:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.BOLUS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessBolus: querying for last uploaded entry")
last_upload = self.nightscout.last_uploaded_entry(BOLUS_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout bolus upload: %s" % last_upload_time)
# Correlate a bolus's request/completion messages by bolusid.
bolusEventsForId: dict = {}
for event in sorted(events, key=lambda x: x.eventTimestamp):
bolusEventsForId.setdefault(event.bolusId, {})[type(event)] = event
# Emit one Nightscout treatment per completion event, each at its own time:
# - LidBolusCompleted -> the standard / "now" bolus (carbs, bg, notes)
# - LidBolexCompleted -> the extended portion of a combo bolus (added
# separately, insulin only, so its later delivery is not dropped).
completions = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if type(event) not in (eventtypes.LidBolusCompleted, eventtypes.LidBolexCompleted):
continue
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping bolus completion not after last upload time: %s (time range: %s - %s)" % (event, time_start, time_end))
continue
completions.append(event)
completions.sort(key=lambda e: e.eventTimestamp)
ns_entries = []
for event in completions:
if type(event) == eventtypes.LidBolexCompleted:
ns_entries.append(self.bolex_to_nsentry(event))
continue
m = bolusEventsForId[event.bolusId]
ns_entries.append(self.bolus_to_nsentry(
event,
bolusRequested1 = m.get(eventtypes.LidBolusRequestedMsg1),
bolusRequested2 = m.get(eventtypes.LidBolusRequestedMsg2),
bolusRequested3 = m.get(eventtypes.LidBolusRequestedMsg3),
))
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def bolus_to_nsentry(self, bolusCompleted: eventtypes.LidBolusCompleted, bolusRequested1: Optional[eventtypes.LidBolusRequestedMsg1], bolusRequested2: Optional[eventtypes.LidBolusRequestedMsg2], bolusRequested3: Optional[eventtypes.LidBolusRequestedMsg3]) -> dict:
suffixes = []
if bolusRequested2 and bolusRequested2.userOverride == eventtypes.LidBolusRequestedMsg2.UseroverrideEnum.Yes:
suffixes.append('(Override)')
if bolusRequested2 and bolusRequested2.declinedCorrection == eventtypes.LidBolusRequestedMsg2.DeclinedcorrectionEnum.Yes:
suffixes.append('(Declined Correction)')
suffix = (' ' + (' '.join(suffixes))) if suffixes else ''
seq_nums = []
for e in [bolusCompleted, bolusRequested1, bolusRequested2, bolusRequested3]:
if e:
seq_nums.append(str(e.seqNum))
notes = ''
if bolusRequested2 and str(bolusRequested2.optionsRaw) in eventtypes.LidBolusRequestedMsg2.OptionsMap:
notes = eventtypes.LidBolusRequestedMsg2.OptionsMap['%d' % bolusRequested2.optionsRaw]
return NightscoutEntry.bolus(
bolus = insulin_float_round(bolusCompleted.insulinDelivered),
carbs = bolusRequested1.carbAmount if bolusRequested1 and bolusRequested1.carbAmount>0 else None,
created_at = bolusCompleted.eventTimestamp.format(),
notes = notes + suffix,
bg = bolusRequested1.bg if bolusRequested1 and bolusRequested1.bg > 0 else None,
pump_event_id = ",".join(seq_nums)
)
def bolex_to_nsentry(self, bolexCompleted: eventtypes.LidBolexCompleted) -> dict:
# The extended portion of a combo bolus, added as its own treatment at
# the time it finished delivering. Insulin only; carbs/bg belong to the
# initial LidBolusCompleted entry and must not be double-counted here.
return NightscoutEntry.bolus(
bolus = insulin_float_round(bolexCompleted.insulinDelivered),
carbs = None,
created_at = bolexCompleted.eventTimestamp.format(),
notes = "Extended Bolus",
bg = None,
pump_event_id = "%s" % bolexCompleted.seqNum
)
@@ -0,0 +1,111 @@
import logging
import arrow
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
SITECHANGE_EVENTTYPE,
NightscoutEntry
)
from typing import Iterable, List, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
logger = logging.getLogger(__name__)
class ProcessCartridge:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PUMP_EVENTS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessCartridge: querying for last uploaded entry")
last_upload = self.nightscout.last_uploaded_entry(SITECHANGE_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout sitechange upload: %s" % last_upload_time)
cartFilledEvents = []
cannulaFilledEvents = []
tubingFilledEvents = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping %s not after last upload time: %s (time range: %s - %s)" % (type(event), event, time_start, time_end))
continue
if type(event) == eventtypes.LidCartridgeFilled:
cartFilledEvents.append(event)
elif type(event) == eventtypes.LidCannulaFilled:
cannulaFilledEvents.append(event)
elif type(event) == eventtypes.LidTubingFilled:
tubingFilledEvents.append(event)
cartFilledEvents.sort(key=lambda e: e.eventTimestamp)
cannulaFilledEvents.sort(key=lambda e: e.eventTimestamp)
tubingFilledEvents.sort(key=lambda e: e.eventTimestamp)
ns_entries = []
for cartFilled in cartFilledEvents:
ns_entries.append(self.cart_to_nsentry(cartFilled))
for cannulaFilled in cannulaFilledEvents:
ns_entries.append(self.cannula_to_nsentry(cannulaFilled))
for tubingFilled in tubingFilledEvents:
ns_entries.append(self.tubing_to_nsentry(tubingFilled))
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def cart_to_nsentry(self, cartFilled: eventtypes.LidCartridgeFilled) -> dict:
# insulinVolume is populated on t:slim X2 / Mobi; v2Volume is a legacy fallback.
volume = cartFilled.insulinVolume or cartFilled.v2Volume
return NightscoutEntry.sitechange(
created_at = cartFilled.eventTimestamp.format(),
reason = "Cartridge Filled" + (" (%du filled)" % round(volume) if volume else ""),
pump_event_id = "%s" % cartFilled.seqNum
)
def cannula_to_nsentry(self, cannulaFilled: eventtypes.LidCannulaFilled) -> dict:
# primeSize is fractional (e.g. 0.3u); format with one decimal, not %d.
primed = cannulaFilled.primeSize if cannulaFilled.primeSize and cannulaFilled.primeSize > 0 else None
return NightscoutEntry.sitechange(
created_at = cannulaFilled.eventTimestamp.format(),
reason = "Cannula Filled" + (" (%.1fu primed)" % primed if primed else ""),
pump_event_id = "%s" % cannulaFilled.seqNum
)
def tubing_to_nsentry(self, tubingFilled: eventtypes.LidTubingFilled) -> dict:
# primeSize is -1 (sentinel, "not recorded") on real tubing fills; only show a real prime volume.
primed = tubingFilled.primeSize if tubingFilled.primeSize and tubingFilled.primeSize > 0 else None
return NightscoutEntry.sitechange(
created_at = tubingFilled.eventTimestamp.format(),
reason = "Tubing Filled" + (" (%du primed)" % round(primed) if primed else ""),
pump_event_id = "%s" % tubingFilled.seqNum
)
@@ -0,0 +1,108 @@
import logging
import arrow
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
CGM_ALERT_EVENTTYPE,
NightscoutEntry
)
from typing import Iterable, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
logger = logging.getLogger(__name__)
# The three CGM alert event types all expose dalertId / dalertIdRaw / seqNum.
CgmAlertEvent = Union[
eventtypes.LidCgmAlertActivated,
eventtypes.LidCgmAlertActivatedDex,
eventtypes.LidCgmAlertActivatedFsl2,
]
class ProcessCGMAlert:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.CGM_ALERTS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessCGMAlert: querying for last uploaded entry")
last_upload = self.nightscout.last_uploaded_entry(CGM_ALERT_EVENTTYPE, time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("Last Nightscout cgmalert upload: %s" % last_upload_time)
alertEvents = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("Skipping %s not after last upload time: %s (time range: %s - %s)" % (type(event), event, time_start, time_end))
continue
alertEvents.append(event)
alertEvents.sort(key=lambda e: e.eventTimestamp)
ns_entries = []
for event in alertEvents:
e = self.alert_to_nsentry(event)
if e:
ns_entries.append(e)
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def alert_to_nsentry(self, alert: CgmAlertEvent) -> Optional[dict]:
# FSL3 alert codes are defined in eventparser/static_dicts.py:CGM_ALERTS_DICT
# Alert code meanings are documented in comments there.
if not alert.dalertId:
logger.info("ProcessCGMAlert: Skipping alert with unknown dalertid %d: %s" % (alert.dalertIdRaw, alert))
return None
if type(alert) == eventtypes.LidCgmAlertActivated:
return NightscoutEntry.cgm_alert(
created_at = alert.eventTimestamp.format(),
reason = ("CGM Alert (%s)" % alert.dalertId.name) if alert.dalertId else "CGM Alert (Unknown)",
pump_event_id = "%s" % alert.seqNum
)
elif type(alert) == eventtypes.LidCgmAlertActivatedDex:
if alert.dalertId == eventtypes.LidCgmAlertActivatedDex.DalertidEnum.CgmOutOfRange:
logger.info("ProcessCGMAlert: Skipping alert with CgmOutOfRange dalertid %d: %s" % (alert.dalertIdRaw, alert))
return None
return NightscoutEntry.cgm_alert(
created_at = alert.eventTimestamp.format(),
reason = ("Dexcom CGM Alert (%s)" % alert.dalertId.name) if alert.dalertId else "Dexcom CGM Alert (Unknown)",
pump_event_id = "%s" % alert.seqNum
)
elif type(alert) == eventtypes.LidCgmAlertActivatedFsl2:
return NightscoutEntry.cgm_alert(
created_at = alert.eventTimestamp.format(),
reason = ("Libre CGM Alert (%s)" % alert.dalertId.name) if alert.dalertId else "Libre CGM Alert (Unknown)",
pump_event_id = "%s" % alert.seqNum
)
return None
@@ -0,0 +1,132 @@
import logging
import arrow
from ...features import DEFAULT_FEATURES
from ... import features
from ... import secret
from ...eventparser.raw_event import TANDEM_EPOCH
from ...eventparser import events as eventtypes
from ...parser.nightscout import NightscoutEntry
from typing import Iterable, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
# The four CGM-reading event types share the glucoseValueStatus /
# currentGlucoseDisplayValue fields determine_glucose_value() reads.
CgmReadingEvent = Union[
eventtypes.LidCgmDataG7,
eventtypes.LidCgmDataGxb,
eventtypes.LidCgmDataFsl2,
eventtypes.LidCgmDataFsl3,
]
logger = logging.getLogger(__name__)
# Mirrors the Tandem Source frontend (CgmBuilder.determineGlucoseValue): out-of-range
# and special readings are reported as sentinel values rather than the raw display value.
GLUCOSE_LIMIT_LOW = 40
GLUCOSE_LIMIT_HIGH = 400
GLUCOSE_VALUE_LOW = 39
GLUCOSE_VALUE_HIGH = 401
def _resolve_glucose_value(display_value, status, *, precise, high, low):
if status == high:
return GLUCOSE_VALUE_HIGH
if status == low:
return GLUCOSE_VALUE_LOW
if status == precise:
if display_value < GLUCOSE_LIMIT_LOW:
return GLUCOSE_VALUE_LOW
if display_value > GLUCOSE_LIMIT_HIGH:
return GLUCOSE_VALUE_HIGH
return display_value
# Each sensor is handled separately: the glucoseValueStatus enums are NOT assumed
# to be consistent across sensor types (e.g. G6 names its members differently), so
# every branch resolves against that sensor's own enum members.
def determine_glucose_value(event: CgmReadingEvent) -> int:
display_value = event.currentGlucoseDisplayValue
status = event.glucoseValueStatus
if isinstance(event, eventtypes.LidCgmDataG7):
g7 = eventtypes.LidCgmDataG7.GlucosevaluestatusEnum
return _resolve_glucose_value(display_value, status,
precise=g7.PreciseValue, high=g7.SpecialHigh, low=g7.SpecialLow)
if isinstance(event, eventtypes.LidCgmDataGxb):
gxb = eventtypes.LidCgmDataGxb.GlucosevaluestatusEnum
return _resolve_glucose_value(display_value, status,
precise=gxb.CurrentglucosedisplayvalueContainsTheGlucoseReading,
high=gxb.TheGlucoseReadingIsHigh, low=gxb.TheGlucoseReadingIsLow)
if isinstance(event, eventtypes.LidCgmDataFsl3):
fsl3 = eventtypes.LidCgmDataFsl3.GlucosevaluestatusEnum
return _resolve_glucose_value(display_value, status,
precise=fsl3.PreciseValue, high=fsl3.SpecialHigh, low=fsl3.SpecialLow)
if isinstance(event, eventtypes.LidCgmDataFsl2):
fsl2 = eventtypes.LidCgmDataFsl2.GlucosevaluestatusEnum
return _resolve_glucose_value(display_value, status,
precise=fsl2.PreciseValue, high=fsl2.SpecialHigh, low=fsl2.SpecialLow)
return display_value
class ProcessCGMReading:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES, timezone: Optional[str] = None) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
self.timezone = timezone or secret.TIMEZONE_NAME
def enabled(self) -> bool:
return features.CGM in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessCGMReading: querying for last uploaded entry")
last_upload = self.nightscout.last_uploaded_bg_entry(time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload and "dateString" in last_upload:
last_upload_time = arrow.get(last_upload["dateString"])
elif last_upload and "date" in last_upload:
last_upload_time = arrow.get(last_upload["date"])
logger.info("ProcessCGMReading: Last Nightscout bg upload: %s" % last_upload_time)
readings = []
for event in sorted(events, key=lambda x: self.timestamp_for(x)):
if last_upload_time and self.timestamp_for(event) <= last_upload_time:
if self.pretend:
logger.info("ProcessCGMReading: Skipping %s not after last upload time: %s (time range: %s - %s)" % (type(event), event, time_start, time_end))
continue
readings.append(event)
ns_entries = []
for event in readings:
ns_entries.append(self.to_nsentry(event))
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry, entity='entries')
count += 1
return count
def timestamp_for(self, event: CgmReadingEvent) -> arrow.Arrow:
# For backfills the time the event was added to the pump's event store
# might not be the time it actually occurred, so we use the egvTimestamp
return arrow.get(TANDEM_EPOCH + event.egvTimeStamp, tzinfo='UTC').replace(tzinfo=self.timezone)
def to_nsentry(self, event: CgmReadingEvent) -> dict:
return NightscoutEntry.entry(
sgv = determine_glucose_value(event),
created_at = self.timestamp_for(event).format(),
pump_event_id = "%s" % event.seqNum,
)
@@ -0,0 +1,120 @@
import logging
import arrow
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...nightscout import format_datetime
from ...parser.nightscout import (
CGM_START_EVENTTYPE,
CGM_JOIN_EVENTTYPE,
CGM_STOP_EVENTTYPE,
NightscoutEntry
)
from typing import Iterable, List, Optional, Union, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
logger = logging.getLogger(__name__)
# The CGM session start/join/stop event types (see EventClass._CGM_START /
# _CGM_JOIN / _CGM_STOP); all expose seqNum and eventTimestamp.
CgmSessionEvent = Union[
eventtypes.LidCgmStartSessionGx,
eventtypes.LidCgmStartSessionFsl2,
eventtypes.LidCgmJoinSessionGx,
eventtypes.LidCgmJoinSessionG7,
eventtypes.LidCgmJoinSessionFsl2,
eventtypes.LidCgmJoinSessionFsl3,
eventtypes.LidCgmStopSessionGx,
eventtypes.LidCgmStopSessionG7,
eventtypes.LidCgmStopSessionFsl2,
eventtypes.LidCgmStopSessionFsl3,
]
class ProcessCGMStartJoinStop:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PUMP_EVENTS in self.features or features.CGM_ALERTS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
last_upload = None
last_upload_time = None
for eventtype in [CGM_START_EVENTTYPE, CGM_JOIN_EVENTTYPE, CGM_STOP_EVENTTYPE]:
logger.debug("ProcessCGMStartJoinStop: querying for last uploaded entry for %s" % eventtype)
_last_upload = self.nightscout.last_uploaded_entry(eventtype, time_start=time_start, time_end=time_end)
_last_upload_time = None
if _last_upload:
_last_upload_time = arrow.get(_last_upload["created_at"])
if not last_upload_time:
last_upload = _last_upload
last_upload_time = _last_upload_time
elif _last_upload_time > last_upload_time:
last_upload = _last_upload
last_upload_time = _last_upload_time
logger.info("ProcessCGMStartJoinStop: Last Nightscout %s upload: %s" % (eventtype, _last_upload_time))
logger.info("ProcessCGMStartJoinStop: Overall last Nightscout upload: %s %s" % (last_upload_time, last_upload))
allEvents = []
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("ProcessCGMStartJoinStop: Skipping %s not after last upload time: %s (time range: %s - %s)" % (type(event), event, time_start, time_end))
continue
allEvents.append(event)
allEvents.sort(key=lambda e: e.eventTimestamp)
ns_entries = []
for event in allEvents:
ns = self.to_nsentry(event)
if ns:
ns_entries.append(ns)
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def to_nsentry(self, event: CgmSessionEvent) -> Optional[dict]:
if type(event) in EventClass._CGM_START:
return NightscoutEntry.cgm_start(
created_at = format_datetime(event.eventTimestamp),
reason = "CGM Session Started",
pump_event_id = "%s" % event.seqNum
)
elif type(event) in EventClass._CGM_JOIN:
return NightscoutEntry.cgm_join(
created_at = format_datetime(event.eventTimestamp),
reason = "CGM Session Joined",
pump_event_id = "%s" % event.seqNum
)
elif type(event) in EventClass._CGM_STOP:
return NightscoutEntry.cgm_stop(
created_at = format_datetime(event.eventTimestamp),
reason = "CGM Session Stopped",
pump_event_id = "%s" % event.seqNum
)
return None
@@ -0,0 +1,97 @@
import logging
import arrow
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
EXERCISE_EVENTTYPE,
SLEEP_EVENTTYPE,
NightscoutEntry
)
from typing import Iterable, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
logger = logging.getLogger(__name__)
class ProcessDeviceStatus:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.DEVICE_STATUS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessDeviceStatus: querying for last uploaded devicestatus")
last_upload = self.nightscout.last_uploaded_devicestatus(time_start=time_start, time_end=time_end)
last_upload_time = None
if last_upload:
last_upload_time = arrow.get(last_upload["created_at"])
logger.info("ProcessDeviceStatus: Last Nightscout devicestatus upload: %s" % last_upload_time)
last_daily_basal_event = None
for event in sorted(events, key=lambda x: x.raw.timestamp):
if last_upload_time and event.raw.timestamp <= last_upload_time:
if self.pretend:
logger.info("ProcessDeviceStatus: Skipping %s not after last upload time: %s (time range: %s - %s)" % (type(event), event, time_start, time_end))
continue
if isinstance(event, eventtypes.LidDailyBasal):
last_daily_basal_event = event
if not last_daily_basal_event:
logger.info("ProcessDeviceStatus: No last_daily_basal_event found for add (time range: %s - %s)" % (time_start, time_end))
return []
logger.info("ProcessDeviceStatus: last_daily_basal_event=%s" % (last_daily_basal_event))
entry = self.daily_basal_to_nsentry(last_daily_basal_event)
if entry is None:
return []
return [entry]
def daily_basal_to_nsentry(self, event: eventtypes.LidDailyBasal) -> Optional[dict]:
# NOTE: the pump-logs endpoint does not emit event 81 (LID_DAILY_BASAL)
# for either t:slim X2 or Mobi (verified against live accounts), and no
# other returned event carries battery data. DEVICE_STATUS therefore
# yields nothing on the new API; this path stays for the binary decoder
# and in case the endpoint starts returning event 81.
#
# batteryChargePercent is the pump's own state-of-charge byte, already
# scaled 0-100; if the event arrived without it (an event shape we
# can't yet parse), skip it rather than emit a bogus device status.
if event.batteryChargePercent is None:
logger.warning("ProcessDeviceStatus: skipping daily basal event missing battery data: %s" % event)
return None
return NightscoutEntry.devicestatus(
created_at=event.eventTimestamp.format(),
batteryVoltage=(float(event.batteryLipoMilliVolts or 0)/1000),
batteryPercent=int(event.batteryChargePercent),
pump_event_id = "%s" % event.seqNum
)
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload devicestatus to Nightscout: %s" % entry)
else:
logger.info("Uploading devicestatus to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry, entity='devicestatus')
count += 1
return count
@@ -0,0 +1,257 @@
import logging
import arrow
from typing import Iterable, List, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
from ...features import DEFAULT_FEATURES
from ... import features
from ...eventparser.generic import Events, decode_raw_events, EVENT_LEN
from ...eventparser.utils import bitmask_to_list
from ...eventparser import events as eventtypes
from ...domain.tandemsource.event_class import EventClass
from ...parser.nightscout import (
EXERCISE_EVENTTYPE,
SLEEP_EVENTTYPE,
NightscoutEntry
)
NOT_ENDED = "Not Ended"
logger = logging.getLogger(__name__)
class ProcessUserMode:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PUMP_EVENTS in self.features
def process(self, events: Iterable, time_start: arrow.Arrow, time_end: arrow.Arrow) -> List[dict]:
logger.debug("ProcessUserMode: querying for last uploaded exercise entry")
exercise_last_upload = self.nightscout.last_uploaded_entry(EXERCISE_EVENTTYPE, time_start=time_start, time_end=time_end)
exercise_last_upload_time = None
if exercise_last_upload:
exercise_last_upload_time = arrow.get(exercise_last_upload["created_at"])
logger.info("ProcessUserMode: Last Nightscout exercise upload: %s" % exercise_last_upload_time)
exercise_not_ended = False
if exercise_last_upload and NOT_ENDED in exercise_last_upload.get("reason", ""):
exercise_not_ended = True
logger.info("ProcessUserMode: Last exercise not ended: %s" % exercise_last_upload)
logger.debug("ProcessUserMode: querying for last uploaded sleep entry")
sleep_last_upload = self.nightscout.last_uploaded_entry(SLEEP_EVENTTYPE, time_start=time_start, time_end=time_end)
sleep_last_upload_time = None
if sleep_last_upload:
sleep_last_upload_time = arrow.get(sleep_last_upload["created_at"])
logger.info("ProcessUserMode: Last Nightscout sleep upload: %s" % sleep_last_upload_time)
sleep_not_ended = False
if sleep_last_upload and NOT_ENDED in sleep_last_upload.get("reason", ""):
sleep_not_ended = True
logger.info("ProcessUserMode: Last sleep not ended: %s" % sleep_last_upload)
last_upload_time = None
if exercise_last_upload_time and sleep_last_upload_time:
last_upload_time = max(exercise_last_upload_time, sleep_last_upload_time)
elif exercise_last_upload_time:
last_upload_time = exercise_last_upload_time
elif sleep_last_upload_time:
last_upload_time = sleep_last_upload_time
logger.info("ProcessUserMode: Last Nightscout usermode upload: %s" % last_upload_time)
ns_entries = []
processed_sleep = []
processed_exercise = []
start_sleep = None
start_exercise = None
for event in sorted(events, key=lambda x: x.eventTimestamp):
if last_upload_time and arrow.get(event.eventTimestamp) <= last_upload_time:
if self.pretend:
logger.info("ProcessUserMode: Skipping usermode event not after last upload time: %s (time range: %s - %s)" % (event, time_start, time_end))
continue
if self.is_start_sleep(event):
start_sleep = event
elif self.is_stop_sleep(event):
if start_sleep:
processed_sleep.append((start_sleep, event))
start_sleep = None
else:
if sleep_not_ended and sleep_last_upload:
logger.info("ProcessUserMode: Found StopSleep without StartSleep, with incomplete sleep event in nightscout: %s NS: %s" % (event, sleep_last_upload))
ns_entries.append(self.process_unended_sleep_stop(event, sleep_last_upload))
else:
logger.warning("ProcessUserMode: Found StopSleep without StartSleep, and no active sleep event in nightscout: %s" % event)
elif self.is_start_exercise(event):
start_exercise = event
elif self.is_stop_exercise(event):
if start_exercise:
processed_exercise.append((start_exercise, event))
start_exercise = None
else:
if exercise_not_ended and exercise_last_upload:
logger.info("ProcessUserMode: Found StopExercise without StartExercise, with incomplete exercise event in nightscout: %s NS: %s" % (event, exercise_last_upload))
ns_entries.append(self.process_unended_exercise_stop(event, exercise_last_upload))
else:
logger.warning("ProcessUserMode: Found StopExercise without StartExercise, and no active exercise event in nightscout: %s" % event)
else:
logger.warning("ProcessUserMode: not sure how to process event: %s" % event)
if start_sleep:
processed_sleep.append((start_sleep, None))
logger.info("ProcessUserMode: sleep is active")
if start_exercise:
processed_exercise.append((start_exercise, None))
logger.info("ProcessUserMode: exercise is active")
for items in processed_sleep:
ns = self.sleep_to_nsentry(start=items[0], stop=items[1], time_end=time_end)
if ns:
ns_entries.append(ns)
for items in processed_exercise:
ns = self.exercise_to_nsentry(start=items[0], stop=items[1], time_end=time_end)
if ns:
ns_entries.append(ns)
return ns_entries
def write(self, ns_entries: List[dict]) -> int:
count = 0
for entry in ns_entries:
if self.pretend:
logger.info("Would upload to Nightscout: %s" % entry)
else:
logger.info("Uploading to Nightscout: %s" % entry)
self.nightscout.upload_entry(entry)
count += 1
return count
def is_start_sleep(self, event: eventtypes.LidAaUserModeChange) -> bool:
return event.requestedAction == eventtypes.LidAaUserModeChange.RequestedactionEnum.StartSleep
def is_stop_sleep(self, event: eventtypes.LidAaUserModeChange) -> bool:
return event.requestedAction == eventtypes.LidAaUserModeChange.RequestedactionEnum.StopSleep or \
event.requestedAction == eventtypes.LidAaUserModeChange.RequestedactionEnum.StopAll
def is_start_exercise(self, event: eventtypes.LidAaUserModeChange) -> bool:
return event.requestedAction == eventtypes.LidAaUserModeChange.RequestedactionEnum.StartExercise
def is_stop_exercise(self, event: eventtypes.LidAaUserModeChange) -> bool:
return event.requestedAction == eventtypes.LidAaUserModeChange.RequestedactionEnum.StopExercise or \
event.requestedAction == eventtypes.LidAaUserModeChange.RequestedactionEnum.StopAll
def sleep_to_nsentry(self, start: eventtypes.LidAaUserModeChange, stop: Optional[eventtypes.LidAaUserModeChange] = None, time_end: Optional[arrow.Arrow] = None) -> Optional[dict]:
if start and stop:
reason = None
if start.sleepStartedByGui == eventtypes.LidAaUserModeChange.SleepstartedbyguiEnum.TrueVal:
reason = "Sleep (Manual)"
elif start.activeSleepSchedule:
reason = "Sleep (Scheduled)"
duration_mins = (stop.eventTimestamp - start.eventTimestamp).total_seconds() / 60
return NightscoutEntry.activity(
created_at=start.eventTimestamp.format(),
reason=reason,
duration=duration_mins,
event_type=SLEEP_EVENTTYPE,
pump_event_id = "%s,%s" % (start.seqNum, stop.seqNum)
)
elif start:
reason = None
if start.sleepStartedByGui == eventtypes.LidAaUserModeChange.SleepstartedbyguiEnum.TrueVal:
reason = "Sleep (Manual)"
elif start.activeSleepScheduleRaw:
reason = "Sleep (Scheduled)"
duration_mins = (time_end - start.eventTimestamp).total_seconds() / 60
return NightscoutEntry.activity(
created_at=start.eventTimestamp.format(),
reason=reason + " - " + NOT_ENDED if reason else NOT_ENDED,
duration=duration_mins,
event_type=SLEEP_EVENTTYPE,
pump_event_id = "%s" % start.seqNum
)
return None
def exercise_to_nsentry(self, start: eventtypes.LidAaUserModeChange, stop: Optional[eventtypes.LidAaUserModeChange] = None, time_end: Optional[arrow.Arrow] = None) -> Optional[dict]:
if start and stop:
reason = "Exercise"
if start.exerciseChoice == eventtypes.LidAaUserModeChange.ExercisechoiceEnum.Timed:
reason = "Exercise (Timed)"
if stop.exerciseStoppedByTimer == eventtypes.LidAaUserModeChange.ExercisestoppedbytimerEnum.TrueVal:
reason += " (Stopped by timer)"
duration_mins = (stop.eventTimestamp - start.eventTimestamp).total_seconds() / 60
return NightscoutEntry.activity(
created_at=start.eventTimestamp.format(),
reason=reason,
duration=duration_mins,
event_type=EXERCISE_EVENTTYPE,
pump_event_id = "%s,%s" % (start.seqNum, stop.seqNum)
)
elif start:
reason = "Exercise"
if start.exerciseChoice == eventtypes.LidAaUserModeChange.ExercisechoiceEnum.Timed:
reason = "Exercise (Timed)"
duration_mins = (time_end - start.eventTimestamp).total_seconds() / 60
return NightscoutEntry.activity(
created_at=start.eventTimestamp.format(),
reason=reason + " - " + NOT_ENDED,
duration=duration_mins,
event_type=EXERCISE_EVENTTYPE,
pump_event_id = "%s" % start.seqNum
)
return None
def process_unended_sleep_stop(self, event: eventtypes.LidAaUserModeChange, sleep_last_upload: dict) -> dict:
logger.info("ProcessUserMode: Deleting old sleep event treatment before pushing update (delete treatments/%s)" % sleep_last_upload["_id"])
if self.pretend:
logger.info("ProcessUserMode: Skipping delete in pretend mode")
else:
self.nightscout.delete_entry('treatments/%s' % sleep_last_upload["_id"])
duration_mins = (event.eventTimestamp - arrow.get(sleep_last_upload["created_at"])).total_seconds() / 60
return NightscoutEntry.activity(
created_at=sleep_last_upload["created_at"],
reason=sleep_last_upload["reason"].replace(" - %s" % NOT_ENDED, ""),
duration=duration_mins,
event_type=SLEEP_EVENTTYPE,
pump_event_id="%s,%s" % (sleep_last_upload.get("pump_event_id",""), event.seqNum)
)
def process_unended_exercise_stop(self, event: eventtypes.LidAaUserModeChange, exercise_last_upload: dict) -> dict:
logger.info("ProcessUserMode: Deleting old exercise event treatment before pushing update (delete treatments/%s)" % exercise_last_upload["_id"])
if self.pretend:
logger.info("ProcessUserMode: Skipping delete in pretend mode")
else:
self.nightscout.delete_entry('treatments/%s' % exercise_last_upload["_id"])
reason = exercise_last_upload["reason"].replace(" - %s" % NOT_ENDED, "")
if event.exerciseStoppedByTimer == eventtypes.LidAaUserModeChange.ExercisestoppedbytimerEnum.TrueVal:
reason += " (Stopped by timer)"
duration_mins = (event.eventTimestamp - arrow.get(exercise_last_upload["created_at"])).total_seconds() / 60
return NightscoutEntry.activity(
created_at=exercise_last_upload["created_at"],
reason=reason,
duration=duration_mins,
event_type=EXERCISE_EVENTTYPE,
pump_event_id="%s,%s" % (exercise_last_upload.get("pump_event_id",""), event.seqNum)
)
@@ -0,0 +1,217 @@
import logging
import arrow
import copy
import json
from typing import Any, Callable, List, Tuple, TYPE_CHECKING
if TYPE_CHECKING:
from ...api import TConnectApi
from ...nightscout import NightscoutApi
from ...features import DEFAULT_FEATURES
from ... import features
from ...domain.tandemsource.pump_settings import PumpSettings
from ...parser.nightscout import (
NightscoutEntry, ENTERED_BY
)
from ...secret import NIGHTSCOUT_PROFILE_UPLOAD_MODE
logger = logging.getLogger(__name__)
def _get_default_upload_mode() -> str:
return NIGHTSCOUT_PROFILE_UPLOAD_MODE
class UpdateProfiles:
def __init__(self, tconnect: "TConnectApi", nightscout: "NightscoutApi", tconnect_device_id: str, pretend: bool, features: List[str] = DEFAULT_FEATURES) -> None:
self.tconnect = tconnect
self.nightscout = nightscout
self.tconnect_device_id = tconnect_device_id
self.pretend = pretend
self.features = features
def enabled(self) -> bool:
return features.PROFILES in self.features
def update(self, pretend: bool) -> bool:
upload_mode = _get_default_upload_mode()
logger.debug("UpdateProfiles: getting Tandem Source profile data")
all_metadata = self.tconnect.tandemsource.get_pumper().get('pumps', [])
pump_meta = None
for m in all_metadata:
if m['assignmentId'] == self.tconnect_device_id:
pump_meta = m
if not pump_meta:
return False
s = pump_meta.get("settings")
raw_settings = s["details"] if s else None
if not raw_settings:
return False
pump_settings = PumpSettings.from_dict(raw_settings)
logger.info("Current pump settings: %s" % pump_settings)
ns_profile_obj = self.nightscout.current_profile()
logger.debug("Current Nightscout profile: %s" % ns_profile_obj)
if ns_profile_obj is None:
ns_profile_obj = {}
logger.info("Current Nightscout profile was authored by: %s" % (ns_profile_obj.get('enteredBy')))
diff, ns_profile_new = self.compare_profiles(pump_settings, ns_profile_obj)
if not diff:
logger.info("Pump and Nightscout profiles up to date")
return False
if upload_mode == 'add':
profile_to_upload = self.setup_new_profile(ns_profile_new)
logger.info("Adding new Nightscout profiles object: %s", profile_to_upload)
if not pretend:
self.nightscout.upload_entry(profile_to_upload, entity='profile')
return True
elif upload_mode == 'replace':
logger.info("Replacing new Nightscout profiles object: %s", ns_profile_new)
if not pretend:
self.nightscout.put_entry(ns_profile_new, entity='profile')
return True
else:
raise RuntimeError('invalid upload_mode: %s' % upload_mode)
"""
Compare pump device and Nightscout profiles, and return a final dictionary of
Nightscout profile objects, with the pump profile settings overriding what is
currently in Nightscout.
ns_profile_obj is the output from NightscoutApi.current_profile() and should be the most
recent profile object in mongo.
Returns the new Nightscout profile and whether it was changed.
"""
def compare_profiles(self, pump_settings: PumpSettings, ns_profile_obj: dict) -> Tuple[bool, dict]:
device = {profile.name: profile for profile in pump_settings.profiles.profile}
activeIdp = pump_settings.profiles.activeIdp
ns = ns_profile_obj.get('store', {})
logger.debug("compare_profiles profile names: device: %s ns: %s", device.keys(), ns.keys())
new_ns_profile = copy.deepcopy(ns_profile_obj)
if not 'store' in new_ns_profile:
new_ns_profile['store'] = {}
updated_ns_profile = False
missing_profiles_in_ns = set(device.keys()) - set(ns.keys())
for profile_name in missing_profiles_in_ns:
logger.info("Missing %s profile in Nightscout: %s", profile_name, device.get(profile_name))
pump_configured_profile = device[profile_name]
ns_translated_profile = NightscoutEntry.tandemsource_profile_store(pump_configured_profile, pump_settings)
logger.info("Will add %s profile to Nightscout: %s", profile_name, ns_translated_profile)
new_ns_profile['store'][profile_name] = ns_translated_profile
updated_ns_profile = True
existent_profiles_in_ns = set(device.keys()) & set(ns.keys())
for profile_name in existent_profiles_in_ns:
#logger.debug("Checking for differences for %s profile between pump and nightscout", profile_name)
pump_configured_profile = device[profile_name]
ns_translated_profile = NightscoutEntry.tandemsource_profile_store(pump_configured_profile, pump_settings)
ns_configured_profile = ns[profile_name]
#logger.debug("Comparing %s profile from pump: %s to nightscout: %s", profile_name, ns_translated_profile, ns_configured_profile)
if self.nightscout_profiles_identical(ns_configured_profile, ns_translated_profile):
logger.info("Profile %s identical between pump and nightscout", profile_name)
continue
logger.info("Profile %s needs update in nightscout: %s", profile_name, ns_translated_profile)
new_ns_profile['store'][profile_name] = ns_translated_profile
updated_ns_profile = True
current_pump_profile = None
for profile in pump_settings.profiles.profile:
if profile.idp == activeIdp:
current_pump_profile = profile.name
if not current_pump_profile:
logger.error('No current pump profile, so skipping profile update')
return False, ns_profile_obj
current_ns_profile = ns_profile_obj.get('defaultProfile')
if current_pump_profile != current_ns_profile:
logger.info("Current profile changed: pump: %s nightscout: %s", current_pump_profile, current_ns_profile)
new_ns_profile['defaultProfile'] = current_pump_profile
updated_ns_profile = True
if not updated_ns_profile:
logger.info("No Nightscout profile changes")
return False, ns_profile_obj
logger.info("New Nightscout profile object: %s", new_ns_profile)
new_ns_profile['enteredBy'] = ENTERED_BY
return True, new_ns_profile
def nightscout_profiles_identical(self, configured: dict, translated: dict) -> bool:
if configured == translated:
logger.debug("direct dicts equal")
return True
if json.dumps(configured, sort_keys=True, indent=None) == json.dumps(translated, sort_keys=True, indent=None):
logger.debug("initial JSON dump identical")
return True
# convert all JSON values into strings
def map_nested_dicts_modify(ob: dict, func: Callable) -> None:
for k, v in ob.items():
if isinstance(v, dict):
map_nested_dicts_modify(v, func)
elif isinstance(v, list):
map_nested_lists_modify(v, func)
else:
ob[k] = func(v)
def map_nested_lists_modify(ob: list, func: Callable) -> None:
for i in range(len(ob)):
v = ob[i]
if isinstance(v, dict):
map_nested_dicts_modify(v, func)
elif isinstance(v, list):
map_nested_lists_modify(v, func)
else:
ob[i] = func(v)
def to_numeric(x: Any) -> Any:
if type(x) in [int, float]:
return '%f' % x
try:
return '%f' % float(x)
except (ValueError, TypeError):
return x
convert_func = lambda x: to_numeric(x)
configured_str = json.loads(json.dumps(configured))
map_nested_dicts_modify(configured_str, convert_func)
translated_str = json.loads(json.dumps(translated))
map_nested_dicts_modify(translated_str, convert_func)
if json.dumps(configured_str, sort_keys=True, indent=None) == json.dumps(translated_str, sort_keys=True, indent=None):
logger.debug("map_nested_dicts JSON dump identical")
return True
logger.debug("profiles not identical")
return False
def setup_new_profile(self, ns_profile: dict) -> dict:
if '_id' in ns_profile:
del ns_profile['_id']
now = arrow.now().isoformat()
ns_profile['startDate'] = now
ns_profile['created_at'] = now
return ns_profile
+19
View File
@@ -1,5 +1,8 @@
import arrow
from . import cli
from . import constants
def timeago(timestamp):
seconds = (arrow.get() - arrow.get(timestamp)).total_seconds()
fmt = '%s ago' if seconds >= 0 else 'in %s'
@@ -15,3 +18,19 @@ def timeago(timestamp):
ret += '%d minutes' % (seconds//60)
return fmt % ret
# String methods only available in python 3.9+
def removesuffix(input_string, suffix):
if suffix and input_string.endswith(suffix):
return input_string[:-len(suffix)]
return input_string
def removeprefix(input_string, prefix):
if prefix and input_string.startswith(prefix):
return input_string[len(prefix):]
return input_string
def cap_length(text, maxlen):
if not text or len(text) <= maxlen:
return text
return '%s[...]%s' % (text[:maxlen//2], text[maxlen//-2:])
+20
View File
@@ -0,0 +1,20 @@
import logging
"""
Enables logging at the specified level for all loggers
inside the tconnectsync package, and sets up a basicConfig
to print those log messages to stderr.
"""
def enable_logging(level=logging.DEBUG):
logging.basicConfig()
for logger in logging.root.manager.loggerDict:
if logger.startswith('tconnectsync'):
logging.getLogger(logger).setLevel(level)
"""
Returns a TConnectApi object with default secret parameters.
"""
def get_api():
from ..api import TConnectApi
from ..secret import TCONNECT_EMAIL, TCONNECT_PASSWORD, TCONNECT_REGION
return TConnectApi(TCONNECT_EMAIL, TCONNECT_PASSWORD, TCONNECT_REGION)
+4
View File
@@ -0,0 +1,4 @@
# http://www.soc-bdr.org/rds/authors/unit_tables_conversions_and_genetic_dictionaries/conversion_glucose_mg_dl_to_mmol_l/index_en.html
MMOLL_TO_MGDL = 18.0182
MGDL_TO_MMOLL = 0.0555
+6 -42
View File
@@ -1,47 +1,11 @@
import tconnectsync.api
class ControlIQApi(tconnectsync.api.controliq.ControlIQApi):
def __init__(self):
self.BASE_URL = 'invalid://'
self.LOGIN_URL = 'invalid://'
def login(self, email, password):
raise NotImplementedError
def needs_relogin(self):
return False
def _get(self, endpoint, query):
raise NotImplementedError
class WS2Api(tconnectsync.api.ws2.WS2Api):
def __init__(self):
self.BASE_URL = 'invalid://'
self.SLEEP_SECONDS_INCREMENT = 0.01
def get(self, endpoint, query):
raise NotImplementedError
def get_jsonp(self, endpoint):
raise NotImplementedError
class AndroidApi(tconnectsync.api.android.AndroidApi):
def __init__(self):
self.BASE_URL = 'invalid://'
def login(self, email, password):
raise NotImplementedError
def needs_relogin(self):
return False
def _get(self, endpoint, query={}, **kwargs):
raise NotImplementedError
class TConnectApi(tconnectsync.api.TConnectApi):
def __init__(self):
pass
def __init__(self, email=None, password=None):
if email is not None and password is not None:
self.with_credentials = True
else:
self.with_credentials = False
_ciq = ControlIQApi()
_ws2 = WS2Api()
_android = AndroidApi()
_tandemsource = None
-90
View File
@@ -1,90 +0,0 @@
#!/usr/bin/env python3
import unittest
import itertools
import datetime
from .fake import AndroidApi
from tconnectsync.api.common import ApiException
class TestAndroidApi(unittest.TestCase):
def fake_get_with_http_code(self, http_code, expected_endpoint, num_times):
tries = 0
def fake_get(endpoint, query):
nonlocal http_code, expected_endpoint, num_times, tries
if endpoint.endswith(expected_endpoint):
if tries < num_times:
tries += 1
raise ApiException(http_code, "fake HTTP %d" % http_code)
return {"faked_json": True}
raise NotImplementedError
return fake_get
def test_last_event_uploaded_works_after_single_http_500(self):
android = AndroidApi()
android._get = self.fake_get_with_http_code(500, "cloud/upload/getlasteventuploaded?sn=1111111", 1)
self.assertEqual(
android.last_event_uploaded(1111111),
{
"faked_json": True
})
def test_last_event_uploaded_fails_after_two_http_500s(self):
android = AndroidApi()
android._get = self.fake_get_with_http_code(500, "cloud/upload/getlasteventuploaded?sn=1111111", 2)
self.assertRaises(ApiException, android.last_event_uploaded, 1111111)
def test_last_event_uploaded_triggers_relogin_after_single_http_401(self):
android = AndroidApi()
android._email = 'email'
android._password = 'password'
hit_login = []
def stub_login(email, password):
nonlocal hit_login
hit_login.append((email, password))
android.login = stub_login
android._get = self.fake_get_with_http_code(401, "cloud/upload/getlasteventuploaded?sn=1111111", 1)
self.assertEqual(
android.last_event_uploaded(1111111),
{
"faked_json": True
})
self.assertListEqual(hit_login, [
('email', 'password')
])
def test_last_event_uploaded_fails_after_two_http_401s(self):
android = AndroidApi()
android._email = 'email'
android._password = 'password'
hit_login = []
def stub_login(email, password):
nonlocal hit_login
hit_login.append((email, password))
android.login = stub_login
android._get = self.fake_get_with_http_code(401, "cloud/upload/getlasteventuploaded?sn=1111111", 2)
self.assertRaises(ApiException, android.last_event_uploaded, 1111111)
self.assertListEqual(hit_login, [
('email', 'password')
])
if __name__ == '__main__':
unittest.main()
+44
View File
@@ -0,0 +1,44 @@
import unittest
from unittest.mock import patch
from tconnectsync.api.common import base_session
class TestRequestsProxy(unittest.TestCase):
def test_proxy_used_in_base_session(self):
with patch("tconnectsync.api.common.secret") as mock_secret, \
patch("requests.Session.request") as mock_request:
s = base_session()
s.request('sentinel')
mock_request.assert_called_once_with('sentinel', proxies={
'http': mock_secret.REQUESTS_PROXY,
'https': mock_secret.REQUESTS_PROXY
})
def test_proxy_used_in_base_session_with_two_args(self):
with patch("tconnectsync.api.common.secret") as mock_secret, \
patch("requests.Session.request") as mock_request:
s = base_session()
s.request('GET', 'sentinel')
mock_request.assert_called_once_with('GET', 'sentinel', proxies={
'http': mock_secret.REQUESTS_PROXY,
'https': mock_secret.REQUESTS_PROXY
})
def test_proxy_used_in_base_session_with_kwargs(self):
with patch("tconnectsync.api.common.secret") as mock_secret, \
patch("requests.Session.request") as mock_request:
s = base_session()
s.request('GET', 'sentinel', foo={'bar': 'baz'})
mock_request.assert_called_once_with('GET', 'sentinel', foo={'bar': 'baz'}, proxies={
'http': mock_secret.REQUESTS_PROXY,
'https': mock_secret.REQUESTS_PROXY
})
-244
View File
@@ -1,244 +0,0 @@
#!/usr/bin/env python3
import unittest
import itertools
import datetime
import json
import requests_mock
from bs4 import BeautifulSoup
from .fake import ControlIQApi
from tconnectsync.api.controliq import ControlIQApi as RealControlIQApi
from tconnectsync.api.common import ApiException, ApiLoginException, base_headers
class TestControlIQApi(unittest.TestCase):
LOGIN_HTML = """
<html>
<body>
<form method="post" action="./login.aspx?ReturnUrl=%2f" onsubmit="javascript:return WebForm_OnSubmit();" id="form1">
<div class="aspNetHidden">
<input type="hidden" name="__LASTFOCUS" id="__LASTFOCUS" value="" />
<input type="hidden" name="__EVENTTARGET" id="__EVENTTARGET" value="" />
<input type="hidden" name="__EVENTARGUMENT" id="__EVENTARGUMENT" value="" />
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="AAAAA" />
</div>
<div class="aspNetHidden">
<input type="hidden" name="__VIEWSTATEGENERATOR" id="__VIEWSTATEGENERATOR" value="BBBBB" />
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION" value="CCCCC" />
</div>
</form>
</body>
</html>
"""
LOGIN_POST_DATA = {
"__LASTFOCUS": "",
"__EVENTTARGET": "ctl00$ContentBody$LoginControl$linkLogin",
"__EVENTARGUMENT": "",
"__VIEWSTATE": "AAAAA",
"__VIEWSTATEGENERATOR": "BBBBB",
"__EVENTVALIDATION": "CCCCC",
"ctl00$ContentBody$LoginControl$txtLoginEmailAddress": "email@email.com",
"txtLoginEmailAddress_ClientState": '{"enabled":true,"emptyMessage":"","validationText":"%s","valueAsString":"%s","lastSetTextBoxValue":"%s"}' % ("email@email.com", "email@email.com", "email@email.com"),
"ctl00$ContentBody$LoginControl$txtLoginPassword": "password",
"txtLoginPassword_ClientState": '{"enabled":true,"emptyMessage":"","validationText":"%s","valueAsString":"%s","lastSetTextBoxValue":"%s"}' % ("password", "password", "password")
}
def test_build_login_data(self):
ciq = ControlIQApi()
soup = BeautifulSoup(self.LOGIN_HTML, features='lxml')
self.assertDictEqual(
ciq._build_login_data('email@email.com', 'password', soup),
self.LOGIN_POST_DATA)
def test_login_successful(self):
ciq = ControlIQApi()
ciq.LOGIN_URL = RealControlIQApi.LOGIN_URL
ciq.login = lambda email, password: RealControlIQApi.login(ciq, email, password)
with requests_mock.Mocker() as m:
m.get('https://tconnect.tandemdiabetes.com/login.aspx?ReturnUrl=%2f',
request_headers=base_headers(),
text=self.LOGIN_HTML)
def post_callback(request, context):
context.status_code = 302
context.headers['Location'] = '/newlocation'
context.cookies['UserGUID'] = 'user_guid'
context.cookies['accessToken'] = 'access_tok'
context.cookies['accessTokenExpiresAt'] = '2021-05-04T11:18:08.381Z'
return ''
m.post('https://tconnect.tandemdiabetes.com/login.aspx?ReturnUrl=%2f',
request_headers={'Referer': ciq.LOGIN_URL, **base_headers()},
text=post_callback)
m.post('https://tconnect.tandemdiabetes.com/newlocation',
cookies={'cookie': 'value'},
headers=base_headers(),
status_code=200)
self.assertTrue(ciq.login('email@email.com', 'password'))
self.assertEqual(ciq.userGuid, 'user_guid')
self.assertEqual(ciq.accessToken, 'access_tok')
self.assertEqual(ciq.accessTokenExpiresAt, '2021-05-04T11:18:08.381Z')
def test_login_invalid_credentials(self):
ciq = ControlIQApi()
ciq.LOGIN_URL = RealControlIQApi.LOGIN_URL
ciq.login = lambda email, password: RealControlIQApi.login(ciq, email, password)
with requests_mock.Mocker() as m:
m.get('https://tconnect.tandemdiabetes.com/login.aspx?ReturnUrl=%2f',
request_headers=base_headers(),
text=self.LOGIN_HTML)
def post_callback(request, context):
context.status_code = 200
return '<html><body>...</body></html>'
m.post('https://tconnect.tandemdiabetes.com/login.aspx?ReturnUrl=%2f',
request_headers={'Referer': ciq.LOGIN_URL, **base_headers()},
text=post_callback)
self.assertRaises(ApiLoginException, ciq.login, 'email@email.com', 'password')
self.assertIsNone(ciq.userGuid)
self.assertIsNone(ciq.accessToken)
self.assertIsNone(ciq.accessTokenExpiresAt)
def fake_get_with_http_code(self, http_code, expected_endpoint, num_times):
tries = 0
def fake_get(endpoint, query):
nonlocal http_code, expected_endpoint, num_times, tries
if endpoint.endswith(expected_endpoint):
if tries < num_times:
tries += 1
raise ApiException(http_code, "fake HTTP %d" % http_code)
return {"faked_json": True}
raise NotImplementedError
return fake_get
def test_therapy_timeline_works_after_single_http_500(self):
ciq = ControlIQApi()
ciq.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
ciq._get = self.fake_get_with_http_code(500, "therapytimeline/users/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", 1)
self.assertEqual(
ciq.therapy_timeline('2021-04-01', '2021-04-02'),
{
"faked_json": True
})
def test_therapy_timeline_fails_after_two_http_500s(self):
ciq = ControlIQApi()
ciq.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
ciq._get = self.fake_get_with_http_code(500, "therapytimeline/users/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", 2)
self.assertRaises(ApiException, ciq.therapy_timeline, '2021-04-01', '2021-04-02')
def test_therapy_timeline_triggers_relogin_after_single_http_401(self):
ciq = ControlIQApi()
ciq.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
ciq._email = 'email'
ciq._password = 'password'
hit_login = []
def stub_login(email, password):
nonlocal hit_login
hit_login.append((email, password))
ciq.login = stub_login
ciq._get = self.fake_get_with_http_code(401, "therapytimeline/users/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", 1)
self.assertEqual(
ciq.therapy_timeline('2021-04-01', '2021-04-02'),
{
"faked_json": True
})
self.assertListEqual(hit_login, [
('email', 'password')
])
def test_therapy_timeline_fails_after_two_http_401s(self):
ciq = ControlIQApi()
ciq.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
ciq._email = 'email'
ciq._password = 'password'
hit_login = []
def stub_login(email, password):
nonlocal hit_login
hit_login.append((email, password))
ciq.login = stub_login
ciq._get = self.fake_get_with_http_code(401, "therapytimeline/users/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee", 2)
self.assertRaises(ApiException, ciq.therapy_timeline, '2021-04-01', '2021-04-02')
self.assertListEqual(hit_login, [
('email', 'password')
])
def test_therapy_timeline_parses_date(self):
ciq = ControlIQApi()
ciq.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
def fake_get(endpoint, query):
self.assertTrue(endpoint.endswith("therapytimeline/users/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))
self.assertEqual(query, {
"startDate": "04-01-2021",
"endDate": "04-02-2021"
})
return {"faked_json": True}
ciq._get = fake_get
self.assertEqual(
ciq.therapy_timeline(datetime.date(2021, 4, 1), datetime.date(2021, 4, 2)),
{
"faked_json": True
})
def test_dashboard_summary_parses_date(self):
ciq = ControlIQApi()
ciq.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
def fake_get(endpoint, query):
self.assertTrue(endpoint.endswith("summary/users/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"))
self.assertEqual(query, {
"startDate": "04-01-2021",
"endDate": "04-02-2021"
})
return {"faked_json": True}
ciq._get = fake_get
self.assertEqual(
ciq.dashboard_summary(datetime.date(2021, 4, 1), datetime.date(2021, 4, 2)),
{
"faked_json": True
})
if __name__ == '__main__':
unittest.main()
+508
View File
@@ -0,0 +1,508 @@
#!/usr/bin/env python3
import arrow
import datetime
import unittest
import urllib.parse
from unittest.mock import patch
from tconnectsync.api.tandemsource import TandemSourceApi, naive_local_to_utc
from tconnectsync.api.common import ApiException
from tconnectsync.eventparser import events as eventtypes
# Representative GET api/reports/bff/pumper/{pumperId} response, mirroring the
# structure of a real captured account response: one active pump with settings
# and one never-uploaded pump (null date/settings fields).
BFF_PUMPER = {
"firstName": "Test",
"lastName": "User",
"name": "Test User",
"dateOfBirth": "1990-01-01",
"lowGlucoseThreshold": 70,
"highGlucoseThreshold": 180,
"country": "US",
"pumps": [
{
"algorithm": "Control-IQ",
"availableDataRange": {"start": "2021-05-06T12:31:19", "end": "2022-02-16T22:45:58"},
"assignmentId": "1b493210-9336-4901-a329-a352775738c5",
"lastUploadDate": "2022-09-20T05:50:12Z",
"maxDateOfEvents": "2022-02-16T22:45:58",
"modelNumber": "1000354",
"modelName": "t:slim X2™ Insulin Pump",
"partNumber": "1011979",
"serialNumber": "90556643",
"softwareVersion": "7.8.0.0",
"lastUploadClientType": "mobile_tconnect",
"settings": {
"id": "b7f931c8-63cd-44c9-86aa-56826f9057e5",
"deviceAssignmentId": "1b493210-9336-4901-a329-a352775738c5",
"uploadedTimeStamp": "2022-09-10T21:07:43.497",
"settingsHash": "29EDDA8E7A72C1AD060271268CC7AE81FAD54B9D",
"uploadId": "5da6a0ca-86c3-440f-9462-fa53168dcb9d",
"details": {"profiles": {"numberOfProfiles": 1}},
},
},
{
"algorithm": "Basal-IQ",
"availableDataRange": {"start": None, "end": None},
"assignmentId": "f6631fff-f403-4ce4-9362-83eff9e2850e",
"glucoseUnit": None,
"lastUploadDate": None,
"maxDateOfEvents": None,
"modelNumber": "1000096",
"modelName": "t:slim X2™ Insulin Pump",
"partNumber": "1003314",
"serialNumber": "514387",
"softwareVersion": "6.0.3.0",
"lastUploadClientType": None,
"settings": None,
},
],
}
class TestNaiveLocalToUtc(unittest.TestCase):
"""The module-level naive_local_to_utc() helper is the sole survivor of the
removed PumpMetadata adapter. It normalizes a BFF pump-local naive
wall-clock timestamp to true UTC, and is now called at the specific date
call sites that compare against real UTC."""
maxDiff = None
def test_naive_dates_normalized_to_utc(self):
# America/New_York is set in tests/conftest.py. Feb -> EST (UTC-5),
# May -> EDT (UTC-4). These are the raw BffPump maxDateOfEvents /
# availableDataRange.start values that call sites now normalize.
self.assertEqual(
naive_local_to_utc(BFF_PUMPER["pumps"][0]["maxDateOfEvents"]),
"2022-02-17T03:45:58+00:00",
)
self.assertEqual(
naive_local_to_utc(BFF_PUMPER["pumps"][0]["availableDataRange"]["start"]),
"2021-05-06T16:31:19+00:00",
)
def test_naive_local_to_utc_none_passthrough(self):
self.assertIsNone(naive_local_to_utc(None))
def test_naive_local_to_utc_idempotent_no_double_shift(self):
# A value that already carries a tz must not be shifted again. Feed the
# already-UTC output back in and confirm it is unchanged.
first = naive_local_to_utc("2022-02-16T22:45:58")
self.assertEqual(first, "2022-02-17T03:45:58+00:00")
self.assertEqual(naive_local_to_utc(first), first)
# A 'Z'-suffixed (true UTC) value is passed through as UTC unchanged.
self.assertEqual(
naive_local_to_utc("2022-09-20T05:50:12Z"),
"2022-09-20T05:50:12+00:00",
)
class TestDefaultEventIds(unittest.TestCase):
def test_default_event_ids(self):
ids = TandemSourceApi.DEFAULT_EVENT_IDS
self.assertEqual(len(ids), 55)
self.assertEqual(len(set(ids)), 55, "DEFAULT_EVENT_IDS contains duplicates")
# FSL3 ids added for the BFF pump-logs endpoint
self.assertTrue({477, 480, 486}.issubset(set(ids)))
# Trimmed real-shape pump-logs response (1 event + 1 clockChange).
PUMP_LOGS = {
"events": [
{
"deviceAssignmentId": "1b493210-9336-4901-a329-a352775738c5",
"eventCode": 16,
"sequenceGroup": 1,
"sequenceNumber": 100123,
"pumpDateTime": "2024-01-10T08:15:30",
"eventProperties": {"iob": 1.25, "bg": 112},
"estimatedDateTime": "2024-01-10T08:15:30Z",
}
],
"clockChanges": [
{
"deviceAssignmentId": "1b493210-9336-4901-a329-a352775738c5",
"eventCode": 13,
"sequenceGroup": 0,
"sequenceNumber": 5,
"pumpDateTime": "2024-01-01T00:00:00",
"eventProperties": {"timePrior": 1, "timeAfter": 2, "rawRtcTime": 3},
"estimatedDateTime": "2024-01-01T00:00:00Z",
}
],
}
class TestGetPumpLogs(unittest.TestCase):
maxDiff = None
def _api(self):
api = TandemSourceApi.__new__(TandemSourceApi)
api.pumperId = "PUMPER123"
return api
def _endpoint(self, mock_get):
mock_get.assert_called_once()
# (endpoint, query_dict) positional args
self.assertEqual(mock_get.call_args.args[1], {})
return mock_get.call_args.args[0]
def _qs(self, endpoint, keep_blank=False):
parsed = urllib.parse.urlparse(endpoint)
return parsed.path, urllib.parse.parse_qs(parsed.query, keep_blank_values=keep_blank)
def test_endpoint_path_and_params(self):
api = self._api()
with patch.object(TandemSourceApi, "get", return_value=PUMP_LOGS) as mock_get:
api.get_pump_logs("dev-uuid", min_date="2024-01-01", max_date="2024-01-15")
endpoint = self._endpoint(mock_get)
path, qs = self._qs(endpoint)
self.assertEqual(path, "api/reports/bff/pump-logs/dev-uuid")
self.assertEqual(qs["pumperId"], ["PUMPER123"])
self.assertEqual(qs["startDate"], ["2024-01-01T00:00:00Z"])
self.assertEqual(qs["endDate"], ["2024-01-15T23:59:59Z"])
def test_default_event_ids_comma_joined(self):
api = self._api()
with patch.object(TandemSourceApi, "get", return_value=PUMP_LOGS) as mock_get:
api.get_pump_logs("dev", min_date="2024-01-01", max_date="2024-01-02")
_, qs = self._qs(self._endpoint(mock_get))
self.assertEqual(qs["eventIds"][0].split(","),
[str(i) for i in TandemSourceApi.DEFAULT_EVENT_IDS])
def test_custom_event_ids_comma_joined(self):
api = self._api()
with patch.object(TandemSourceApi, "get", return_value=PUMP_LOGS) as mock_get:
api.get_pump_logs("dev", "2024-01-01", "2024-01-02", event_ids_filter=[16, 5, 28])
_, qs = self._qs(self._endpoint(mock_get))
self.assertEqual(qs["eventIds"], ["16,5,28"])
def test_none_event_ids_empty(self):
api = self._api()
with patch.object(TandemSourceApi, "get", return_value=PUMP_LOGS) as mock_get:
api.get_pump_logs("dev", "2024-01-01", "2024-01-02", event_ids_filter=None)
_, qs = self._qs(self._endpoint(mock_get), keep_blank=True)
self.assertEqual(qs["eventIds"], [""])
def test_return_value_passthrough(self):
api = self._api()
with patch.object(TandemSourceApi, "get", return_value=PUMP_LOGS):
result = api.get_pump_logs("dev", "2024-01-01", "2024-01-15")
self.assertIs(result, PUMP_LOGS)
def test_none_dates_default_to_today(self):
api = self._api()
with patch.object(TandemSourceApi, "get", return_value=PUMP_LOGS) as mock_get:
api.get_pump_logs("dev")
_, qs = self._qs(self._endpoint(mock_get))
today = datetime.datetime.now().strftime('%Y-%m-%d')
self.assertEqual(qs["startDate"], ["%sT00:00:00Z" % today])
self.assertEqual(qs["endDate"], ["%sT23:59:59Z" % today])
def _ev(group, num, event_code=16, pump_date_time="2024-01-10T08:15:30", **props):
"""Trimmed real-shape pump-log event; eventCode 16 parses to LidBgReadingTaken."""
return {
"deviceAssignmentId": "1b493210-9336-4901-a329-a352775738c5",
"eventCode": event_code,
"sequenceGroup": group,
"sequenceNumber": num,
"pumpDateTime": pump_date_time,
"eventProperties": props or {"iob": 1.25, "bg": 112},
"estimatedDateTime": pump_date_time + "Z",
}
class TestPumpLogWindows(unittest.TestCase):
"""#10: the range is paged into inclusive windows no larger than 28 days."""
maxDiff = None
def test_single_day(self):
self.assertEqual(TandemSourceApi._pump_log_windows("2024-01-01", "2024-01-01"),
[("2024-01-01", "2024-01-01")])
def test_short_range_is_one_window(self):
# A span shorter than the window must still yield a covering window.
self.assertEqual(TandemSourceApi._pump_log_windows("2024-01-01", "2024-01-15"),
[("2024-01-01", "2024-01-15")])
def test_exactly_28_days_is_one_window(self):
self.assertEqual(TandemSourceApi._pump_log_windows("2024-01-01", "2024-01-28"),
[("2024-01-01", "2024-01-28")])
def test_29_days_splits(self):
self.assertEqual(TandemSourceApi._pump_log_windows("2024-01-01", "2024-01-29"),
[("2024-01-01", "2024-01-28"), ("2024-01-29", "2024-01-29")])
def test_long_range_windows_are_contiguous_and_bounded(self):
windows = TandemSourceApi._pump_log_windows("2024-01-01", "2024-03-01")
self.assertEqual(windows, [
("2024-01-01", "2024-01-28"),
("2024-01-29", "2024-02-25"),
("2024-02-26", "2024-03-01"),
])
# each window <= 28 days, and windows are contiguous (no gaps/overlaps)
for start, end in windows:
self.assertLessEqual((arrow.get(end) - arrow.get(start)).days, 27)
for (_, prev_end), (next_start, _) in zip(windows, windows[1:]):
self.assertEqual(arrow.get(next_start), arrow.get(prev_end).shift(days=1))
def test_reversed_dates_are_swapped(self):
self.assertEqual(TandemSourceApi._pump_log_windows("2024-03-01", "2024-01-01"),
TandemSourceApi._pump_log_windows("2024-01-01", "2024-03-01"))
def test_none_dates_default_to_single_today_window(self):
windows = TandemSourceApi._pump_log_windows(None, None)
self.assertEqual(len(windows), 1)
self.assertEqual(windows[0][0], windows[0][1])
class TestPumpEvents(unittest.TestCase):
"""#16: pump_events pages get_pump_logs by window, dedupes, skips
clockChanges, and yields parsed event objects."""
maxDiff = None
def _api(self):
api = TandemSourceApi.__new__(TandemSourceApi)
api.pumperId = "PUMPER123"
return api
def test_single_window_one_call_with_default_event_ids(self):
api = self._api()
resp = {"events": [_ev(0, 1)], "clockChanges": []}
with patch.object(TandemSourceApi, "get_pump_logs", return_value=resp) as m:
out = list(api.pump_events("dev-uuid", "2024-01-01", "2024-01-10"))
m.assert_called_once_with("dev-uuid", "2024-01-01", "2024-01-10",
TandemSourceApi.DEFAULT_EVENT_IDS)
self.assertEqual([type(e).__name__ for e in out], ["LidBgReadingTaken"])
def test_fetch_all_event_types_passes_none_filter(self):
api = self._api()
resp = {"events": [], "clockChanges": []}
with patch.object(TandemSourceApi, "get_pump_logs", return_value=resp) as m:
list(api.pump_events("dev", "2024-01-01", "2024-01-10", fetch_all_event_types=True))
self.assertIsNone(m.call_args.args[3])
def test_multi_window_paging_boundaries(self):
api = self._api()
responses = [
{"events": [_ev(0, 1)], "clockChanges": []},
{"events": [_ev(0, 2)], "clockChanges": []},
{"events": [_ev(0, 3)], "clockChanges": []},
]
with patch.object(TandemSourceApi, "get_pump_logs", side_effect=responses) as m:
out = list(api.pump_events("dev", "2024-01-01", "2024-03-01"))
windows = [(c.args[1], c.args[2]) for c in m.call_args_list]
self.assertEqual(windows, [
("2024-01-01", "2024-01-28"),
("2024-01-29", "2024-02-25"),
("2024-02-26", "2024-03-01"),
])
self.assertEqual([e.seqNum for e in out], [1, 2, 3])
def test_dedupes_across_windows_by_group_and_number(self):
api = self._api()
# Same (sequenceGroup, sequenceNumber) appears in two windows -> kept once.
responses = [
{"events": [_ev(0, 100), _ev(0, 101)], "clockChanges": []},
{"events": [_ev(0, 100), _ev(0, 102)], "clockChanges": []},
]
with patch.object(TandemSourceApi, "get_pump_logs", side_effect=responses):
out = list(api.pump_events("dev", "2024-01-01", "2024-02-15"))
self.assertEqual([e.seqNum for e in out], [100, 101, 102])
def test_same_number_different_group_not_deduped(self):
api = self._api()
responses = [
{"events": [_ev(0, 100)], "clockChanges": []},
{"events": [_ev(1, 100)], "clockChanges": []},
]
with patch.object(TandemSourceApi, "get_pump_logs", side_effect=responses):
out = list(api.pump_events("dev", "2024-01-01", "2024-02-15"))
self.assertEqual(len(out), 2)
def test_clock_changes_are_skipped(self):
api = self._api()
resp = {
"events": [_ev(0, 1)],
"clockChanges": [_ev(0, 5, event_code=13), _ev(0, 6, event_code=14)],
}
with patch.object(TandemSourceApi, "get_pump_logs", return_value=resp):
out = list(api.pump_events("dev", "2024-01-01", "2024-01-10"))
self.assertEqual([e.eventId for e in out], [16])
def test_missing_events_key_is_tolerated(self):
api = self._api()
with patch.object(TandemSourceApi, "get_pump_logs", return_value={}):
out = list(api.pump_events("dev", "2024-01-01", "2024-01-10"))
self.assertEqual(out, [])
class TestPumpEventsRealEventTypes(unittest.TestCase):
"""Parse bolus (20), basal (279), CGM (399) and alarm (5) events through
pump_events(). eventProperties use Tandem's real camelCase names; bitmask
fields arrive as arrays of set-bit indices."""
maxDiff = None
def _api(self):
api = TandemSourceApi.__new__(TandemSourceApi)
api.pumperId = "PUMPER123"
return api
RESPONSE = {
"events": [
_ev(0, 201, event_code=20, completionStatus=3, bolusId=777,
insulinDelivered=2.5, insulinRequested=2.5, iob=1.1),
_ev(0, 202, event_code=279, commandedRateSource=1, commandedRate=800,
profileBasalRate=800, algorithmRate=0, tempRate=0),
_ev(0, 203, event_code=399, glucoseValueStatus=0, cgmDataType=[0], rate=-5,
algorithmState=2, rssi=-60, currentGlucoseDisplayValue=112,
egvTimeStamp=123456, egvInfoBitmask=[], interval=5),
_ev(0, 204, event_code=5, alarmId=2, faultLocatorData=100, param1=1, param2=2.0),
],
"clockChanges": [],
}
def _parse(self):
api = self._api()
with patch.object(TandemSourceApi, "get_pump_logs", return_value=self.RESPONSE):
out = list(api.pump_events("dev", "2024-01-01", "2024-01-10"))
return {type(e).__name__: e for e in out}
def test_all_four_event_types_parse(self):
parsed = self._parse()
self.assertEqual(
set(parsed),
{"LidBolusCompleted", "LidBasalDelivery", "LidCgmDataG7", "LidAlarmActivated"},
)
def test_bolus_completed_decodes(self):
e = self._parse()["LidBolusCompleted"]
self.assertEqual(e.eventId, 20)
self.assertEqual(e.seqNum, 201)
self.assertEqual(e.bolusId, 777)
self.assertEqual(e.insulinDelivered, 2.5)
self.assertEqual(e.insulinRequested, 2.5)
self.assertEqual(e.iob, 1.1)
self.assertEqual(e.completionStatus,
eventtypes.LidBolusCompleted.CompletionstatusEnum.Completed)
def test_basal_delivery_decodes(self):
e = self._parse()["LidBasalDelivery"]
self.assertEqual(e.eventId, 279)
self.assertEqual(e.seqNum, 202)
self.assertEqual(e.commandedRate, 800)
self.assertEqual(e.profileBasalRate, 800)
self.assertEqual(e.commandedRateSource,
eventtypes.LidBasalDelivery.CommandedratesourceEnum.Profile)
def test_cgm_g7_decodes(self):
e = self._parse()["LidCgmDataG7"]
self.assertEqual(e.eventId, 399)
self.assertEqual(e.seqNum, 203)
self.assertEqual(e.currentGlucoseDisplayValue, 112)
self.assertEqual(e.glucoseValueStatus,
eventtypes.LidCgmDataG7.GlucosevaluestatusEnum.PreciseValue)
# cgmDataType bitmask array [0] -> bit 0 set -> Fmr
self.assertEqual(e.cgmDataType,
eventtypes.LidCgmDataG7.CgmdatatypeBitmask.Fmr)
# rate is stored raw and scaled x0.1 by the property (-5 -> -0.5 mg/dL/min)
self.assertAlmostEqual(e.rate, -0.5)
def test_alarm_activated_decodes(self):
e = self._parse()["LidAlarmActivated"]
self.assertEqual(e.eventId, 5)
self.assertEqual(e.seqNum, 204)
self.assertEqual(e.faultLocatorData, 100)
self.assertEqual(e.param2, 2.0)
self.assertEqual(e.alarmId,
eventtypes.LidAlarmActivated.AlarmidEnum.OcclusionAlarm)
def _cc(num, code):
return {"eventCode": code, "sequenceGroup": 0, "sequenceNumber": num,
"pumpDateTime": "2024-01-01T00:00:00", "eventProperties": {}}
class TestPumpClockChanges(unittest.TestCase):
def _api(self):
api = TandemSourceApi.__new__(TandemSourceApi)
api.pumperId = "P"
return api
def test_parses_clock_changes(self):
with patch.object(TandemSourceApi, "get_pump_logs",
return_value={"clockChanges": [_cc(5, 13), _cc(6, 14)]}):
out = list(self._api().pump_clock_changes("dev", "2024-01-01", "2024-01-10"))
self.assertEqual([(type(e).__name__, e.seqNum) for e in out],
[("LidTimeChanged", 5), ("LidDateChanged", 6)])
def test_dedupes_across_windows(self):
responses = [{"clockChanges": [_cc(5, 13)]}, {"clockChanges": [_cc(5, 13), _cc(7, 14)]}]
with patch.object(TandemSourceApi, "get_pump_logs", side_effect=responses):
out = list(self._api().pump_clock_changes("dev", "2024-01-01", "2024-02-15"))
self.assertEqual([e.seqNum for e in out], [5, 7])
def test_missing_clock_changes_key_is_tolerated(self):
with patch.object(TandemSourceApi, "get_pump_logs", return_value={}):
out = list(self._api().pump_clock_changes("dev", "2024-01-01", "2024-01-10"))
self.assertEqual(out, [])
class TestGetRetry(unittest.TestCase):
"""get() retries once on 500, re-logs-in and retries once on 401, and
raises immediately on other statuses; after one retry it gives up."""
maxDiff = None
def _api(self):
api = TandemSourceApi.__new__(TandemSourceApi)
api._email = 'e'
api._password = 'p'
api.accessTokenExpiresAt = 0
return api
def test_401_triggers_relogin_then_retry_succeeds(self):
api = self._api()
with patch.object(TandemSourceApi, "_get",
side_effect=[ApiException(401, 'unauth'), {'ok': True}]) as m_get, \
patch.object(TandemSourceApi, "login", return_value=None) as m_login:
result = api.get('ep', {})
self.assertEqual(result, {'ok': True})
self.assertEqual(m_login.call_count, 1)
self.assertEqual(m_get.call_count, 2)
def test_500_retries_without_relogin(self):
api = self._api()
with patch.object(TandemSourceApi, "_get",
side_effect=[ApiException(500, 'err'), {'ok': True}]) as m_get, \
patch.object(TandemSourceApi, "login", return_value=None) as m_login:
result = api.get('ep', {})
self.assertEqual(result, {'ok': True})
self.assertEqual(m_login.call_count, 0)
self.assertEqual(m_get.call_count, 2)
def test_other_status_raises_immediately(self):
api = self._api()
with patch.object(TandemSourceApi, "_get",
side_effect=ApiException(403, 'forbidden')) as m_get, \
patch.object(TandemSourceApi, "login", return_value=None) as m_login:
with self.assertRaises(ApiException):
api.get('ep', {})
self.assertEqual(m_login.call_count, 0)
self.assertEqual(m_get.call_count, 1)
def test_persistent_401_raises_after_one_retry(self):
api = self._api()
with patch.object(TandemSourceApi, "_get",
side_effect=[ApiException(401, 'unauth'), ApiException(401, 'unauth')]) as m_get, \
patch.object(TandemSourceApi, "login", return_value=None) as m_login:
with self.assertRaises(ApiException):
api.get('ep', {})
self.assertEqual(m_login.call_count, 1)
self.assertEqual(m_get.call_count, 2)
if __name__ == "__main__":
unittest.main()
-129
View File
@@ -1,129 +0,0 @@
#!/usr/bin/env python3
import unittest
import itertools
from .fake import WS2Api
from tconnectsync.api.common import ApiException
class TestWS2Api(unittest.TestCase):
def fake_get_with_http_500(self, num_times):
tries = 0
def fake_get(endpoint, query):
nonlocal tries, num_times
if "therapytimeline2csv" in endpoint:
if tries < num_times:
tries += 1
raise ApiException(500, "fake HTTP 500")
return ""
raise NotImplementedError
return fake_get
def test_therapy_timeline_csv_works_after_two_retries(self):
ws2 = WS2Api()
ws2.get = self.fake_get_with_http_500(2)
self.assertEqual(
ws2.therapy_timeline_csv('2021-04-01', '2021-04-02'),
{
"readingData": [],
"iobData": [],
"basalData": [],
"bolusData": []
})
def test_therapy_timeline_csv_fails_after_three_retries(self):
ws2 = WS2Api()
ws2.get = self.fake_get_with_http_500(3)
self.assertRaises(ApiException, ws2.therapy_timeline_csv, '2021-04-01', '2021-04-02')
RAW_DATA_HEADER = """Tandem Diabetes Care Inc.
t:connect Therapy Timeline Data Export
Patient Name, Sample Name
Patient DOB, 1/1/1990
Report Generated On, 4/24/2021 7:50:04 PM
"""
RAW_DATA_CGM = """DeviceType,SerialNumber,Description,EventDateTime,Readings (CGM / BGM)
"t:slim X2 Insulin Pump","11111111","EGV","2021-04-01T00:01:33","235",
"t:slim X2 Insulin Pump","11111111","EGV","2021-04-01T00:06:33","230",
"t:slim X2 Insulin Pump","11111111","EGV","2021-04-02T23:31:36","181",
"""
RAW_DATA_IOB = """Type,EventID,EventDateTime,IOB
"IOB","81","2021-04-01T00:00:19","13.24"
"IOB","9","2021-04-01T00:03:12","12.80"
"IOB","81","2021-04-02T23:58:19","4.25"
"""
RAW_DATA_BOLUS = """Type,Description,BG,IOB,BolusRequestID,BolusCompletionID,CompletionDateTime,InsulinDelivered,FoodDelivered,CorrectionDelivered,CompletionStatusID,CompletionStatusDesc,BolusIsComplete,BolexCompletionID,BolexSize,BolexStartDateTime,BolexCompletionDateTime,BolexInsulinDelivered,BolexIOB,BolexCompletionStatusID,BolexCompletionStatusDesc,ExtendedBolusIsComplete,EventDateTime,RequestDateTime,BolusType,BolusRequestOptions,StandardPercent,Duration,CarbSize,UserOverride,TargetBG,CorrectionFactor,FoodBolusSize,CorrectionBolusSize,ActualTotalBolusRequested,IsQuickBolus,EventHistoryReportEventDesc,EventHistoryReportDetails,NoteID,IndexID,Note
"Bolus","Standard/Correction","141",,"7001.000","7001.000","2021-04-01T12:58:26","13.53","12.50","1.03","3","Completed","1",,,,,,,,,,"2021-04-01T12:53:36","2021-04-01T12:53:36","Carb","Standard/Correction","100.00","0","75","0","110","30.00","12.50","1.03","13.53","0","0","Correction & Food Bolus","CF 1:30 - Carb Ratio 1:6 - Target BG 110","0","1181649","",
"Bolus","Standard","131","0.71","7003.000","7003.000","2021-04-01T16:03:25","1.50","0.00","0.00","3","Completed","1",,,,,,,,,,"2021-04-01T16:02:04","2021-04-01T16:02:04","Carb","Standard","100.00","0","0","1","110","30.00","0.00","0.00","1.50","0","0","Food Bolus","CF 1:30 - Carb Ratio 1:6 - Target BG 110 | Override: Pump calculated Bolus = 0.0 units","0","1182026","",
"Bolus","Standard/Correction","168","1.71","7004.000","7004.000","2021-04-01T16:24:08","2.00","0.00","0.00","3","Completed","1",,,,,,,,,,"2021-04-01T16:22:21","2021-04-01T16:22:21","Carb","Standard/Correction","100.00","0","0","1","110","30.00","0.00","0.22","2.00","0","0","Correction & Food Bolus","CF 1:30 - Carb Ratio 1:6 - Target BG 110 | Override: Pump calculated Bolus = 0.2 units","0","1182082","",
"Bolus","Standard","220","3.98","7032.000","7032.000","2021-04-02T23:16:24","2.50","0.00","0.00","3","Completed","1",,,,,,,,,,"2021-04-02T23:14:33","2021-04-02T23:14:33","Carb","Standard","100.00","0","0","1","110","30.00","0.00","0.00","2.50","0","0","Food Bolus","CF 1:30 - Carb Ratio 1:6 - Target BG 110 | Override: Pump calculated Bolus = 0.0 units","0","1185846","",
"""
RAW_DATA_FULL = RAW_DATA_HEADER + "\n" + RAW_DATA_CGM + "\n" + RAW_DATA_IOB + "\n" + RAW_DATA_BOLUS
PARSED_DATA = {
'readingData': [
{"DeviceType": "t:slim X2 Insulin Pump", "SerialNumber": "11111111", "Description": "EGV", "EventDateTime": "2021-04-01T00:01:33", "Readings (CGM / BGM)": "235"},
{"DeviceType": "t:slim X2 Insulin Pump", "SerialNumber": "11111111", "Description": "EGV", "EventDateTime": "2021-04-01T00:06:33", "Readings (CGM / BGM)": "230"},
{"DeviceType": "t:slim X2 Insulin Pump", "SerialNumber": "11111111", "Description": "EGV", "EventDateTime": "2021-04-02T23:31:36", "Readings (CGM / BGM)": "181"}
],
'iobData': [
{"Type": "IOB", "EventID": "81", "EventDateTime": "2021-04-01T00:00:19", "IOB": "13.24"},
{"Type": "IOB", "EventID": "9", "EventDateTime": "2021-04-01T00:03:12", "IOB": "12.80"},
{"Type": "IOB", "EventID": "81", "EventDateTime": "2021-04-02T23:58:19", "IOB": "4.25"},
],
'basalData': [],
'bolusData': [
{"Type": "Bolus", "Description": "Standard/Correction", "BG": "141", "IOB": "", "BolusRequestID": "7001.000", "BolusCompletionID": "7001.000", "CompletionDateTime": "2021-04-01T12:58:26", "InsulinDelivered": "13.53", "FoodDelivered": "12.50", "CorrectionDelivered": "1.03", "CompletionStatusID": "3", "CompletionStatusDesc": "Completed", "BolusIsComplete": "1", "BolexCompletionID": "", "BolexSize": "", "BolexStartDateTime": "", "BolexCompletionDateTime": "", "BolexInsulinDelivered": "", "BolexIOB": "", "BolexCompletionStatusID": "", "BolexCompletionStatusDesc": "", "ExtendedBolusIsComplete": "", "EventDateTime": "2021-04-01T12:53:36", "RequestDateTime": "2021-04-01T12:53:36", "BolusType": "Carb", "BolusRequestOptions": "Standard/Correction", "StandardPercent": "100.00", "Duration": "0", "CarbSize": "75", "UserOverride": "0", "TargetBG": "110", "CorrectionFactor": "30.00", "FoodBolusSize": "12.50", "CorrectionBolusSize": "1.03", "ActualTotalBolusRequested": "13.53", "IsQuickBolus": "0", "EventHistoryReportEventDesc": "0", "EventHistoryReportDetails": "Correction & Food Bolus", "NoteID": "CF 1:30 - Carb Ratio 1:6 - Target BG 110", "IndexID": "0", "Note": "1181649"},
{"Type": "Bolus", "Description": "Standard", "BG": "131", "IOB": "0.71", "BolusRequestID": "7003.000", "BolusCompletionID": "7003.000", "CompletionDateTime": "2021-04-01T16:03:25", "InsulinDelivered": "1.50", "FoodDelivered": "0.00", "CorrectionDelivered": "0.00", "CompletionStatusID": "3", "CompletionStatusDesc": "Completed", "BolusIsComplete": "1", "BolexCompletionID": "", "BolexSize": "", "BolexStartDateTime": "", "BolexCompletionDateTime": "", "BolexInsulinDelivered": "", "BolexIOB": "", "BolexCompletionStatusID": "", "BolexCompletionStatusDesc": "", "ExtendedBolusIsComplete": "", "EventDateTime": "2021-04-01T16:02:04", "RequestDateTime": "2021-04-01T16:02:04", "BolusType": "Carb", "BolusRequestOptions": "Standard", "StandardPercent": "100.00", "Duration": "0", "CarbSize": "0", "UserOverride": "1", "TargetBG": "110", "CorrectionFactor": "30.00", "FoodBolusSize": "0.00", "CorrectionBolusSize": "0.00", "ActualTotalBolusRequested": "1.50", "IsQuickBolus": "0", "EventHistoryReportEventDesc": "0", "EventHistoryReportDetails": "Food Bolus", "NoteID": "CF 1:30 - Carb Ratio 1:6 - Target BG 110 | Override: Pump calculated Bolus = 0.0 units", "IndexID": "0", "Note": "1182026"},
{"Type": "Bolus", "Description": "Standard/Correction", "BG": "168", "IOB": "1.71", "BolusRequestID": "7004.000", "BolusCompletionID": "7004.000", "CompletionDateTime": "2021-04-01T16:24:08", "InsulinDelivered": "2.00", "FoodDelivered": "0.00", "CorrectionDelivered": "0.00", "CompletionStatusID": "3", "CompletionStatusDesc": "Completed", "BolusIsComplete": "1", "BolexCompletionID": "", "BolexSize": "", "BolexStartDateTime": "", "BolexCompletionDateTime": "", "BolexInsulinDelivered": "", "BolexIOB": "", "BolexCompletionStatusID": "", "BolexCompletionStatusDesc": "", "ExtendedBolusIsComplete": "", "EventDateTime": "2021-04-01T16:22:21", "RequestDateTime": "2021-04-01T16:22:21", "BolusType": "Carb", "BolusRequestOptions": "Standard/Correction", "StandardPercent": "100.00", "Duration": "0", "CarbSize": "0", "UserOverride": "1", "TargetBG": "110", "CorrectionFactor": "30.00", "FoodBolusSize": "0.00", "CorrectionBolusSize": "0.22", "ActualTotalBolusRequested": "2.00", "IsQuickBolus": "0", "EventHistoryReportEventDesc": "0", "EventHistoryReportDetails": "Correction & Food Bolus", "NoteID": "CF 1:30 - Carb Ratio 1:6 - Target BG 110 | Override: Pump calculated Bolus = 0.2 units", "IndexID": "0", "Note": "1182082"},
{"Type": "Bolus", "Description": "Standard", "BG": "220", "IOB": "3.98", "BolusRequestID": "7032.000", "BolusCompletionID": "7032.000", "CompletionDateTime": "2021-04-02T23:16:24", "InsulinDelivered": "2.50", "FoodDelivered": "0.00", "CorrectionDelivered": "0.00", "CompletionStatusID": "3", "CompletionStatusDesc": "Completed", "BolusIsComplete": "1", "BolexCompletionID": "", "BolexSize": "", "BolexStartDateTime": "", "BolexCompletionDateTime": "", "BolexInsulinDelivered": "", "BolexIOB": "", "BolexCompletionStatusID": "", "BolexCompletionStatusDesc": "", "ExtendedBolusIsComplete": "", "EventDateTime": "2021-04-02T23:14:33", "RequestDateTime": "2021-04-02T23:14:33", "BolusType": "Carb", "BolusRequestOptions": "Standard", "StandardPercent": "100.00", "Duration": "0", "CarbSize": "0", "UserOverride": "1", "TargetBG": "110", "CorrectionFactor": "30.00", "FoodBolusSize": "0.00", "CorrectionBolusSize": "0.00", "ActualTotalBolusRequested": "2.50", "IsQuickBolus": "0", "EventHistoryReportEventDesc": "0", "EventHistoryReportDetails": "Food Bolus", "NoteID": "CF 1:30 - Carb Ratio 1:6 - Target BG 110 | Override: Pump calculated Bolus = 0.0 units", "IndexID": "0", "Note": "1185846"}
]
}
def test_therapy_timeline_csv_parses_full(self):
ws2 = WS2Api()
ws2.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
rawData = self.RAW_DATA_FULL
def fake_get(endpoint, query):
nonlocal rawData
if endpoint == 'therapytimeline2csv/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/2021-04-01/2021-04-02?format=csv':
return rawData
ws2.get = fake_get
tt = ws2.therapy_timeline_csv('2021-04-01', '2021-04-02')
self.assertDictEqual(tt, self.PARSED_DATA)
def test_therapy_timeline_csv_parses_random_order(self):
ws2 = WS2Api()
ws2.userGuid = 'aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee'
rawData = ""
def fake_get(endpoint, query):
nonlocal rawData
if endpoint == 'therapytimeline2csv/aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee/2021-04-01/2021-04-02?format=csv':
return rawData
ws2.get = fake_get
# Randomize the order of all sections
for i in itertools.permutations([self.RAW_DATA_HEADER, self.RAW_DATA_CGM, self.RAW_DATA_IOB, self.RAW_DATA_BOLUS], 4):
rawData = "\n".join(i)
tt = ws2.therapy_timeline_csv('2021-04-01', '2021-04-02')
self.assertDictEqual(tt, self.PARSED_DATA)
if __name__ == '__main__':
unittest.main()
+10
View File
@@ -0,0 +1,10 @@
import os
import sys
# Set timezone BEFORE importing any tconnectsync modules
os.environ['TIMEZONE_NAME'] = 'America/New_York'
# Remove any cached imports of tconnectsync modules to force reimport with new env
for module_name in list(sys.modules.keys()):
if module_name.startswith('tconnectsync'):
del sys.modules[module_name]
View File
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
import unittest
from tconnectsync.domain.tandemsource.pump_settings import PumpSettings
# Trimmed real bff/pumper settings.details (values from a captured account,
# schedule condensed to two segments). Extra top-level blocks the parser
# ignores (basalLimitSettings/controlIqSettings/...) are omitted.
SETTINGS_DETAILS = {
"profiles": {
"numberOfProfiles": 2,
"activeSegment": 0,
"activeIdp": 0,
"profile": [
{
"idp": 0,
"timeDependentSegmentNumber": 2,
"name": "A",
"carbEntry": "UnitsAsCarbs",
"maxBolus": 25000,
"insulinDuration": 300,
"timeDependentSegments": [
{"startTime": 0, "basalRate": 800, "carbRatio": 6000, "targetBg": 110, "isf": 30,
"status": ["BasalRateAvailability"]},
{"startTime": 480, "basalRate": 1200, "carbRatio": 6000, "targetBg": 110, "isf": 30,
"status": ["BasalRateAvailability"]},
],
},
{
"idp": 2,
"timeDependentSegmentNumber": 1,
"name": "No delivery",
"carbEntry": "UnitsAsCarbs",
"maxBolus": 25000,
"insulinDuration": 300,
# An all-zero segment must be dropped as a skip.
"timeDependentSegments": [
{"startTime": 0, "basalRate": 0, "carbRatio": 0, "targetBg": 0, "isf": 0, "status": []},
{"startTime": 720, "basalRate": 500, "carbRatio": 12000, "targetBg": 120, "isf": 45, "status": []},
],
},
],
},
"cgmSettings": {
"highGlucoseAlertMgPerDl": 200,
"highGlucoseAlertEnabled": True,
"lowGlucoseAlertMgPerDl": 80,
"lowGlucoseAlertEnabled": True,
"riseRateAlertLevel": 3,
},
# Blocks the parser does not consume; must be ignored, not error.
"basalLimitSettings": {"basalLimitDefault": 5000, "basalLimit": 2500},
"controlIqSettings": {"weight": 140, "closedLoop": False},
}
class TestPumpSettingsFromDict(unittest.TestCase):
maxDiff = None
def setUp(self):
self.settings = PumpSettings.from_dict(SETTINGS_DETAILS)
def test_profiles_container(self):
self.assertEqual(self.settings.profiles.activeIdp, 0)
self.assertEqual(len(self.settings.profiles.profile), 2)
self.assertEqual([p.name for p in self.settings.profiles.profile], ["A", "No delivery"])
def test_profile_fields(self):
profile = self.settings.profiles.profile[0]
self.assertEqual(profile.idp, 0)
self.assertEqual(profile.insulinDuration, 300)
self.assertEqual(profile.maxBolus, 25000)
self.assertEqual(profile.carbEntry, "UnitsAsCarbs")
def test_segments_parse_with_new_key(self):
# The BFF names the container timeDependentSegments (was tDependentSegs).
profile = self.settings.profiles.profile[0]
self.assertEqual(len(profile.timeDependentSegments), 2)
seg = profile.timeDependentSegments[0]
self.assertEqual((seg.startTime, seg.basalRate, seg.carbRatio, seg.targetBg, seg.isf),
(0, 800, 6000, 110, 30))
def test_tdependentsegs_alias(self):
profile = self.settings.profiles.profile[0]
self.assertIs(profile.tDependentSegs, profile.timeDependentSegments)
def test_skip_segments_are_dropped(self):
# "No delivery" has one all-zero (skip) segment and one real segment.
profile = self.settings.profiles.profile[1]
self.assertEqual(len(profile.timeDependentSegments), 1)
self.assertEqual(profile.timeDependentSegments[0].startTime, 720)
def test_cgm_settings_are_flat(self):
self.assertEqual(self.settings.cgmSettings.lowGlucoseAlertMgPerDl, 80)
self.assertEqual(self.settings.cgmSettings.highGlucoseAlertMgPerDl, 200)
if __name__ == "__main__":
unittest.main()
View File
@@ -0,0 +1,107 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
class TestLidAaDailyStatus(unittest.TestCase):
"""313 LID_AA_DAILY_STATUS: pumpControlState/usermode/sensorType enums.
Fixtures are real captured pump-log events copied verbatim, including the
extra weightUnit/weight/currentTdIpop keys the parser ignores.
"""
maxDiff = None
def setUp(self):
# Real capture: pumpControlState 3 -> PcmClosedLoop.
self.fixtureClosedLoop = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 313,
"sequenceGroup": 0,
"sequenceNumber": 393118,
"pumpDateTime": "2026-04-30T00:00:06",
"eventProperties": {
"pumpControlState": 3, "usermode": 1, "sensorType": 3,
"weightUnit": 0, "weight": 0, "currentTdIpop": 0,
},
"estimatedDateTime": "2026-04-30T00:00:06Z",
}
# Real capture: pumpControlState 0 -> PcmNoControlNoCartridgeInstalled.
self.fixtureNoControl = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 313,
"sequenceGroup": 0,
"sequenceNumber": 420321,
"pumpDateTime": "2026-05-08T00:00:06",
"eventProperties": {
"pumpControlState": 0, "usermode": 1, "sensorType": 3,
"weightUnit": 0, "weight": 0, "currentTdIpop": 0,
},
"estimatedDateTime": "2026-05-08T00:00:06Z",
}
def test_dispatches_to_lidaadailystatus(self):
self.assertIsInstance(Event(self.fixtureClosedLoop), eventtypes.LidAaDailyStatus)
self.assertIsInstance(Event(self.fixtureNoControl), eventtypes.LidAaDailyStatus)
def test_envelope_fields(self):
ev = Event(self.fixtureClosedLoop)
self.assertEqual(ev.eventId, 313)
self.assertEqual(ev.seqNum, 393118)
self.assertEqual(Event(self.fixtureNoControl).seqNum, 420321)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureClosedLoop)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T00:00:06")
def test_pumpcontrolstate_closed_loop(self):
ev = Event(self.fixtureClosedLoop)
self.assertEqual(ev.pumpControlStateRaw, 3)
self.assertEqual(ev.pumpControlState,
eventtypes.LidAaDailyStatus.PumpcontrolstateEnum.PcmClosedLoop)
def test_pumpcontrolstate_no_control_zero_value(self):
# pumpControlState 0 must resolve, not be treated as missing.
ev = Event(self.fixtureNoControl)
self.assertEqual(ev.pumpControlStateRaw, 0)
self.assertEqual(ev.pumpControlState,
eventtypes.LidAaDailyStatus.PumpcontrolstateEnum.PcmNoControlNoCartridgeInstalled)
def test_usermode_resolves(self):
ev = Event(self.fixtureClosedLoop)
self.assertEqual(ev.usermodeRaw, 1)
self.assertEqual(ev.usermode,
eventtypes.LidAaDailyStatus.UsermodeEnum.Sleeping)
def test_sensortype_resolves(self):
ev = Event(self.fixtureClosedLoop)
self.assertEqual(ev.sensorTypeRaw, 3)
self.assertEqual(ev.sensorType,
eventtypes.LidAaDailyStatus.SensortypeEnum.CgmTypeDexcomG7)
def test_unknown_keys_ignored(self):
# weightUnit/weight/currentTdIpop are not in the schema and must be
# dropped without raising or becoming attributes.
ev = Event(self.fixtureClosedLoop)
self.assertFalse(hasattr(ev, "weightUnit"))
self.assertFalse(hasattr(ev, "weight"))
self.assertFalse(hasattr(ev, "currentTdIpop"))
def test_todict_is_json_serializable(self):
ev = Event(self.fixtureClosedLoop)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 313)
self.assertEqual(d["name"], "LID_AA_DAILY_STATUS")
self.assertEqual(d["seqNum"], 393118)
self.assertEqual(d["pumpControlStateRaw"], 3)
self.assertEqual(d["usermodeRaw"], 1)
self.assertEqual(d["sensorTypeRaw"], 3)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,147 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidAaPcmChange(unittest.TestCase):
"""230 LID_AA_PCM_CHANGE: currentPcm/previousPcm resolve to a PCM enum,
and the boolean-ish fields resolve to False/True enum members. All
fixtures are real captured events copied verbatim."""
maxDiff = None
def setUp(self):
# currentPcm:0 (NoControl) from previousPcm:3 (ClosedLoop), suspended.
self.fixtureSuspendedNoControl = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 230,
"sequenceGroup": 0,
"sequenceNumber": 394337,
"pumpDateTime": "2026-04-30T10:01:49",
"eventProperties": {
"currentPcm": 0, "previousPcm": 3, "pumpSuspended": 1,
"calculationAvailable": 1, "cgmAvailable": 1,
"closedLoopPreferred": 1, "sufficientClosedLoopParams": 1,
},
"estimatedDateTime": "2026-04-30T10:01:49Z",
}
# currentPcm:3 (ClosedLoop) from previousPcm:0 (NoControl), not suspended.
self.fixtureResumedClosedLoop = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 230,
"sequenceGroup": 0,
"sequenceNumber": 394430,
"pumpDateTime": "2026-04-30T10:16:31",
"eventProperties": {
"currentPcm": 3, "previousPcm": 0, "pumpSuspended": 0,
"calculationAvailable": 1, "cgmAvailable": 1,
"closedLoopPreferred": 1, "sufficientClosedLoopParams": 1,
},
"estimatedDateTime": "2026-04-30T10:16:31Z",
}
# currentPcm:2 (Pining) with cgmAvailable:0 -> FalseVal boolean-ish field.
self.fixturePiningNoCgm = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 230,
"sequenceGroup": 0,
"sequenceNumber": 409128,
"pumpDateTime": "2026-05-04T18:58:22",
"eventProperties": {
"currentPcm": 2, "previousPcm": 3, "pumpSuspended": 0,
"calculationAvailable": 1, "cgmAvailable": 0,
"closedLoopPreferred": 1, "sufficientClosedLoopParams": 1,
},
"estimatedDateTime": "2026-05-04T18:58:22Z",
}
def test_dispatches_to_correct_class(self):
ev = Event(self.fixtureSuspendedNoControl)
self.assertIsInstance(ev, eventtypes.LidAaPcmChange)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureSuspendedNoControl)
self.assertEqual(ev.eventId, 230)
self.assertEqual(ev.seqNum, 394337)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureSuspendedNoControl)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T10:01:49")
def test_pcm_enums_no_control_from_closed_loop(self):
# currentPcm:0 -> NoControl, previousPcm:3 -> ClosedLoop
ev = Event(self.fixtureSuspendedNoControl)
self.assertEqual(ev.currentPcmRaw, 0)
self.assertEqual(ev.currentPcm,
eventtypes.LidAaPcmChange.CurrentpcmEnum.NoControl)
self.assertEqual(ev.previousPcmRaw, 3)
self.assertEqual(ev.previousPcm,
eventtypes.LidAaPcmChange.PreviouspcmEnum.ClosedLoop)
def test_pcm_enums_closed_loop_from_no_control(self):
# currentPcm:3 -> ClosedLoop, previousPcm:0 -> NoControl
ev = Event(self.fixtureResumedClosedLoop)
self.assertEqual(ev.currentPcm,
eventtypes.LidAaPcmChange.CurrentpcmEnum.ClosedLoop)
self.assertEqual(ev.previousPcm,
eventtypes.LidAaPcmChange.PreviouspcmEnum.NoControl)
def test_pcm_enum_pining(self):
# currentPcm:2 -> Pining
ev = Event(self.fixturePiningNoCgm)
self.assertEqual(ev.currentPcmRaw, 2)
self.assertEqual(ev.currentPcm,
eventtypes.LidAaPcmChange.CurrentpcmEnum.Pining)
def test_boolean_fields_when_suspended(self):
ev = Event(self.fixtureSuspendedNoControl)
self.assertEqual(ev.pumpSuspendedRaw, 1)
self.assertEqual(ev.pumpSuspended,
eventtypes.LidAaPcmChange.PumpsuspendedEnum.TrueVal)
self.assertEqual(ev.calculationAvailable,
eventtypes.LidAaPcmChange.CalculationavailableEnum.TrueVal)
self.assertEqual(ev.cgmAvailable,
eventtypes.LidAaPcmChange.CgmavailableEnum.TrueVal)
self.assertEqual(ev.closedLoopPreferred,
eventtypes.LidAaPcmChange.ClosedlooppreferredEnum.TrueVal)
self.assertEqual(ev.sufficientClosedLoopParams,
eventtypes.LidAaPcmChange.SufficientclosedloopparamsEnum.TrueVal)
def test_pump_suspended_false(self):
# pumpSuspended:0 -> FalseVal (0 must not be treated as missing)
ev = Event(self.fixtureResumedClosedLoop)
self.assertEqual(ev.pumpSuspendedRaw, 0)
self.assertEqual(ev.pumpSuspended,
eventtypes.LidAaPcmChange.PumpsuspendedEnum.FalseVal)
def test_cgm_available_false(self):
# cgmAvailable:0 -> FalseVal while other boolean-ish fields stay TrueVal
ev = Event(self.fixturePiningNoCgm)
self.assertEqual(ev.cgmAvailableRaw, 0)
self.assertEqual(ev.cgmAvailable,
eventtypes.LidAaPcmChange.CgmavailableEnum.FalseVal)
self.assertEqual(ev.calculationAvailable,
eventtypes.LidAaPcmChange.CalculationavailableEnum.TrueVal)
self.assertEqual(ev.closedLoopPreferred,
eventtypes.LidAaPcmChange.ClosedlooppreferredEnum.TrueVal)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureSuspendedNoControl,
self.fixtureResumedClosedLoop,
self.fixturePiningNoCgm):
ev = Event(fixture)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 230)
self.assertEqual(d["name"], "LID_AA_PCM_CHANGE")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,163 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidAaUserModeChange(unittest.TestCase):
"""229 LID_AA_USER_MODE_CHANGE, from real captured pump-log events."""
maxDiff = None
def setUp(self):
# Normal <- Sleeping, requestedAction StopSleep, activeSleepSchedule [0].
self.fixtureStopSleep = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 229,
"sequenceGroup": 0,
"sequenceNumber": 456851,
"pumpDateTime": "2026-05-18T10:15:53",
"eventProperties": {
"currentUserMode": 0, "previousUserMode": 1, "requestedAction": 2,
"spareA3": 0, "sleepStartedByGui": 1, "activeSleepSchedule": [0],
"spareB6": 0, "exerciseStoppedByTimer": 0, "exerciseChoice": 0,
"exerciseTime": 0, "eatingSoonStoppedByTimer": 0,
},
"estimatedDateTime": "2026-05-18T10:15:53Z",
}
# Sleeping <- Normal, requestedAction StartSleep, activeSleepSchedule [0].
self.fixtureStartSleep = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 229,
"sequenceGroup": 0,
"sequenceNumber": 456855,
"pumpDateTime": "2026-05-18T10:16:00",
"eventProperties": {
"currentUserMode": 1, "previousUserMode": 0, "requestedAction": 1,
"spareA3": 0, "sleepStartedByGui": 1, "activeSleepSchedule": [0],
"spareB6": 0, "exerciseStoppedByTimer": 0, "exerciseChoice": 0,
"exerciseTime": 0, "eatingSoonStoppedByTimer": 0,
},
"estimatedDateTime": "2026-05-18T10:16:00Z",
}
# Exercising <- Normal, requestedAction StartExercise, empty activeSleepSchedule.
self.fixtureStartExercise = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 229,
"sequenceGroup": 0,
"sequenceNumber": 456961,
"pumpDateTime": "2026-05-18T10:20:04",
"eventProperties": {
"currentUserMode": 2, "previousUserMode": 0, "requestedAction": 3,
"spareA3": 0, "sleepStartedByGui": 0, "activeSleepSchedule": [],
"spareB6": 0, "exerciseStoppedByTimer": 0, "exerciseChoice": 0,
"exerciseTime": 0, "eatingSoonStoppedByTimer": 0,
},
"estimatedDateTime": "2026-05-18T10:20:04Z",
}
# Sleeping <- Exercising, requestedAction StopExercise, activeSleepSchedule [0].
self.fixtureStopExercise = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 229,
"sequenceGroup": 0,
"sequenceNumber": 456965,
"pumpDateTime": "2026-05-18T10:20:15",
"eventProperties": {
"currentUserMode": 1, "previousUserMode": 2, "requestedAction": 4,
"spareA3": 0, "sleepStartedByGui": 0, "activeSleepSchedule": [0],
"spareB6": 0, "exerciseStoppedByTimer": 0, "exerciseChoice": 0,
"exerciseTime": 0, "eatingSoonStoppedByTimer": 0,
},
"estimatedDateTime": "2026-05-18T10:20:15Z",
}
def test_dispatches_to_correct_class(self):
for fx in (self.fixtureStopSleep, self.fixtureStartSleep,
self.fixtureStartExercise, self.fixtureStopExercise):
ev = Event(fx)
self.assertIsInstance(ev, eventtypes.LidAaUserModeChange)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureStopSleep)
self.assertEqual(ev.eventId, 229)
self.assertEqual(ev.seqNum, 456851)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-05-18T10:15:53")
def test_envelope_fields_other_fixture(self):
ev = Event(self.fixtureStartExercise)
self.assertEqual(ev.eventId, 229)
self.assertEqual(ev.seqNum, 456961)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-05-18T10:20:04")
def test_stop_sleep_enums(self):
ev = Event(self.fixtureStopSleep)
self.assertEqual(ev.currentUserModeRaw, 0)
self.assertEqual(ev.currentUserMode,
eventtypes.LidAaUserModeChange.CurrentusermodeEnum.Normal)
self.assertEqual(ev.previousUserModeRaw, 1)
self.assertEqual(ev.previousUserMode,
eventtypes.LidAaUserModeChange.PrevioususermodeEnum.Sleeping)
self.assertEqual(ev.requestedActionRaw, 2)
self.assertEqual(ev.requestedAction,
eventtypes.LidAaUserModeChange.RequestedactionEnum.StopSleep)
def test_start_sleep_enums(self):
ev = Event(self.fixtureStartSleep)
self.assertEqual(ev.currentUserMode,
eventtypes.LidAaUserModeChange.CurrentusermodeEnum.Sleeping)
self.assertEqual(ev.previousUserMode,
eventtypes.LidAaUserModeChange.PrevioususermodeEnum.Normal)
self.assertEqual(ev.requestedAction,
eventtypes.LidAaUserModeChange.RequestedactionEnum.StartSleep)
def test_start_exercise_enums(self):
ev = Event(self.fixtureStartExercise)
self.assertEqual(ev.currentUserMode,
eventtypes.LidAaUserModeChange.CurrentusermodeEnum.Exercising)
self.assertEqual(ev.previousUserMode,
eventtypes.LidAaUserModeChange.PrevioususermodeEnum.Normal)
self.assertEqual(ev.requestedAction,
eventtypes.LidAaUserModeChange.RequestedactionEnum.StartExercise)
def test_stop_exercise_enums(self):
ev = Event(self.fixtureStopExercise)
self.assertEqual(ev.currentUserMode,
eventtypes.LidAaUserModeChange.CurrentusermodeEnum.Sleeping)
self.assertEqual(ev.previousUserMode,
eventtypes.LidAaUserModeChange.PrevioususermodeEnum.Exercising)
self.assertEqual(ev.requestedAction,
eventtypes.LidAaUserModeChange.RequestedactionEnum.StopExercise)
def test_active_sleep_schedule_single_bit(self):
# activeSleepSchedule:[0] -> 1<<0 == 1 -> SleepSchedule1IsActive
ev = Event(self.fixtureStopSleep)
self.assertEqual(ev.activeSleepScheduleRaw, 1)
self.assertEqual(ev.activeSleepSchedule,
eventtypes.LidAaUserModeChange.ActivesleepscheduleBitmask.SleepSchedule1IsActive)
def test_active_sleep_schedule_empty(self):
# An empty array folds to 0 (empty IntFlag), not None.
ev = Event(self.fixtureStartExercise)
self.assertEqual(ev.activeSleepScheduleRaw, 0)
self.assertEqual(ev.activeSleepSchedule,
eventtypes.LidAaUserModeChange.ActivesleepscheduleBitmask(0))
self.assertEqual(int(ev.activeSleepSchedule), 0)
def test_todict_json_serializable(self):
for fx in (self.fixtureStopSleep, self.fixtureStartSleep,
self.fixtureStartExercise, self.fixtureStopExercise):
ev = Event(fx)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 229)
self.assertEqual(d["name"], "LID_AA_USER_MODE_CHANGE")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidAlarmActivated(unittest.TestCase):
"""5: LID_ALARM_ACTIVATED. Real captured pump-log events; alarmId is a
dictionary transform resolving to an AlarmidEnum member."""
maxDiff = None
def setUp(self):
# Real capture: alarmId 18 -> RESUME_PUMP_ALARM.
self.fixtureResumePumpAlarm = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 5,
"sequenceGroup": 0,
"sequenceNumber": 398724,
"pumpDateTime": "2026-05-01T17:08:10",
"eventProperties": {"alarmId": 18, "faultLocatorData": 8311, "param1": 3993668, "param2": 0},
"estimatedDateTime": "2026-05-01T17:08:10Z",
}
# Real capture: alarmId 23 -> RESUME_PUMP_ALARM2.
self.fixtureResumePumpAlarm2 = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 5,
"sequenceGroup": 0,
"sequenceNumber": 398725,
"pumpDateTime": "2026-05-01T17:08:10",
"eventProperties": {"alarmId": 23, "faultLocatorData": 8311, "param1": 18, "param2": 0},
"estimatedDateTime": "2026-05-01T17:08:10Z",
}
def test_dispatches_to_correct_class(self):
self.assertIsInstance(Event(self.fixtureResumePumpAlarm), eventtypes.LidAlarmActivated)
self.assertIsInstance(Event(self.fixtureResumePumpAlarm2), eventtypes.LidAlarmActivated)
self.assertNotIsInstance(Event(self.fixtureResumePumpAlarm), RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.eventId, 5)
self.assertEqual(ev.seqNum, 398724)
ev2 = Event(self.fixtureResumePumpAlarm2)
self.assertEqual(ev2.eventId, 5)
self.assertEqual(ev2.seqNum, 398725)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'), "2026-05-01T17:08:10")
def test_alarmid_resolves_resume_pump_alarm(self):
# alarmId:18 -> RESUME_PUMP_ALARM
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.alarmIdRaw, 18)
self.assertEqual(ev.alarmId, eventtypes.LidAlarmActivated.AlarmidEnum.ResumePumpAlarm)
def test_alarmid_resolves_resume_pump_alarm2(self):
# alarmId:23 -> RESUME_PUMP_ALARM2
ev = Event(self.fixtureResumePumpAlarm2)
self.assertEqual(ev.alarmIdRaw, 23)
self.assertEqual(ev.alarmId, eventtypes.LidAlarmActivated.AlarmidEnum.ResumePumpAlarm2)
def test_plain_fields(self):
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.faultLocatorData, 8311)
self.assertEqual(ev.param1, 3993668)
self.assertEqual(ev.param2, 0)
ev2 = Event(self.fixtureResumePumpAlarm2)
self.assertEqual(ev2.faultLocatorData, 8311)
self.assertEqual(ev2.param1, 18)
self.assertEqual(ev2.param2, 0)
def test_todict_is_json_serializable(self):
for f in (self.fixtureResumePumpAlarm, self.fixtureResumePumpAlarm2):
ev = Event(f)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 5)
self.assertEqual(d["name"], "LID_ALARM_ACTIVATED")
self.assertEqual(Event(self.fixtureResumePumpAlarm).todict(), {
"id": 5,
"name": "LID_ALARM_ACTIVATED",
"seqNum": 398724,
"eventTimestamp": "2026-05-01T17:08:10-04:00",
"alarmIdRaw": 18,
"faultLocatorData": 8311,
"param1": 3993668,
"param2": 0,
})
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,86 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidAlarmCleared(unittest.TestCase):
"""28: LID_ALARM_CLEARED. Real captured pump-log events; alarmId is a
dictionary transform resolving to an AlarmidEnum member."""
maxDiff = None
def setUp(self):
# Real capture: alarmId 18 -> RESUME_PUMP_ALARM.
self.fixtureResumePumpAlarm = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 28,
"sequenceGroup": 0,
"sequenceNumber": 398734,
"pumpDateTime": "2026-05-01T17:11:22",
"eventProperties": {"alarmId": 18},
"estimatedDateTime": "2026-05-01T17:11:22Z",
}
# Real capture: alarmId 23 -> RESUME_PUMP_ALARM2.
self.fixtureResumePumpAlarm2 = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 28,
"sequenceGroup": 0,
"sequenceNumber": 398733,
"pumpDateTime": "2026-05-01T17:11:22",
"eventProperties": {"alarmId": 23},
"estimatedDateTime": "2026-05-01T17:11:22Z",
}
def test_dispatches_to_correct_class(self):
self.assertIsInstance(Event(self.fixtureResumePumpAlarm), eventtypes.LidAlarmCleared)
self.assertIsInstance(Event(self.fixtureResumePumpAlarm2), eventtypes.LidAlarmCleared)
self.assertNotIsInstance(Event(self.fixtureResumePumpAlarm), RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.eventId, 28)
self.assertEqual(ev.seqNum, 398734)
ev2 = Event(self.fixtureResumePumpAlarm2)
self.assertEqual(ev2.eventId, 28)
self.assertEqual(ev2.seqNum, 398733)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'), "2026-05-01T17:11:22")
def test_alarmid_resolves_resume_pump_alarm(self):
# alarmId:18 -> RESUME_PUMP_ALARM
ev = Event(self.fixtureResumePumpAlarm)
self.assertEqual(ev.alarmIdRaw, 18)
self.assertEqual(ev.alarmId, eventtypes.LidAlarmCleared.AlarmidEnum.ResumePumpAlarm)
def test_alarmid_resolves_resume_pump_alarm2(self):
# alarmId:23 -> RESUME_PUMP_ALARM2
ev = Event(self.fixtureResumePumpAlarm2)
self.assertEqual(ev.alarmIdRaw, 23)
self.assertEqual(ev.alarmId, eventtypes.LidAlarmCleared.AlarmidEnum.ResumePumpAlarm2)
def test_todict_is_json_serializable(self):
for f in (self.fixtureResumePumpAlarm, self.fixtureResumePumpAlarm2):
ev = Event(f)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 28)
self.assertEqual(d["name"], "LID_ALARM_CLEARED")
self.assertEqual(Event(self.fixtureResumePumpAlarm).todict(), {
"id": 28,
"name": "LID_ALARM_CLEARED",
"seqNum": 398734,
"eventTimestamp": "2026-05-01T17:11:22-04:00",
"alarmIdRaw": 18,
})
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,155 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidAlertActivated(unittest.TestCase):
"""4: LID_ALERT_ACTIVATED. alertid is a dictionary/enum field resolved
through alertidRaw; faultlocatordata/param1/param2 are plain numeric fields.
All fixtures are real captured pump-log events copied verbatim."""
maxDiff = None
def setUp(self):
# alertId:50 -> DefaultAlert50; integer param2, zero fault/param1.
self.fixtureDefaultAlert50 = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 4,
"sequenceGroup": 0,
"sequenceNumber": 395022,
"pumpDateTime": "2026-04-30T14:26:30",
"eventProperties": {"alertId": 50, "faultLocatorData": 0, "param1": 0, "param2": 866},
"estimatedDateTime": "2026-04-30T14:26:30Z",
}
# alertId:51 -> ControlIqLow.
self.fixtureControlIqLow = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 4,
"sequenceGroup": 0,
"sequenceNumber": 396263,
"pumpDateTime": "2026-04-30T23:07:17",
"eventProperties": {"alertId": 51, "faultLocatorData": 0, "param1": 0, "param2": 877},
"estimatedDateTime": "2026-04-30T23:07:17Z",
}
# alertId:0 -> LowInsulinAlert (zero must resolve, not read as missing);
# non-zero faultLocatorData and a fractional float param2.
self.fixtureLowInsulinFloat = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 4,
"sequenceGroup": 0,
"sequenceNumber": 398333,
"pumpDateTime": "2026-05-01T15:57:06",
"eventProperties": {"alertId": 0, "faultLocatorData": 8242, "param1": 102, "param2": 249.76517},
"estimatedDateTime": "2026-05-01T15:57:06Z",
}
# alertId:14 -> IncompleteFillTubingAlert; all-zero params.
self.fixtureIncompleteFillTubing = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 4,
"sequenceGroup": 0,
"sequenceNumber": 420528,
"pumpDateTime": "2026-05-08T00:52:18",
"eventProperties": {"alertId": 14, "faultLocatorData": 8378, "param1": 0, "param2": 0},
"estimatedDateTime": "2026-05-08T00:52:18Z",
}
# alertId:2 -> LowPowerAlert.
self.fixtureLowPower = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 4,
"sequenceGroup": 0,
"sequenceNumber": 436691,
"pumpDateTime": "2026-05-12T17:52:10",
"eventProperties": {"alertId": 2, "faultLocatorData": 8306, "param1": 20, "param2": 1},
"estimatedDateTime": "2026-05-12T17:52:10Z",
}
def test_dispatches_to_correct_class(self):
for f in (self.fixtureDefaultAlert50, self.fixtureControlIqLow,
self.fixtureLowInsulinFloat, self.fixtureIncompleteFillTubing,
self.fixtureLowPower):
ev = Event(f)
self.assertIsInstance(ev, eventtypes.LidAlertActivated)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureDefaultAlert50)
self.assertEqual(ev.eventId, 4)
self.assertEqual(ev.seqNum, 395022)
ev = Event(self.fixtureControlIqLow)
self.assertEqual(ev.eventId, 4)
self.assertEqual(ev.seqNum, 396263)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureDefaultAlert50)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T14:26:30")
ev = Event(self.fixtureLowPower)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-05-12T17:52:10")
def test_plain_fields(self):
ev = Event(self.fixtureLowInsulinFloat)
self.assertEqual(ev.faultLocatorData, 8242)
self.assertEqual(ev.param1, 102)
self.assertAlmostEqual(ev.param2, 249.76517)
ev = Event(self.fixtureIncompleteFillTubing)
self.assertEqual(ev.faultLocatorData, 8378)
self.assertEqual(ev.param1, 0)
self.assertEqual(ev.param2, 0)
def test_alertid_enum_resolves_from_raw_int(self):
ev = Event(self.fixtureDefaultAlert50)
self.assertEqual(ev.alertIdRaw, 50)
self.assertEqual(ev.alertId,
eventtypes.LidAlertActivated.AlertidEnum.DefaultAlert50)
ev = Event(self.fixtureControlIqLow)
self.assertEqual(ev.alertIdRaw, 51)
self.assertEqual(ev.alertId,
eventtypes.LidAlertActivated.AlertidEnum.ControlIqLow)
ev = Event(self.fixtureIncompleteFillTubing)
self.assertEqual(ev.alertIdRaw, 14)
self.assertEqual(ev.alertId,
eventtypes.LidAlertActivated.AlertidEnum.IncompleteFillTubingAlert)
ev = Event(self.fixtureLowPower)
self.assertEqual(ev.alertIdRaw, 2)
self.assertEqual(ev.alertId,
eventtypes.LidAlertActivated.AlertidEnum.LowPowerAlert)
def test_alertid_zero_value_resolves(self):
# alertId:0 -> LowInsulinAlert (0 must not be treated as missing).
ev = Event(self.fixtureLowInsulinFloat)
self.assertEqual(ev.alertIdRaw, 0)
self.assertEqual(ev.alertId,
eventtypes.LidAlertActivated.AlertidEnum.LowInsulinAlert)
def test_todict_is_json_serializable(self):
for f in (self.fixtureDefaultAlert50, self.fixtureLowInsulinFloat,
self.fixtureLowPower):
ev = Event(f)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 4)
self.assertEqual(d["name"], "LID_ALERT_ACTIVATED")
def test_todict_round_trips_fields(self):
ev = Event(self.fixtureLowInsulinFloat)
d = ev.todict()
self.assertEqual(d["seqNum"], 398333)
self.assertEqual(d["alertIdRaw"], 0)
self.assertEqual(d["faultLocatorData"], 8242)
self.assertEqual(d["param1"], 102)
self.assertAlmostEqual(d["param2"], 249.76517)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,113 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
# Real LID_ALERT_CLEARED (eventCode 26) events copied verbatim from a captured
# pump-log response. Each has a different alertId (dictionary enum) value.
class TestLidAlertCleared(unittest.TestCase):
maxDiff = None
def setUp(self):
# alertId 0 -> LowInsulinAlert (0 must not be treated as missing)
self.fixtureLowInsulin = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 26,
"sequenceGroup": 0,
"sequenceNumber": 398601,
"pumpDateTime": "2026-05-01T16:49:45",
"eventProperties": {"alertId": 0, "faultLocatorData": 0},
"estimatedDateTime": "2026-05-01T16:49:45Z",
}
# alertId 2 -> LowPowerAlert
self.fixtureLowPower = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 26,
"sequenceGroup": 0,
"sequenceNumber": 439055,
"pumpDateTime": "2026-05-13T10:06:58",
"eventProperties": {"alertId": 2, "faultLocatorData": 0},
"estimatedDateTime": "2026-05-13T10:06:58Z",
}
# alertId 14 -> IncompleteFillTubingAlert
self.fixtureIncompleteFillTubing = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 26,
"sequenceGroup": 0,
"sequenceNumber": 420534,
"pumpDateTime": "2026-05-08T00:52:50",
"eventProperties": {"alertId": 14, "faultLocatorData": 0},
"estimatedDateTime": "2026-05-08T00:52:50Z",
}
# alertId 51 -> ControlIqLow
self.fixtureControlIqLow = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 26,
"sequenceGroup": 0,
"sequenceNumber": 396276,
"pumpDateTime": "2026-04-30T23:12:18",
"eventProperties": {"alertId": 51, "faultLocatorData": 0},
"estimatedDateTime": "2026-04-30T23:12:18Z",
}
def test_dispatches_to_lidalertcleared(self):
for fx in (self.fixtureLowInsulin, self.fixtureLowPower,
self.fixtureIncompleteFillTubing, self.fixtureControlIqLow):
ev = Event(fx)
self.assertIsInstance(ev, eventtypes.LidAlertCleared)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureControlIqLow)
self.assertEqual(ev.eventId, 26)
self.assertEqual(ev.seqNum, 396276)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureControlIqLow)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T23:12:18")
def test_plain_field_round_trips(self):
ev = Event(self.fixtureControlIqLow)
self.assertEqual(ev.faultLocatorData, 0)
def test_alertid_raw_round_trips(self):
self.assertEqual(Event(self.fixtureLowInsulin).alertIdRaw, 0)
self.assertEqual(Event(self.fixtureLowPower).alertIdRaw, 2)
self.assertEqual(Event(self.fixtureIncompleteFillTubing).alertIdRaw, 14)
self.assertEqual(Event(self.fixtureControlIqLow).alertIdRaw, 51)
def test_alertid_resolves_to_enum(self):
E = eventtypes.LidAlertCleared.AlertidEnum
self.assertEqual(Event(self.fixtureLowInsulin).alertId, E.LowInsulinAlert)
self.assertEqual(Event(self.fixtureLowPower).alertId, E.LowPowerAlert)
self.assertEqual(Event(self.fixtureIncompleteFillTubing).alertId,
E.IncompleteFillTubingAlert)
self.assertEqual(Event(self.fixtureControlIqLow).alertId, E.ControlIqLow)
def test_alertid_zero_resolves(self):
# alertId 0 must resolve, not be dropped as a falsy/missing value.
ev = Event(self.fixtureLowInsulin)
self.assertEqual(ev.alertIdRaw, 0)
self.assertEqual(ev.alertId,
eventtypes.LidAlertCleared.AlertidEnum.LowInsulinAlert)
def test_todict_is_json_serializable(self):
ev = Event(self.fixtureControlIqLow)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 26)
self.assertEqual(d["name"], "LID_ALERT_CLEARED")
self.assertEqual(d["seqNum"], 396276)
self.assertEqual(d["alertIdRaw"], 51)
self.assertEqual(d["faultLocatorData"], 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,159 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
class TestLidBasalDelivery(unittest.TestCase):
"""279 LID_BASAL_DELIVERY: commandedRateSource enum + milliunits/hr rates.
Fixtures are real captured pump-log dicts (copied verbatim), each with a
different commandedRateSource so every enum member is exercised. reservedA2
and spareA3 are ignored by the parser and not asserted on.
"""
maxDiff = None
def setUp(self):
# commandedRateSource:0 -> Suspended; commandedRate 0, algorithmRate/tempRate sentinel.
self.fixtureSuspended = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 279,
"sequenceGroup": 0,
"sequenceNumber": 394356,
"pumpDateTime": "2026-04-30T10:04:05",
"eventProperties": {
"commandedRateSource": 0, "reservedA2": 3, "spareA3": 0,
"commandedRate": 0, "profileBasalRate": 1200,
"algorithmRate": 65535, "tempRate": 65535,
},
"estimatedDateTime": "2026-04-30T10:04:05Z",
}
# commandedRateSource:1 -> Profile; commandedRate follows profileBasalRate.
self.fixtureProfile = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 279,
"sequenceGroup": 0,
"sequenceNumber": 409132,
"pumpDateTime": "2026-05-04T18:58:52",
"eventProperties": {
"commandedRateSource": 1, "reservedA2": 3, "spareA3": 0,
"commandedRate": 1000, "profileBasalRate": 1000,
"algorithmRate": 65535, "tempRate": 65535,
},
"estimatedDateTime": "2026-05-04T18:58:52Z",
}
# commandedRateSource:2 -> TempRate; real tempRate=500 (not the 65535 sentinel).
self.fixtureTempRate = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 279,
"sequenceGroup": 0,
"sequenceNumber": 449599,
"pumpDateTime": "2026-05-16T11:16:07",
"eventProperties": {
"commandedRateSource": 2, "reservedA2": 0, "spareA3": 0,
"commandedRate": 500, "profileBasalRate": 1000,
"algorithmRate": 65535, "tempRate": 500,
},
"estimatedDateTime": "2026-05-16T11:16:07Z",
}
# commandedRateSource:3 -> Algorithm; commandedRate follows algorithmRate, tempRate sentinel.
self.fixtureAlgorithm = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 279,
"sequenceGroup": 0,
"sequenceNumber": 393151,
"pumpDateTime": "2026-04-30T00:08:30",
"eventProperties": {
"commandedRateSource": 3, "reservedA2": 3, "spareA3": 0,
"commandedRate": 1061, "profileBasalRate": 1000,
"algorithmRate": 1061, "tempRate": 65535,
},
"estimatedDateTime": "2026-04-30T00:08:30Z",
}
# commandedRateSource:4 -> TempRateAndAlgorithm; both algorithmRate and real tempRate=600 present.
self.fixtureTempRateAndAlgorithm = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 279,
"sequenceGroup": 0,
"sequenceNumber": 449571,
"pumpDateTime": "2026-05-16T11:01:05",
"eventProperties": {
"commandedRateSource": 4, "reservedA2": 3, "spareA3": 0,
"commandedRate": 500, "profileBasalRate": 1000,
"algorithmRate": 500, "tempRate": 500,
},
"estimatedDateTime": "2026-05-16T11:01:05Z",
}
def test_dispatches_to_correct_class(self):
for fixture in (self.fixtureSuspended, self.fixtureProfile,
self.fixtureTempRate, self.fixtureAlgorithm,
self.fixtureTempRateAndAlgorithm):
ev = Event(fixture)
self.assertIsInstance(ev, eventtypes.LidBasalDelivery)
def test_envelope_fields(self):
ev = Event(self.fixtureAlgorithm)
self.assertEqual(ev.eventId, 279)
self.assertEqual(ev.seqNum, 393151)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T00:08:30")
def test_rate_fields_round_trip(self):
ev = Event(self.fixtureAlgorithm)
self.assertEqual(ev.commandedRate, 1061)
self.assertEqual(ev.profileBasalRate, 1000)
self.assertEqual(ev.algorithmRate, 1061)
self.assertEqual(ev.tempRate, 65535)
def test_temp_rate_sentinel_vs_real(self):
# Algorithm capture uses the 65535 sentinel; TempRate capture has a real value.
self.assertEqual(Event(self.fixtureAlgorithm).tempRate, 65535)
self.assertEqual(Event(self.fixtureTempRate).tempRate, 500)
self.assertEqual(Event(self.fixtureTempRateAndAlgorithm).tempRate, 500)
def test_commanded_rate_source_suspended(self):
ev = Event(self.fixtureSuspended)
self.assertEqual(ev.commandedRateSourceRaw, 0)
self.assertEqual(ev.commandedRateSource,
eventtypes.LidBasalDelivery.CommandedratesourceEnum.Suspended)
def test_commanded_rate_source_profile(self):
ev = Event(self.fixtureProfile)
self.assertEqual(ev.commandedRateSourceRaw, 1)
self.assertEqual(ev.commandedRateSource,
eventtypes.LidBasalDelivery.CommandedratesourceEnum.Profile)
def test_commanded_rate_source_temp_rate(self):
ev = Event(self.fixtureTempRate)
self.assertEqual(ev.commandedRateSourceRaw, 2)
self.assertEqual(ev.commandedRateSource,
eventtypes.LidBasalDelivery.CommandedratesourceEnum.TempRate)
def test_commanded_rate_source_algorithm(self):
ev = Event(self.fixtureAlgorithm)
self.assertEqual(ev.commandedRateSourceRaw, 3)
self.assertEqual(ev.commandedRateSource,
eventtypes.LidBasalDelivery.CommandedratesourceEnum.Algorithm)
def test_commanded_rate_source_temp_rate_and_algorithm(self):
ev = Event(self.fixtureTempRateAndAlgorithm)
self.assertEqual(ev.commandedRateSourceRaw, 4)
self.assertEqual(ev.commandedRateSource,
eventtypes.LidBasalDelivery.CommandedratesourceEnum.TempRateAndAlgorithm)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureSuspended, self.fixtureProfile,
self.fixtureTempRate, self.fixtureAlgorithm,
self.fixtureTempRateAndAlgorithm):
d = Event(fixture).todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 279)
self.assertEqual(d["name"], "LID_BASAL_DELIVERY")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,115 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBgReadingTaken(unittest.TestCase):
maxDiff = None
def setUp(self):
# Real captured LID_BG_READING_TAKEN (eventCode 16) events, copied
# verbatim. The two fixtures differ only in bgEntryType.
self.fixtureManualEntry = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 16,
"sequenceGroup": 0,
"sequenceNumber": 456822,
"pumpDateTime": "2026-05-18T10:15:14",
"eventProperties": {
"bg": 151, "cgmCalibration": 0, "bgEntryType": 0,
"iob": 1.1809407, "targetBg": 110, "isf": 30,
"selectedIob": 1, "bgSourceType": 1,
},
"estimatedDateTime": "2026-05-18T10:15:14Z",
}
self.fixtureAutoPopulated = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 16,
"sequenceGroup": 0,
"sequenceNumber": 394632,
"pumpDateTime": "2026-04-30T11:57:36",
"eventProperties": {
"bg": 164, "cgmCalibration": 0, "bgEntryType": 1,
"iob": 1.8189592, "targetBg": 110, "isf": 30,
"selectedIob": 1, "bgSourceType": 1,
},
"estimatedDateTime": "2026-04-30T11:57:36Z",
}
def test_dispatches_to_correct_class(self):
ev = Event(self.fixtureManualEntry)
self.assertIsInstance(ev, eventtypes.LidBgReadingTaken)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.eventId, 16)
self.assertEqual(ev.seqNum, 456822)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-05-18T10:15:14")
def test_bg_iob_targetbg_isf_round_trip(self):
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.bg, 151)
self.assertAlmostEqual(ev.iob, 1.1809407)
self.assertEqual(ev.targetBg, 110)
self.assertEqual(ev.isf, 30)
ev2 = Event(self.fixtureAutoPopulated)
self.assertEqual(ev2.bg, 164)
self.assertAlmostEqual(ev2.iob, 1.8189592)
self.assertEqual(ev2.targetBg, 110)
self.assertEqual(ev2.isf, 30)
def test_selectediob_enum_resolves(self):
# selectedIob:1 -> SwanIobMeal
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.selectedIobRaw, 1)
self.assertEqual(ev.selectedIob,
eventtypes.LidBgReadingTaken.SelectediobEnum.SwanIobMeal)
def test_bgentrytype_enum_resolves(self):
# bgEntryType:0 -> ManualEntryByTheUserViaNumpad (0 not treated as missing)
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.bgEntryTypeRaw, 0)
self.assertEqual(
ev.bgEntryType,
eventtypes.LidBgReadingTaken.BgentrytypeEnum.ManualEntryByTheUserViaNumpad)
# bgEntryType:1 -> AutoPopulatedBgUsingDexcomEgv
ev2 = Event(self.fixtureAutoPopulated)
self.assertEqual(ev2.bgEntryTypeRaw, 1)
self.assertEqual(
ev2.bgEntryType,
eventtypes.LidBgReadingTaken.BgentrytypeEnum.AutoPopulatedBgUsingDexcomEgv)
def test_bgsourcetype_enum_resolves(self):
# bgSourceType:1 -> RemoteEntry
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.bgSourceTypeRaw, 1)
self.assertEqual(ev.bgSourceType,
eventtypes.LidBgReadingTaken.BgsourcetypeEnum.RemoteEntry)
def test_cgmcalibration_enum_resolves(self):
# cgmCalibration:0 -> No (0 not treated as missing)
ev = Event(self.fixtureManualEntry)
self.assertEqual(ev.cgmCalibrationRaw, 0)
self.assertEqual(ev.cgmCalibration,
eventtypes.LidBgReadingTaken.CgmcalibrationEnum.No)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureManualEntry, self.fixtureAutoPopulated):
ev = Event(fixture)
json.dumps(ev.todict())
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,110 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBolusActivated(unittest.TestCase):
"""55 LID_BOLUS_ACTIVATED: real captured pump-log events."""
maxDiff = None
def setUp(self):
# Real captured events (verbatim). All observed captures have
# selectedIob=1 (Swan IOB Meal); fixtures differ by bolusSize/iob.
self.fixtureMeal = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 55,
"sequenceGroup": 0,
"sequenceNumber": 394650,
"pumpDateTime": "2026-04-30T11:57:53",
"eventProperties": {
"bolusId": 1423, "selectedIob": 1, "spareA3": 0,
"iob": 1.8189592, "bolusSize": 8.33,
},
"estimatedDateTime": "2026-04-30T11:57:53Z",
}
self.fixtureZeroIob = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 55,
"sequenceGroup": 0,
"sequenceNumber": 395970,
"pumpDateTime": "2026-04-30T21:38:00",
"eventProperties": {
"bolusId": 1426, "selectedIob": 1, "spareA3": 0,
"iob": 0, "bolusSize": 10.96,
},
"estimatedDateTime": "2026-04-30T21:38:00Z",
}
self.fixtureSmall = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 55,
"sequenceGroup": 0,
"sequenceNumber": 395158,
"pumpDateTime": "2026-04-30T15:13:14",
"eventProperties": {
"bolusId": 1425, "selectedIob": 1, "spareA3": 0,
"iob": 4.116488, "bolusSize": 2,
},
"estimatedDateTime": "2026-04-30T15:13:14Z",
}
def test_dispatches_to_correct_class(self):
ev = Event(self.fixtureMeal)
self.assertIsInstance(ev, eventtypes.LidBolusActivated)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureMeal)
self.assertEqual(ev.eventId, 55)
self.assertEqual(ev.seqNum, 394650)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureMeal)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T11:57:53")
def test_bolus_fields_round_trip(self):
ev = Event(self.fixtureMeal)
self.assertEqual(ev.bolusId, 1423)
self.assertAlmostEqual(ev.iob, 1.8189592)
self.assertAlmostEqual(ev.bolusSize, 8.33)
def test_zero_iob_is_preserved(self):
# iob:0 must not be dropped as missing.
ev = Event(self.fixtureZeroIob)
self.assertEqual(ev.bolusId, 1426)
self.assertEqual(ev.iob, 0)
self.assertAlmostEqual(ev.bolusSize, 10.96)
def test_small_bolus_round_trips(self):
ev = Event(self.fixtureSmall)
self.assertEqual(ev.bolusId, 1425)
self.assertAlmostEqual(ev.iob, 4.116488)
self.assertEqual(ev.bolusSize, 2)
def test_selectediob_resolves_to_enum(self):
# selectedIob:1 -> Swan IOB Meal
ev = Event(self.fixtureMeal)
self.assertEqual(ev.selectedIobRaw, 1)
self.assertEqual(ev.selectedIob,
eventtypes.LidBolusActivated.SelectediobEnum.SwanIobMeal)
def test_spareA3_is_ignored(self):
ev = Event(self.fixtureMeal)
self.assertFalse(hasattr(ev, "spareA3"))
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureMeal, self.fixtureZeroIob, self.fixtureSmall):
ev = Event(fixture)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 55)
self.assertEqual(d["name"], "LID_BOLUS_ACTIVATED")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,93 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBolusCompleted(unittest.TestCase):
maxDiff = None
def setUp(self):
# Real captured LID_BOLUS_COMPLETED (eventCode 20) events, verbatim.
# completionStatus 3 -> Completed, insulinDelivered == insulinRequested.
self.fixtureCompleted = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 20,
"sequenceGroup": 0,
"sequenceNumber": 394675,
"pumpDateTime": "2026-04-30T12:01:53",
"eventProperties": {
"completionStatus": 3, "bolusId": 1423, "iob": 10.088287,
"insulinDelivered": 8.33, "insulinRequested": 8.33,
},
"estimatedDateTime": "2026-04-30T12:01:53Z",
}
# completionStatus 0 -> UserAborted, an interrupted bolus where
# insulinDelivered (0.04657) is far below insulinRequested (0.5).
self.fixtureInterrupted = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 20,
"sequenceGroup": 0,
"sequenceNumber": 456849,
"pumpDateTime": "2026-05-18T10:15:39",
"eventProperties": {
"completionStatus": 0, "bolusId": 1644, "iob": 1.2275107,
"insulinDelivered": 0.04657, "insulinRequested": 0.5,
},
"estimatedDateTime": "2026-05-18T10:15:39Z",
}
def test_dispatches_to_lidboluscompleted(self):
self.assertIsInstance(Event(self.fixtureCompleted), eventtypes.LidBolusCompleted)
self.assertIsInstance(Event(self.fixtureInterrupted), eventtypes.LidBolusCompleted)
self.assertNotIsInstance(Event(self.fixtureCompleted), RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureCompleted)
self.assertEqual(ev.eventId, 20)
self.assertEqual(ev.seqNum, 394675)
# eventTimestamp keeps pumpDateTime's wall-clock.
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'), "2026-04-30T12:01:53")
def test_completed_fields_round_trip(self):
ev = Event(self.fixtureCompleted)
self.assertEqual(ev.bolusId, 1423)
self.assertAlmostEqual(ev.insulinDelivered, 8.33)
self.assertAlmostEqual(ev.insulinRequested, 8.33)
self.assertAlmostEqual(ev.iob, 10.088287)
def test_interrupted_fields_round_trip(self):
ev = Event(self.fixtureInterrupted)
self.assertEqual(ev.bolusId, 1644)
self.assertAlmostEqual(ev.insulinDelivered, 0.04657)
self.assertAlmostEqual(ev.insulinRequested, 0.5)
self.assertAlmostEqual(ev.iob, 1.2275107)
# Interrupted: less insulin delivered than requested.
self.assertLess(ev.insulinDelivered, ev.insulinRequested)
def test_completionstatus_resolves_to_enum(self):
completed = Event(self.fixtureCompleted)
self.assertEqual(completed.completionStatusRaw, 3)
self.assertEqual(completed.completionStatus,
eventtypes.LidBolusCompleted.CompletionstatusEnum.Completed)
interrupted = Event(self.fixtureInterrupted)
self.assertEqual(interrupted.completionStatusRaw, 0)
self.assertEqual(interrupted.completionStatus,
eventtypes.LidBolusCompleted.CompletionstatusEnum.UserAborted)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureCompleted, self.fixtureInterrupted):
ev = Event(fixture)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 20)
self.assertEqual(d["name"], "LID_BOLUS_COMPLETED")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,133 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBolusDelivery(unittest.TestCase):
"""280: LID_BOLUS_DELIVERY. All fixtures are real captured pump-log events."""
maxDiff = None
def setUp(self):
# Manual pump-button bolus, started: bolusType [0] (Now),
# bolusSource 0 (PumpButton), bolusDeliveryStatus 1 (BolusStarted).
self.fixturePumpButtonStarted = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 280,
"sequenceGroup": 0,
"sequenceNumber": 395159,
"pumpDateTime": "2026-04-30T15:13:14",
"eventProperties": {
"bolusId": 1425, "bolusDeliveryStatus": 1, "bolusType": [0],
"bolusSource": 0, "remoteId": 145, "requestedNow": 2000,
"requestedLater": 0, "correction": 0,
"extendedDurationRequested": 0, "deliveredTotal": 0,
},
"estimatedDateTime": "2026-04-30T15:13:14Z",
}
# Carb+correction BLE bolus, started: bolusType [0,3,4]
# (Now|Correction|Carb), bolusSource 8 (Ble), status 1 (BolusStarted).
self.fixtureCarbCorrectionStarted = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 280,
"sequenceGroup": 0,
"sequenceNumber": 395971,
"pumpDateTime": "2026-04-30T21:38:00",
"eventProperties": {
"bolusId": 1426, "bolusDeliveryStatus": 1, "bolusType": [0, 3, 4],
"bolusSource": 8, "remoteId": 146, "requestedNow": 10960,
"requestedLater": 0, "correction": 130,
"extendedDurationRequested": 0, "deliveredTotal": 0,
},
"estimatedDateTime": "2026-04-30T21:38:00Z",
}
# Completion of the same bolus: status 0 (BolusCompleted),
# deliveredTotal now populated (10960).
self.fixtureCarbCorrectionCompleted = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 280,
"sequenceGroup": 0,
"sequenceNumber": 395991,
"pumpDateTime": "2026-04-30T21:40:03",
"eventProperties": {
"bolusId": 1426, "bolusDeliveryStatus": 0, "bolusType": [0, 3, 4],
"bolusSource": 8, "remoteId": 146, "requestedNow": 10960,
"requestedLater": 0, "correction": 130,
"extendedDurationRequested": 0, "deliveredTotal": 10960,
},
"estimatedDateTime": "2026-04-30T21:40:03Z",
}
def test_dispatches_to_correct_class(self):
self.assertIsInstance(Event(self.fixturePumpButtonStarted),
eventtypes.LidBolusDelivery)
self.assertNotIsInstance(Event(self.fixturePumpButtonStarted), RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureCarbCorrectionStarted)
self.assertEqual(ev.eventId, 280)
self.assertEqual(ev.seqNum, 395971)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T21:38:00")
def test_plain_fields_round_trip(self):
ev = Event(self.fixtureCarbCorrectionStarted)
self.assertEqual(ev.bolusId, 1426)
self.assertEqual(ev.requestedNow, 10960)
self.assertEqual(ev.deliveredTotal, 0)
self.assertEqual(ev.correction, 130)
self.assertEqual(ev.remoteId, 146)
self.assertEqual(ev.requestedLater, 0)
self.assertEqual(ev.extendedDurationRequested, 0)
def test_completion_carries_delivered_total(self):
ev = Event(self.fixtureCarbCorrectionCompleted)
self.assertEqual(ev.bolusId, 1426)
self.assertEqual(ev.deliveredTotal, 10960)
def test_bolustype_single_bit_folds_and_resolves(self):
# bolusType [0] -> 1<<0 == 1 -> Now
ev = Event(self.fixturePumpButtonStarted)
self.assertEqual(ev.bolusTypeRaw, 1)
self.assertEqual(ev.bolusType, eventtypes.LidBolusDelivery.BolustypeBitmask.Now)
def test_bolustype_multi_bit_folds_and_resolves(self):
# bolusType [0,3,4] -> 1<<0 | 1<<3 | 1<<4 == 25 -> Now|Correction|Carb
ev = Event(self.fixtureCarbCorrectionStarted)
self.assertEqual(ev.bolusTypeRaw, sum(1 << i for i in [0, 3, 4]))
self.assertEqual(ev.bolusTypeRaw, 25)
bt = eventtypes.LidBolusDelivery.BolustypeBitmask
self.assertEqual(ev.bolusType, bt.Now | bt.Correction | bt.Carb)
def test_bolussource_resolves(self):
self.assertEqual(
Event(self.fixturePumpButtonStarted).bolusSource,
eventtypes.LidBolusDelivery.BolussourceEnum.PumpButton)
self.assertEqual(
Event(self.fixtureCarbCorrectionStarted).bolusSource,
eventtypes.LidBolusDelivery.BolussourceEnum.Ble)
def test_bolusdeliverystatus_resolves(self):
self.assertEqual(
Event(self.fixtureCarbCorrectionStarted).bolusDeliveryStatus,
eventtypes.LidBolusDelivery.BolusdeliverystatusEnum.BolusStarted)
self.assertEqual(
Event(self.fixtureCarbCorrectionCompleted).bolusDeliveryStatus,
eventtypes.LidBolusDelivery.BolusdeliverystatusEnum.BolusCompleted)
def test_todict_is_json_serializable(self):
for fixture in (self.fixturePumpButtonStarted,
self.fixtureCarbCorrectionStarted,
self.fixtureCarbCorrectionCompleted):
ev = Event(fixture)
json.dumps(ev.todict()) # must not raise
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBolusRequestedMsg1(unittest.TestCase):
"""64: LID_BOLUS_REQUESTED_MSG1. Fixtures are real captured pump-log events
copied verbatim from a captured account response."""
maxDiff = None
def setUp(self):
# bolusType 3 (Remote), correctionBolusIncluded 0 (No), carbs present.
self.fixtureRemoteWithCarbs = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 64, "sequenceGroup": 0, "sequenceNumber": 394641,
"pumpDateTime": "2026-04-30T11:57:38",
"eventProperties": {
"bolusId": 1423, "bolusType": 3, "correctionBolusIncluded": 0,
"carbAmount": 50, "bg": 164, "iob": 1.82, "carbRatio": 0,
},
"estimatedDateTime": "2026-04-30T11:57:38Z",
}
# bolusType 3 (Remote), correctionBolusIncluded 1 (Yes), iob 0.
self.fixtureRemoteWithCorrection = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 64, "sequenceGroup": 0, "sequenceNumber": 395959,
"pumpDateTime": "2026-04-30T21:37:45",
"eventProperties": {
"bolusId": 1426, "bolusType": 3, "correctionBolusIncluded": 1,
"carbAmount": 65, "bg": 114, "iob": 0, "carbRatio": 0,
},
"estimatedDateTime": "2026-04-30T21:37:45Z",
}
# bolusType 0 (Insulin), no carbs, bg 0, fractional iob.
self.fixtureInsulinNoCarbs = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 64, "sequenceGroup": 0, "sequenceNumber": 395146,
"pumpDateTime": "2026-04-30T15:12:59",
"eventProperties": {
"bolusId": 1425, "bolusType": 0, "correctionBolusIncluded": 0,
"carbAmount": 0, "bg": 0, "iob": 4.116488, "carbRatio": 0,
},
"estimatedDateTime": "2026-04-30T15:12:59Z",
}
def test_dispatches_to_correct_class(self):
ev = Event(self.fixtureRemoteWithCarbs)
self.assertIsInstance(ev, eventtypes.LidBolusRequestedMsg1)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureRemoteWithCarbs)
self.assertEqual(ev.eventId, 64)
self.assertEqual(ev.seqNum, 394641)
# eventTimestamp keeps pumpDateTime's wall-clock.
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T11:57:38")
def test_plain_fields_round_trip(self):
ev = Event(self.fixtureRemoteWithCarbs)
self.assertEqual(ev.bolusId, 1423)
self.assertEqual(ev.carbAmount, 50)
self.assertEqual(ev.bg, 164)
self.assertEqual(ev.iob, 1.82)
def test_fractional_iob_and_zero_bg(self):
ev = Event(self.fixtureInsulinNoCarbs)
self.assertEqual(ev.bolusId, 1425)
self.assertEqual(ev.carbAmount, 0)
self.assertEqual(ev.bg, 0)
self.assertAlmostEqual(ev.iob, 4.116488)
def test_bolustype_remote(self):
ev = Event(self.fixtureRemoteWithCarbs)
self.assertEqual(ev.bolusTypeRaw, 3)
self.assertEqual(ev.bolusType,
eventtypes.LidBolusRequestedMsg1.BolustypeEnum.Remote)
def test_bolustype_insulin(self):
# bolusType 0 must resolve (0 not treated as missing).
ev = Event(self.fixtureInsulinNoCarbs)
self.assertEqual(ev.bolusTypeRaw, 0)
self.assertEqual(ev.bolusType,
eventtypes.LidBolusRequestedMsg1.BolustypeEnum.Insulin)
def test_correctionbolusincluded_no(self):
ev = Event(self.fixtureRemoteWithCarbs)
self.assertEqual(ev.correctionBolusIncludedRaw, 0)
self.assertEqual(
ev.correctionBolusIncluded,
eventtypes.LidBolusRequestedMsg1.CorrectionbolusincludedEnum.No)
def test_correctionbolusincluded_yes(self):
ev = Event(self.fixtureRemoteWithCorrection)
self.assertEqual(ev.correctionBolusIncludedRaw, 1)
self.assertEqual(
ev.correctionBolusIncluded,
eventtypes.LidBolusRequestedMsg1.CorrectionbolusincludedEnum.Yes)
def test_carbratio_scales(self):
# carbratio is carbratioRaw * 0.001; real captures carry 0.
ev = Event(self.fixtureRemoteWithCorrection)
self.assertEqual(ev.carbRatioRaw, 0)
self.assertAlmostEqual(ev.carbRatio, 0.0)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureRemoteWithCarbs,
self.fixtureRemoteWithCorrection,
self.fixtureInsulinNoCarbs):
ev = Event(fixture)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 64)
self.assertEqual(d["name"], "LID_BOLUS_REQUESTED_MSG1")
self.assertEqual(d["bolusId"],
fixture["eventProperties"]["bolusId"])
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBolusRequestedMsg2(unittest.TestCase):
"""65: LID_BOLUS_REQUESTED_MSG2 — real captured pump-log events."""
maxDiff = None
def setUp(self):
# BLE standard bolus, user did NOT override the bolus size.
self.fixtureBleStandard = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 65,
"sequenceGroup": 0,
"sequenceNumber": 394642,
"pumpDateTime": "2026-04-30T11:57:38",
"eventProperties": {
"bolusId": 1423, "options": 4, "standardPercent": 100,
"duration": 0, "spareB6": 0, "isf": 0, "targetBg": 0,
"userOverride": 0, "declinedCorrection": 0, "selectedIob": 1,
},
"estimatedDateTime": "2026-04-30T11:57:38Z",
}
# BLE standard bolus, user DID override the bolus size.
self.fixtureUserOverride = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 65,
"sequenceGroup": 0,
"sequenceNumber": 394840,
"pumpDateTime": "2026-04-30T13:13:28",
"eventProperties": {
"bolusId": 1424, "options": 4, "standardPercent": 100,
"duration": 0, "spareB6": 0, "isf": 0, "targetBg": 0,
"userOverride": 1, "declinedCorrection": 0, "selectedIob": 1,
},
"estimatedDateTime": "2026-04-30T13:13:28Z",
}
# Quick bolus (options=2).
self.fixtureQuick = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 65,
"sequenceGroup": 0,
"sequenceNumber": 395147,
"pumpDateTime": "2026-04-30T15:12:59",
"eventProperties": {
"bolusId": 1425, "options": 2, "standardPercent": 100,
"duration": 0, "spareB6": 0, "isf": 0, "targetBg": 0,
"userOverride": 0, "declinedCorrection": 0, "selectedIob": 1,
},
"estimatedDateTime": "2026-04-30T15:12:59Z",
}
def test_dispatches_to_correct_class(self):
ev = Event(self.fixtureBleStandard)
self.assertIsInstance(ev, eventtypes.LidBolusRequestedMsg2)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureBleStandard)
self.assertEqual(ev.eventId, 65)
self.assertEqual(ev.seqNum, 394642)
self.assertEqual(
ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'), "2026-04-30T11:57:38")
def test_plain_fields_round_trip(self):
ev = Event(self.fixtureBleStandard)
self.assertEqual(ev.bolusId, 1423)
self.assertEqual(ev.standardPercent, 100)
self.assertEqual(ev.duration, 0)
self.assertEqual(ev.isf, 0)
self.assertEqual(ev.targetBg, 0)
def test_options_enum_ble_standard(self):
ev = Event(self.fixtureBleStandard)
self.assertEqual(ev.optionsRaw, 4)
self.assertEqual(ev.options,
eventtypes.LidBolusRequestedMsg2.OptionsEnum.BleStandardBolus)
def test_options_enum_quick(self):
ev = Event(self.fixtureQuick)
self.assertEqual(ev.optionsRaw, 2)
self.assertEqual(ev.options,
eventtypes.LidBolusRequestedMsg2.OptionsEnum.QuickBolus)
def test_selectediob_enum(self):
ev = Event(self.fixtureBleStandard)
self.assertEqual(ev.selectedIobRaw, 1)
self.assertEqual(ev.selectedIob,
eventtypes.LidBolusRequestedMsg2.SelectediobEnum.SwanIobMeal)
def test_useroverride_enum_no(self):
ev = Event(self.fixtureBleStandard)
self.assertEqual(ev.userOverrideRaw, 0)
self.assertEqual(ev.userOverride,
eventtypes.LidBolusRequestedMsg2.UseroverrideEnum.No)
def test_useroverride_enum_yes(self):
ev = Event(self.fixtureUserOverride)
self.assertEqual(ev.userOverrideRaw, 1)
self.assertEqual(ev.userOverride,
eventtypes.LidBolusRequestedMsg2.UseroverrideEnum.Yes)
def test_declinedcorrection_enum(self):
ev = Event(self.fixtureBleStandard)
self.assertEqual(ev.declinedCorrectionRaw, 0)
self.assertEqual(ev.declinedCorrection,
eventtypes.LidBolusRequestedMsg2.DeclinedcorrectionEnum.No)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureBleStandard, self.fixtureUserOverride,
self.fixtureQuick):
ev = Event(fixture)
json.dumps(ev.todict()) # must not raise
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,127 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidBolusRequestedMsg3(unittest.TestCase):
"""66: LID_BOLUS_REQUESTED_MSG3. Fixtures are real captured pump-log
events copied verbatim (spareA2 is present but ignored by the parser)."""
maxDiff = None
def setUp(self):
# food-only bolus; total carries float rounding (8.330001).
self.fixtureFoodOnly = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 66,
"sequenceGroup": 0,
"sequenceNumber": 394643,
"pumpDateTime": "2026-04-30T11:57:38",
"eventProperties": {
"bolusId": 1423, "spareA2": 0, "foodBolusSize": 8.33,
"correctionBolusSize": 0, "totalBolusSize": 8.330001,
},
"estimatedDateTime": "2026-04-30T11:57:38Z",
}
# food + correction; both components non-zero.
self.fixtureFoodAndCorrection = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 66,
"sequenceGroup": 0,
"sequenceNumber": 395961,
"pumpDateTime": "2026-04-30T21:37:45",
"eventProperties": {
"bolusId": 1426, "spareA2": 0, "foodBolusSize": 10.83,
"correctionBolusSize": 0.13, "totalBolusSize": 10.96,
},
"estimatedDateTime": "2026-04-30T21:37:45Z",
}
# correction-only food component; total exceeds correction.
self.fixtureCorrectionOnly = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 66,
"sequenceGroup": 0,
"sequenceNumber": 398360,
"pumpDateTime": "2026-05-01T16:02:12",
"eventProperties": {
"bolusId": 1430, "spareA2": 0, "foodBolusSize": 0,
"correctionBolusSize": 1.47, "totalBolusSize": 3,
},
"estimatedDateTime": "2026-05-01T16:02:12Z",
}
# both breakdown components zero but a non-zero total.
self.fixtureTotalOnly = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 66,
"sequenceGroup": 0,
"sequenceNumber": 394841,
"pumpDateTime": "2026-04-30T13:13:28",
"eventProperties": {
"bolusId": 1424, "spareA2": 0, "foodBolusSize": 0,
"correctionBolusSize": 0, "totalBolusSize": 4,
},
"estimatedDateTime": "2026-04-30T13:13:28Z",
}
def test_dispatches_to_correct_class(self):
ev = Event(self.fixtureFoodOnly)
self.assertIsInstance(ev, eventtypes.LidBolusRequestedMsg3)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureFoodOnly)
self.assertEqual(ev.eventId, 66)
self.assertEqual(ev.seqNum, 394643)
def test_timestamp_preserves_wall_clock(self):
ev = Event(self.fixtureFoodOnly)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T11:57:38")
def test_food_only(self):
ev = Event(self.fixtureFoodOnly)
self.assertEqual(ev.bolusId, 1423)
self.assertAlmostEqual(ev.foodBolusSize, 8.33)
self.assertAlmostEqual(ev.correctionBolusSize, 0)
self.assertAlmostEqual(ev.totalBolusSize, 8.330001)
def test_food_and_correction(self):
ev = Event(self.fixtureFoodAndCorrection)
self.assertEqual(ev.bolusId, 1426)
self.assertAlmostEqual(ev.foodBolusSize, 10.83)
self.assertAlmostEqual(ev.correctionBolusSize, 0.13)
self.assertAlmostEqual(ev.totalBolusSize, 10.96)
def test_correction_only(self):
ev = Event(self.fixtureCorrectionOnly)
self.assertEqual(ev.bolusId, 1430)
self.assertAlmostEqual(ev.foodBolusSize, 0)
self.assertAlmostEqual(ev.correctionBolusSize, 1.47)
self.assertAlmostEqual(ev.totalBolusSize, 3)
def test_total_only(self):
ev = Event(self.fixtureTotalOnly)
self.assertEqual(ev.bolusId, 1424)
self.assertAlmostEqual(ev.foodBolusSize, 0)
self.assertAlmostEqual(ev.correctionBolusSize, 0)
self.assertAlmostEqual(ev.totalBolusSize, 4)
def test_todict_json_serializable(self):
for fixture in (self.fixtureFoodOnly, self.fixtureFoodAndCorrection,
self.fixtureCorrectionOnly, self.fixtureTotalOnly):
ev = Event(fixture)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 66)
self.assertEqual(d["name"], "LID_BOLUS_REQUESTED_MSG3")
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,67 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidCannulaFilled(unittest.TestCase):
"""61: LID_CANNULA_FILLED. Fixture is a real captured pump-log event.
Only one distinct eventProperties shape exists in the captures, so a
single fixture covers the observed behavior. The extra infusionSetType
key is not in the schema and must be ignored by the parser."""
maxDiff = None
def setUp(self):
self.fixtureCompleted = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 61,
"sequenceGroup": 0,
"sequenceNumber": 412912,
"pumpDateTime": "2026-05-05T19:16:40",
"eventProperties": {
"primeSize": 0.3, "completionStatus": 3, "infusionSetType": 0,
},
"estimatedDateTime": "2026-05-05T19:16:40Z",
}
def test_dispatches_to_lidcannulafilled(self):
ev = Event(self.fixtureCompleted)
self.assertIsInstance(ev, eventtypes.LidCannulaFilled)
self.assertNotIsInstance(ev, RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureCompleted)
self.assertEqual(ev.eventId, 61)
self.assertEqual(ev.seqNum, 412912)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-05-05T19:16:40")
def test_primesize_round_trips(self):
ev = Event(self.fixtureCompleted)
self.assertEqual(ev.primeSize, 0.3)
def test_completionstatus_resolves_to_enum(self):
# completionStatus:3 -> Completed
ev = Event(self.fixtureCompleted)
self.assertEqual(ev.completionStatusRaw, 3)
self.assertEqual(ev.completionStatus,
eventtypes.LidCannulaFilled.CompletionstatusEnum.Completed)
def test_unknown_infusionsettype_key_is_ignored(self):
# infusionSetType is not in the schema; the parser must not raise and
# must not expose an attribute for it.
ev = Event(self.fixtureCompleted) # must not raise
self.assertFalse(hasattr(ev, "infusionSetType"))
self.assertFalse(hasattr(ev, "infusionsettype"))
def test_todict_is_json_serializable(self):
ev = Event(self.fixtureCompleted)
json.dumps(ev.todict()) # must not raise
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
from tconnectsync.eventparser.raw_event import RawEvent
class TestLidCartridgeFilled(unittest.TestCase):
"""33: LID_CARTRIDGE_FILLED. All fixtures are real captured pump-log
events (verbatim). insulinVolume varies; v2Volume is always 0."""
maxDiff = None
def setUp(self):
# Smallest observed insulinVolume.
self.fixtureMin = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 33,
"sequenceGroup": 0,
"sequenceNumber": 418402,
"pumpDateTime": "2026-05-07T10:35:59",
"eventProperties": {"insulinVolume": 60, "v2Volume": 0},
"estimatedDateTime": "2026-05-07T10:35:59Z",
}
# A mid-range fill.
self.fixtureMid = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 33,
"sequenceGroup": 0,
"sequenceNumber": 394427,
"pumpDateTime": "2026-04-30T10:16:09",
"eventProperties": {"insulinVolume": 105, "v2Volume": 0},
"estimatedDateTime": "2026-04-30T10:16:09Z",
}
# Largest observed insulinVolume.
self.fixtureMax = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 33,
"sequenceGroup": 0,
"sequenceNumber": 463083,
"pumpDateTime": "2026-05-20T02:15:04",
"eventProperties": {"insulinVolume": 190, "v2Volume": 0},
"estimatedDateTime": "2026-05-20T02:15:04Z",
}
def test_dispatches_to_lidcartridgefilled(self):
ev = Event(self.fixtureMid)
self.assertIsInstance(ev, eventtypes.LidCartridgeFilled)
self.assertIsNot(type(ev), RawEvent)
def test_envelope_fields(self):
ev = Event(self.fixtureMid)
self.assertEqual(ev.eventId, 33)
self.assertEqual(ev.seqNum, 394427)
self.assertEqual(
ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'),
"2026-04-30T10:16:09")
def test_insulinvolume_round_trips(self):
self.assertEqual(Event(self.fixtureMin).insulinVolume, 60)
self.assertEqual(Event(self.fixtureMid).insulinVolume, 105)
self.assertEqual(Event(self.fixtureMax).insulinVolume, 190)
def test_v2volume_round_trips(self):
for fixture in (self.fixtureMin, self.fixtureMid, self.fixtureMax):
self.assertEqual(Event(fixture).v2Volume, 0)
def test_todict_is_json_serializable(self):
for fixture in (self.fixtureMin, self.fixtureMid, self.fixtureMax):
d = Event(fixture).todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 33)
self.assertEqual(d["name"], "LID_CARTRIDGE_FILLED")
def test_todict_reflects_real_values(self):
d = Event(self.fixtureMax).todict()
self.assertEqual(d["seqNum"], 463083)
self.assertEqual(d["insulinVolume"], 190)
self.assertEqual(d["v2Volume"], 0)
if __name__ == "__main__":
unittest.main()
@@ -0,0 +1,95 @@
#!/usr/bin/env python3
import json
import unittest
from tconnectsync.eventparser.generic import Event
from tconnectsync.eventparser import events as eventtypes
# Real captured LID_CGM_ALERT_ACK_DEX (371) events, copied verbatim.
# dalertId/sensorType/ackSource are dictionary/enum fields. "spareA2" is
# ignored by the parser (kept here but never asserted on).
class TestLidCgmAlertAckDex(unittest.TestCase):
maxDiff = None
def setUp(self):
# dalertId:2 (CGM High), sensorType:3 (G7), ackSource:0 (by User)
self.fixtureCgmHigh = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 371,
"sequenceGroup": 0,
"sequenceNumber": 416807,
"pumpDateTime": "2026-05-06T23:04:58",
"eventProperties": {"dalertId": 2, "sensorType": 3, "spareA2": 0, "ackSource": 0},
"estimatedDateTime": "2026-05-06T23:04:58Z",
}
# dalertId:12 (CGM Sensor Expiring Soon), sensorType:3 (G7), ackSource:0 (by User)
self.fixtureSensorExpiringSoon = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 371,
"sequenceGroup": 0,
"sequenceNumber": 446797,
"pumpDateTime": "2026-05-15T16:43:28",
"eventProperties": {"dalertId": 12, "sensorType": 3, "spareA2": 0, "ackSource": 0},
"estimatedDateTime": "2026-05-15T16:43:28Z",
}
# dalertId:32 (not in enum -> None), sensorType:3 (G7), ackSource:1 (by Software)
self.fixtureAckBySoftware = {
"deviceAssignmentId": "4ff6bebc-d4d6-4423-b123-eecfcf5a4238",
"eventCode": 371,
"sequenceGroup": 0,
"sequenceNumber": 449784,
"pumpDateTime": "2026-05-16T12:34:28",
"eventProperties": {"dalertId": 32, "sensorType": 3, "spareA2": 0, "ackSource": 1},
"estimatedDateTime": "2026-05-16T12:34:28Z",
}
def test_dispatches_to_lidcgmalertackdex(self):
for fx in (self.fixtureCgmHigh, self.fixtureSensorExpiringSoon, self.fixtureAckBySoftware):
self.assertIsInstance(Event(fx), eventtypes.LidCgmAlertAckDex)
def test_envelope_fields(self):
ev = Event(self.fixtureCgmHigh)
self.assertEqual(ev.eventId, 371)
self.assertEqual(ev.seqNum, 416807)
self.assertEqual(ev.eventTimestamp.format('YYYY-MM-DDTHH:mm:ss'), "2026-05-06T23:04:58")
def test_dalertid_resolves_cgm_high(self):
ev = Event(self.fixtureCgmHigh)
self.assertEqual(ev.dalertIdRaw, 2)
self.assertEqual(ev.dalertId, eventtypes.LidCgmAlertAckDex.DalertidEnum.CgmHigh)
def test_dalertid_resolves_sensor_expiring_soon(self):
ev = Event(self.fixtureSensorExpiringSoon)
self.assertEqual(ev.dalertIdRaw, 12)
self.assertEqual(ev.dalertId, eventtypes.LidCgmAlertAckDex.DalertidEnum.CgmSensorExpiringSoon)
def test_sensortype_resolves_g7(self):
for fx in (self.fixtureCgmHigh, self.fixtureSensorExpiringSoon, self.fixtureAckBySoftware):
ev = Event(fx)
self.assertEqual(ev.sensorTypeRaw, 3)
self.assertEqual(ev.sensorType, eventtypes.LidCgmAlertAckDex.SensortypeEnum.CgmTypeDexcomG7)
def test_acksource_resolves_by_user(self):
ev = Event(self.fixtureCgmHigh)
self.assertEqual(ev.ackSourceRaw, 0)
self.assertEqual(ev.ackSource, eventtypes.LidCgmAlertAckDex.AcksourceEnum.AlertAcknowledgedByUser)
def test_acksource_resolves_by_software(self):
ev = Event(self.fixtureAckBySoftware)
self.assertEqual(ev.ackSourceRaw, 1)
self.assertEqual(ev.ackSource, eventtypes.LidCgmAlertAckDex.AcksourceEnum.AlertAcknowledgedBySoftware)
def test_todict_is_json_serializable(self):
for fx in (self.fixtureCgmHigh, self.fixtureSensorExpiringSoon, self.fixtureAckBySoftware):
ev = Event(fx)
d = ev.todict()
json.dumps(d) # must not raise
self.assertEqual(d["id"], 371)
self.assertEqual(d["name"], "LID_CGM_ALERT_ACK_DEX")
if __name__ == "__main__":
unittest.main()

Some files were not shown because too many files have changed in this diff Show More