### Install cgmsim-lib Package Source: https://github.com/lsandini/cgmsim-lib/blob/main/README.md Install the cgmsim-lib package using npm. This command is used to add the library to your project's dependencies. ```bash npm install @lsandini/cgmsim-lib ``` -------------------------------- ### Run Glucose Simulation with simulator Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Execute the main blood glucose simulation. Pass the required `MainParams` object to this function to get the simulation results. ```typescript const result = simulator(params); ``` -------------------------------- ### Run CGMSIM Blood Glucose Simulator Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Use the `simulator` function to run the proprietary CGMSIM model for a single 5-minute step. Provide a comprehensive patient profile, historical glucose data, treatments, pump profiles, and optional activity data. The result includes the new glucose value and detailed activity breakdowns. ```typescript import { simulator } from '@lsandini/cgmsim-lib'; import type { MainParams, SimulationResult } from '@lsandini/cgmsim-lib'; const params: MainParams = { patient: { WEIGHT: 70, AGE: 35, GENDER: 'Male', TZ: 'Europe/Paris', ISF: 50, // mg/dl per unit of insulin CR: 10, // grams of carbs per unit TP: 75, // time to peak insulin activity (minutes) DIA: 6, // duration of insulin action (hours) CARBS_ABS_TIME: 360, // carb absorption time (minutes) }, entries: [ { mills: Date.now() - 5 * 60 * 1000, sgv: 120 }, { mills: Date.now() - 10 * 60 * 1000, sgv: 115 }, { mills: Date.now() - 15 * 60 * 1000, sgv: 110 }, ], treatments: [ { eventType: 'Meal Bolus', insulin: 4, carbs: 40, created_at: new Date(Date.now() - 30 * 60 * 1000).toISOString(), }, ], profiles: [ { startDate: '2024-01-01', defaultProfile: 'Default', store: { Default: { basal: 0.8 } }, }, ], pumpEnabled: false, activities: [ { heartRate: 72, steps: 3000, created_at: new Date().toISOString() }, ], user: { nsUrl: 'https://nightscout.example.com' }, }; const result: SimulationResult = simulator(params); console.log('New SGV:', result.sgv); // Output: // { // sgv: 127, // deltaMinutes: 5, // carbsActivity: 0.00312, // cortisoneActivity: 0, // basalActivity: 0.00041, // bolusActivity: 0.00218, // liverActivity: 0.00089, // activityFactor: 0.98, // alcoholActivity: 0, // isf: { dynamic: 50, constant: 50 }, // cob: 28.4, // bolusIOB: 2.1, // pumpBasalIOB: 0, // profileBasalIOB: 0, // basalIOB: 0 // } ``` -------------------------------- ### simulatorUVA Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Simulates blood glucose levels in response to various parameters and inputs. ```APIDOC ## simulatorUVA ### Description Simulates blood glucose levels in response to various parameters and inputs. ### Parameters #### Path Parameters - **params** (object) - Required - Parameters for the UVA simulation. ``` -------------------------------- ### simulatorUVA Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Runs the UVA/Padova Type 1 Diabetes Metabolic Simulator. It takes patient state and baseline parameters to simulate glucose levels and returns the simulation results. ```APIDOC ## `simulatorUVA` — UVA/Padova T1DMS Simulator Runs the physiologically validated UVA/Padova Type 1 Diabetes Metabolic Simulator model. Requires an initial `PatientState` (internal compartment values) and a `defaultPatient` baseline. Returns a `UvaSimulationResult` including the new glucose value and the updated patient state for use in the next simulation step. ```typescript import { simulatorUVA } from '@lsandini/cgmsim-lib'; import type { MainParamsUVA, UvaSimulationResult } from '@lsandini/cgmsim-lib'; // defaultPatient holds the steady-state compartment values for the UVA model const defaultPatient = { /* PatientState from lt1/types */ }; const lastState = null; // null on first run; pass previous result.state thereafter const params: MainParamsUVA = { patient: { WEIGHT: 70, AGE: 35, GENDER: 'Male', TZ: 'Europe/Paris', ISF: 50, CR: 10, TP: 75, DIA: 6, CARBS_ABS_TIME: 360, }, entries: [ { mills: Date.now() - 5 * 60 * 1000, sgv: 118 }, ], treatments: [ { eventType: 'Meal Bolus', insulin: 3, carbs: 30, created_at: new Date(Date.now() - 10 * 60 * 1000).toISOString(), }, ], profiles: [ { startDate: '2024-01-01', defaultProfile: 'Default', store: { Default: { basal: 0.8 } }, }, ], pumpEnabled: true, lastState, defaultPatient, user: { nsUrl: 'https://nightscout.example.com' }, }; const result: UvaSimulationResult = simulatorUVA(params); console.log('UVA SGV:', result.sgv); console.log('Bolus IOB:', result.bolusIOB); // Output: // { // sgv: 122, // clamped to [40, 400] mg/dl // state: { Gp: 122, Gt: 119, I_: ..., ... }, // full compartment state // cob: 21.3, // bolusIOB: 1.8, // pumpBasalIOB: 0.4, // profileBasalIOB: 0.3, // basalIOB: 0 // } // On next call, pass result.state as lastState to continue the simulation ``` ``` -------------------------------- ### simulator Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Runs the proprietary CGMSIM simulation model for one 5-minute step. It accepts a comprehensive set of patient parameters, historical glucose entries, insulin/carb treatments, pump profiles, and optional physical activity data. The function returns a `SimulationResult` object containing the new glucose value and detailed breakdowns of the simulation's activity. ```APIDOC ## simulator ### Description Runs the proprietary CGMSIM simulation model for one 5-minute step. Accepts a full patient profile, historical glucose entries, insulin/carb treatments, pump profiles, and optional physical activity data. Returns a `SimulationResult` with the new glucose value plus detailed activity breakdowns. ### Method Signature ```typescript simulator(params: MainParams): SimulationResult ``` ### Parameters - **params** (`MainParams`): An object containing all necessary parameters for the simulation. - **patient** (`object`): Core patient physiological parameters. - **WEIGHT** (`number`): Patient's weight. - **AGE** (`number`): Patient's age. - **GENDER** (`string`): Patient's gender. - **TZ** (`string`): Patient's time zone. - **ISF** (`number`): Insulin Sensitivity Factor (mg/dl per unit of insulin). - **CR** (`number`): Carbohydrate Ratio (grams of carbs per unit of insulin). - **TP** (`number`): Time to peak insulin activity (minutes). - **DIA** (`number`): Duration of insulin action (hours). - **CARBS_ABS_TIME** (`number`): Carbohydrate absorption time (minutes). - **entries** (`Array`): Historical glucose entries. - **mills** (`number`): Timestamp of the glucose entry. - **sgv** (`number`): The glucose value. - **treatments** (`Array`): Insulin and carb treatments administered. - **eventType** (`string`): Type of event (e.g., 'Meal Bolus'). - **insulin** (`number`): Amount of insulin administered. - **carbs** (`number`): Amount of carbohydrates consumed. - **created_at** (`string`): Timestamp of the treatment. - **profiles** (`Array`): Insulin pump profiles. - **startDate** (`string`): The start date of the profile. - **defaultProfile** (`string`): The name of the default profile. - **store** (`object`): Contains profile configurations. - **Default** (`object`): Default basal rate settings. - **basal** (`number`): The basal insulin rate. - **pumpEnabled** (`boolean`): Whether the insulin pump is enabled. - **activities** (`Array`): Physical activity data. - **heartRate** (`number`): Heart rate during activity. - **steps** (`number`): Number of steps taken. - **created_at** (`string`): Timestamp of the activity. - **user** (`object`): User-specific information. - **nsUrl** (`string`): URL of the Nightscout instance. ### Returns - **`SimulationResult`**: An object containing the simulation results. - **sgv** (`number`): The new simulated glucose value. - **deltaMinutes** (`number`): The time delta in minutes for the simulation step. - **carbsActivity** (`number`): Contribution of carbs to glucose change. - **cortisoneActivity** (`number`): Contribution of cortisone to glucose change. - **basalActivity** (`number`): Contribution of basal insulin to glucose change. - **bolusActivity** (`number`): Contribution of bolus insulin to glucose change. - **liverActivity** (`number`): Contribution of liver glucose production to change. - **activityFactor** (`number`): Factor representing physical activity's impact. - **alcoholActivity** (`number`): Contribution of alcohol to glucose change. - **isf** (`object`): Insulin Sensitivity Factor details. - **dynamic** (`number`): Dynamic ISF value. - **constant** (`number`): Constant ISF value. - **cob** (`number`): Carbohydrates on Board. - **bolusIOB** (`number`): Bolus Insulin On Board. - **pumpBasalIOB** (`number`): Pump Basal Insulin On Board. - **profileBasalIOB** (`number`): Profile Basal Insulin On Board. - **basalIOB** (`number`): Total Basal Insulin On Board. ### Request Example ```typescript import { simulator } from '@lsandini/cgmsim-lib'; import type { MainParams, SimulationResult } from '@lsandini/cgmsim-lib'; const params: MainParams = { patient: { WEIGHT: 70, AGE: 35, GENDER: 'Male', TZ: 'Europe/Paris', ISF: 50, // mg/dl per unit of insulin CR: 10, // grams of carbs per unit TP: 75, // time to peak insulin activity (minutes) DIA: 6, // duration of insulin action (hours) CARBS_ABS_TIME: 360, // carb absorption time (minutes) }, entries: [ { mills: Date.now() - 5 * 60 * 1000, sgv: 120 }, { mills: Date.now() - 10 * 60 * 1000, sgv: 115 }, { mills: Date.now() - 15 * 60 * 1000, sgv: 110 }, ], treatments: [ { eventType: 'Meal Bolus', insulin: 4, carbs: 40, created_at: new Date(Date.now() - 30 * 60 * 1000).toISOString(), }, ], profiles: [ { startDate: '2024-01-01', defaultProfile: 'Default', store: { Default: { basal: 0.8 } }, }, ], pumpEnabled: false, activities: [ { heartRate: 72, steps: 3000, created_at: new Date().toISOString() }, ], user: { nsUrl: 'https://nightscout.example.com' }, }; const result: SimulationResult = simulator(params); console.log('New SGV:', result.sgv); ``` ### Response Example ```json { "sgv": 127, "deltaMinutes": 5, "carbsActivity": 0.00312, "cortisoneActivity": 0, "basalActivity": 0.00041, "bolusActivity": 0.00218, "liverActivity": 0.00089, "activityFactor": 0.98, "alcoholActivity": 0, "isf": { "dynamic": 50, "constant": 50 }, "cob": 28.4, "bolusIOB": 2.1, "pumpBasalIOB": 0, "profileBasalIOB": 0, "basalIOB": 0 } ``` ``` -------------------------------- ### Run UVA/Padova T1DMS Simulation Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Simulates glucose levels using the UVA/Padova model. Requires initial patient state and baseline parameters. Pass the previous result's state for continuous simulation. ```typescript import { simulatorUVA } from '@lsandini/cgmsim-lib'; import type { MainParamsUVA, UvaSimulationResult } from '@lsandini/cgmsim-lib'; // defaultPatient holds the steady-state compartment values for the UVA model const defaultPatient = { /* PatientState from lt1/types */ }; const lastState = null; // null on first run; pass previous result.state thereafter const params: MainParamsUVA = { patient: { WEIGHT: 70, AGE: 35, GENDER: 'Male', TZ: 'Europe/Paris', ISF: 50, CR: 10, TP: 75, DIA: 6, CARBS_ABS_TIME: 360, }, entries: [ { mills: Date.now() - 5 * 60 * 1000, sgv: 118 }, ], treatments: [ { eventType: 'Meal Bolus', insulin: 3, carbs: 30, created_at: new Date(Date.now() - 10 * 60 * 1000).toISOString(), }, ], profiles: [ { startDate: '2024-01-01', defaultProfile: 'Default', store: { Default: { basal: 0.8 } }, }, ], pumpEnabled: true, lastState, defaultPatient, user: { nsUrl: 'https://nightscout.example.com' }, }; const result: UvaSimulationResult = simulatorUVA(params); console.log('UVA SGV:', result.sgv); console.log('Bolus IOB:', result.bolusIOB); // Output: // { // sgv: 122, // clamped to [40, 400] mg/dl // state: { Gp: 122, Gt: 119, I_: ..., ... }, // full compartment state // cob: 21.3, // bolusIOB: 1.8, // pumpBasalIOB: 0.4, // profileBasalIOB: 0.3, // basalIOB: 0 // } // On next call, pass result.state as lastState to continue the simulation ``` -------------------------------- ### simulator Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Runs a blood glucose simulation with the provided parameters. It takes a MainParamsUVA object and returns a SimulationResult containing blood glucose data and patient state. ```APIDOC ## simulator ### Description Runs a blood glucose simulation with the provided parameters. ### Parameters #### Path Parameters - `params` (MainParamsUVA) - Required - Main parameters for running the simulation. ### Returns `Object` Simulation result containing blood glucose data and patient state. - `sgv` (number) - - `state` (Object) - - `Gp` (number) - - `Gt` (number) - - `I_` (number) - - `Il` (number) - - `Ip` (number) - - `Isc1` (number) - - `Isc2` (number) - - `Qgut` (number) - - `Qsto1` (number) - - `Qsto2` (number) - - `W` (number) - - `X` (number) - - `XL` (number) - - `Y` (number) - - `Z` (number) - ### Request Example ```ts const simulationParams = { env: { WEIGHT: "70", AGE: "35", GENDER: "Male", // ... other environment parameters ... }, treatments: [ // ... treatment data ... ], profiles: [ // ... profile data ... ], lastState: { // ... patient state data ... }, entries: [ // ... blood glucose entry data ... ], pumpEnabled: true, activities: [ // ... activity data ... ], user: { nsUrl: "https://nightscout.example.com", // ... other user-related data ... }, }; const simulationResult = simulator(simulationParams); console.log("Blood glucose simulation result:", simulationResult); ``` ``` -------------------------------- ### simulator Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Simulation module for blood glucose data calculation. It takes main simulation parameters and returns the simulation result. ```APIDOC ## simulator ### Description Simulation module for blood glucose data calculation. ### Parameters #### Path Parameters - **params** ([MainParams](modules/types.md#mainparams)) - Required - Main parameters for running the simulation. ### Returns [`SimulationResult`](modules/types.md#simulationresult) Simulation result containing blood glucose data and other parameters. ``` -------------------------------- ### Simulate UVA Glucose Levels with simulatorUVA Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Simulate blood glucose levels using the `simulatorUVA` function. This function takes a `params` object as input and returns an object with simulation results. ```typescript const result = simulatorUVA(params); ``` -------------------------------- ### downloads Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Fetches treatments, profiles, CGM entries, and device status from a Nightscout instance in parallel. Includes validation for the maximum number of records. ```APIDOC ## `downloads` — Download All Nightscout Data Fetches treatments, profiles, CGM entries, and device status from a Nightscout instance in parallel. Validates that `maxCount` does not exceed 3000. ```typescript import downloads from '@lsandini/cgmsim-lib'; async function fetchPatientData() { try { const data = await downloads( 'https://nightscout.example.com', 'myApiSecret', 288, // optional: max records per collection (≤ 3000) ); console.log('Entries:', data.entries.length); console.log('Treatments:', data.treatments.length); console.log('Profiles:', data.profiles.length); console.log('Device statuses:', data.deviceStatus.length); // Output: // Entries: 288 // Treatments: 147 // Profiles: 1 // Device statuses: 288 } catch (err) { console.error('Download failed:', err.message); } } ``` ``` -------------------------------- ### Run Blood Glucose Simulation Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Use this function to run a blood glucose simulation with specified parameters. Ensure all required environment, treatment, profile, last state, entry, and user data are provided. ```typescript // Run a blood glucose simulation with specified parameters const simulationParams = { env: { WEIGHT: "70", AGE: "35", GENDER: "Male", // ... other environment parameters ... }, treatments: [ // ... treatment data ... ], profiles: [ // ... profile data ... ], lastState: { // ... patient state data ... }, entries: [ // ... blood glucose entry data ... ], pumpEnabled: true, activities: [ // ... activity data ... ], user: { nsUrl: "https://nightscout.example.com", // ... other user-related data ... }, }; const simulationResult = simulator(simulationParams); console.log("Blood glucose simulation result:", simulationResult); ``` -------------------------------- ### `uploadNotes` — Upload a Note to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a free-text annotation note as a treatment record to Nightscout. ```APIDOC ## `uploadNotes` — Upload a Note to Nightscout Uploads a free-text annotation note as a treatment record to Nightscout. ### Method POST ### Endpoint `/api/v1/treatments/` ### Parameters #### Request Body - **note** (string) - Required - The free-text note content. - **eventType** (string) - Required - Must be 'Note'. - **created_at** (string) - Required - ISO 8601 timestamp of when the note was created. ### Request Example ```json { "note": "Simulation started — patient fasting", "eventType": "Note", "created_at": "2024-04-17T12:00:00.000Z" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Note uploaded successfully" } ``` ``` -------------------------------- ### `uploadLogs` — Upload Simulation Logs to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a full `SimulationResult` with an attached notes string as a structured log treatment record. ```APIDOC ## `uploadLogs` — Upload Simulation Logs to Nightscout Uploads a full `SimulationResult` with an attached notes string as a structured log treatment record, enabling post-hoc inspection of simulation internals from Nightscout. ### Method POST ### Endpoint `/api/v1/treatments/` ### Parameters #### Request Body - **sgv** (number) - Required - Simulated glucose value. - **carbsActivity** (number) - Required - Carbohydrate activity value. - **bolusActivity** (number) - Required - Bolus activity value. - **notes** (string) - Optional - Additional notes about the simulation step. - **type** (string) - Required - Must be 'logs'. - **dateString** (string) - Required - The date and time of the log in ISO format. - **date** (number) - Required - The timestamp of the log in milliseconds since the epoch. ### Request Example ```json { "sgv": 150, "carbsActivity": 10, "bolusActivity": 2, "notes": "Step 42 — post-meal peak", "type": "logs", "dateString": "2024-04-17T12:00:00.000Z", "date": 1713350400000 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Simulation logs uploaded successfully" } ``` ``` -------------------------------- ### Upload Simulation Logs to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a full SimulationResult with an attached notes string as a structured log treatment record to Nightscout for post-hoc inspection. Requires the result object, notes, Nightscout URL, and API secret. ```typescript import { simulator, uploadLogs } from '@lsandini/cgmsim-lib'; const result = simulator(params); // params as shown in simulator example await uploadLogs( { ...result, notes: 'Step 42 — post-meal peak' }, 'https://nightscout.example.com', 'myApiSecret', ); // Uploads: { sgv, carbsActivity, bolusActivity, ..., type: 'logs', dateString, date } ``` -------------------------------- ### Download Nightscout Data with downloads Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Fetch data from the Nightscout API, including entries, profiles, and treatments. Requires the Nightscout URL and API secret. Handles asynchronous data retrieval. ```typescript // Download data from Nightscout API const apiUrl = "https://nightscout.example.com"; const apiSecret = "apiSecret123"; downloads(apiUrl, apiSecret) .then((downloadedData) => { console.log("Downloaded data:", downloadedData); }) .catch((error) => { console.error("Error downloading data:", error); }); ``` -------------------------------- ### `uploadTreatments` — Upload Treatment to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a meal bolus or temporary basal treatment to `/api/v1/treatments/`. Automatically nulls out inapplicable fields. ```APIDOC ## `uploadTreatments` — Upload Treatment to Nightscout Uploads a meal bolus or temporary basal treatment to `/api/v1/treatments/`. Automatically nulls out inapplicable fields (e.g., `carbs` for a temp basal). ### Method POST ### Endpoint `/api/v1/treatments/` ### Parameters #### Request Body - **eventType** (string) - Required - Type of treatment ('Meal Bolus', 'Temp Basal', etc.). - **insulin** (number) - Optional - Amount of insulin. - **carbs** (number) - Optional - Amount of carbohydrates. - **created_at** (string) - Required - ISO 8601 timestamp of when the treatment occurred. - **rate** (number) - Optional - Basal rate for temporary basal. - **duration** (number) - Optional - Duration of temporary basal in minutes. - **durationInMilliseconds** (number) - Optional - Duration of temporary basal in milliseconds. ### Request Example ```json // Meal bolus { "eventType": "Meal Bolus", "insulin": 5, "carbs": 50, "created_at": "2024-04-17T12:00:00.000Z" } // Temporary basal { "eventType": "Temp Basal", "rate": 1.2, "duration": 60, "durationInMilliseconds": 3600000, "created_at": "2024-04-17T12:00:00.000Z" } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Treatment uploaded successfully" } ``` ``` -------------------------------- ### UserParams Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/modules/types.md Represents user parameters, including the nsUrl. ```APIDOC Ƭ UserParams: `Object` #### Type declaration | Name | Type | | :------ | :----- | | `nsUrl` | `string` | ``` -------------------------------- ### downloadNightscoutEntries Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Downloads only SGV (blood glucose) entries from the Nightscout `/api/v1/entries/sgv.json` endpoint. ```APIDOC ## `downloadNightscoutEntries` — Download CGM Entries Downloads only SGV (blood glucose) entries from the Nightscout `/api/v1/entries/sgv.json` endpoint. ```typescript import { downloadNightscoutEntries } from '@lsandini/cgmsim-lib/src/downloads'; const entries = await downloadNightscoutEntries( 'https://nightscout.example.com', 'myApiSecret', 48, // last 48 readings (~4 hours at 5-min intervals) ); // entries: Array<{ mills: number; sgv: number }> console.log(entries[0]); // { mills: 1713350400000, sgv: 112 } ``` ``` -------------------------------- ### uploadLogs Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Uploads logs to the Nightscout API. It takes simulation results with notes, Nightscout URL, and API secret. ```APIDOC ## uploadLogs ### Description Uploads logs to the Nightscout API. ### Method `uploadLogs` ### Parameters #### Path Parameters - `simResult` (SimulationResult & { notes: string }) - Required - Simulation result with attached notes. - `nsUrl` (string) - Required - Nightscout URL. - `apiSecret` (string) - Required - Nightscout API secret. ### Returns `Promise` A promise that resolves when the upload is complete. ### Request Example ```ts const simulationResult = { // ... simulation result data ... notes: "Simulation complete", }; uploadLogs(simulationResult, "https://nightscout.example.com", "apiSecret123") .then(() => { console.log("Logs uploaded successfully."); }) .catch((error) => { console.error("Error uploading logs:", error); }); ``` ``` -------------------------------- ### uploadNotes Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Uploads notes to a Nightscout instance. This function returns a promise that resolves upon successful upload. ```APIDOC ## uploadNotes ### Description Uploads a note to Nightscout. ### Parameters #### Path Parameters - None #### Query Parameters - None #### Request Body - **notes** (string) - Required - The notes to upload. - **nsUrl** (string) - Required - Nightscout URL. - **apiSecret** (string) - Required - Nightscout API secret. ### Request Example ```ts // Upload a note to Nightscout uploadNotes("Important note", "https://nightscout.example.com", "apiSecret123") .then(() => { console.log("Note uploaded successfully."); }) .catch((error) => { console.error("Error uploading note:", error); }); ``` ### Response #### Success Response (void) - The promise resolves with no value upon successful upload. #### Response Example - None (Promise resolves to void) #### Error Handling - The promise rejects with an error if the upload fails. ``` -------------------------------- ### Upload Notes to Nightscout Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Use this function to upload notes to a Nightscout instance. Ensure you provide the correct Nightscout URL and API secret. The function returns a promise that resolves upon successful upload or rejects with an error. ```typescript // Upload a note to Nightscout uploadNotes("Important note", "https://nightscout.example.com", "apiSecret123") .then(() => { console.log("Note uploaded successfully."); }) .catch((error) => { console.error("Error uploading note:", error); }); ``` -------------------------------- ### Upload a Note to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a free-text annotation note as a treatment record to Nightscout. Requires the note content, Nightscout URL, and API secret. ```typescript import { uploadNotes } from '@lsandini/cgmsim-lib'; await uploadNotes( 'Simulation started — patient fasting', 'https://nightscout.example.com', 'myApiSecret', ); ``` -------------------------------- ### `loadActivity` — Load Activity Data from Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Loads physical activity records (steps and heart rate) from Nightscout's `/api/v1/activity/` endpoint. Supports optional time-based filtering. ```APIDOC ## `loadActivity` — Load Activity Data from Nightscout Loads physical activity records (steps and heart rate) from Nightscout's `/api/v1/activity/` endpoint. Supports optional time-based filtering. ### Method GET ### Endpoint `/api/v1/activity/` ### Parameters #### Query Parameters - **startDate** (string) - Optional - ISO 8601 timestamp to filter records from. If not provided, all records are returned. ### Request Example ``` GET /api/v1/activity/?startDate=2024-04-10T12:00:00.000Z ``` ### Response #### Success Response (200) - **activities** (array) - An array of activity objects. - **steps** (number) - Optional - Number of steps recorded. - **heartRate** (number) - Optional - Heart rate recorded. - **created_at** (string) - Required - ISO 8601 timestamp of the activity record. #### Response Example ```json [ { "steps": 4200, "heartRate": 88, "created_at": "2024-04-16T10:00:00.000Z" } ] ``` ``` -------------------------------- ### uploadActivity Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Uploads activity data to the Nightscout API. It takes activity data, Nightscout URL, and API secret as parameters. ```APIDOC ## uploadActivity ### Description Uploads activity data to the Nightscout API. ### Method `uploadActivity` ### Parameters #### Path Parameters - `activity` (Activity) - Required - Activity data to upload. - `nsUrl` (string) - Required - Nightscout URL. - `apiSecret` (string) - Required - Nightscout API secret. ### Returns `Promise` A promise that resolves when the upload is complete. ### Request Example ```ts const activityData = { // ... activity data ... }; uploadActivity(activityData, "https://nightscout.example.com", "apiSecret123") .then(() => { console.log("Activity data uploaded successfully."); }) .catch((error) => { console.error("Error uploading activity data:", error); }); ``` ``` -------------------------------- ### Download All Nightscout Data Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Fetches treatments, profiles, CGM entries, and device status from a Nightscout instance in parallel. Ensures the maximum record count does not exceed 3000. ```typescript import downloads from '@lsandini/cgmsim-lib'; async function fetchPatientData() { try { const data = await downloads( 'https://nightscout.example.com', 'myApiSecret', 288, // optional: max records per collection (≤ 3000) ); console.log('Entries:', data.entries.length); console.log('Treatments:', data.treatments.length); console.log('Profiles:', data.profiles.length); console.log('Device statuses:', data.deviceStatus.length); // Output: // Entries: 288 // Treatments: 147 // Profiles: 1 // Device statuses: 288 } catch (err) { console.error('Download failed:', err.message); } } ``` -------------------------------- ### Load Activity Data from Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Loads physical activity records (steps and heart rate) from Nightscout's /api/v1/activity/ endpoint. Supports optional time-based filtering using an ISO string. ```typescript import { loadActivity } from '@lsandini/cgmsim-lib'; // Load all activity records since 7 days ago const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000).toISOString(); const activities = await loadActivity( 'https://nightscout.example.com', 'myApiSecret', sevenDaysAgo, ); // activities: Array<{ steps?: number; heartRate?: number; created_at: string }> console.log('Activity records:', activities.length); console.log(activities[0]); // { steps: 4200, heartRate: 88, created_at: '2024-04-16T10:00:00.000Z' } ``` -------------------------------- ### Download Nightscout Treatments Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Downloads insulin, carb, and other treatment records from the Nightscout API. Allows filtering for specific treatment types. ```typescript import { downloadNightscoutTreatments } from '@lsandini/cgmsim-lib/src/downloads'; const treatments = await downloadNightscoutTreatments( 'https://nightscout.example.com', 'myApiSecret', 100, ); // Filter for recent boluses const recentBoluses = treatments.filter( (t) => t.eventType === 'Meal Bolus' && t.insulin > 0, ); console.log('Recent boluses:', recentBoluses.length); ``` -------------------------------- ### `uploadEntries` — Upload CGM Reading to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a simulated blood glucose reading (with trend direction) to the Nightscout `/api/v1/entries/` endpoint. ```APIDOC ## `uploadEntries` — Upload CGM Reading to Nightscout Uploads a simulated blood glucose reading (with trend direction) to the Nightscout `/api/v1/entries/` endpoint. ### Method POST ### Endpoint `/api/v1/entries/` ### Parameters #### Request Body - **sgv** (number) - Required - The glucose value. - **direction** (string) - Required - The trend direction (e.g., 'FortyFiveUp'). - **type** (string) - Required - Must be 'sgv'. - **dateString** (string) - Required - The date and time of the reading in ISO format. - **date** (number) - Required - The timestamp of the reading in milliseconds since the epoch. ### Request Example ```json { "sgv": 134, "direction": "FortyFiveUp", "type": "sgv", "dateString": "2024-04-17T12:00:00.000Z", "date": 1713350400000 } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Entry uploaded successfully" } ``` ``` -------------------------------- ### Upload Simulation Logs to Nightscout Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Uploads simulation logs, including any attached notes, to the Nightscout API. This function requires the simulation result object, Nightscout URL, and API secret. It returns a promise that resolves upon completion. ```typescript // Upload simulation logs to Nightscout const simulationResult = { // ... simulation result data ... notes: "Simulation complete", }; uploadLogs(simulationResult, "https://nightscout.example.com", "apiSecret123") .then(() => { console.log("Logs uploaded successfully."); }) .catch((error) => { console.error("Error uploading logs:", error); }); ``` -------------------------------- ### Download Nightscout CGM Entries Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Downloads only SGV (blood glucose) entries from the Nightscout API. Specify the number of last readings to fetch. ```typescript import { downloadNightscoutEntries } from '@lsandini/cgmsim-lib/src/downloads'; const entries = await downloadNightscoutEntries( 'https://nightscout.example.com', 'myApiSecret', 48, // last 48 readings (~4 hours at 5-min intervals) ); // entries: Array<{ mills: number; sgv: number }> console.log(entries[0]); // { mills: 1713350400000, sgv: 112 } ``` -------------------------------- ### loadActivity Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Loads activity data from the Nightscout API. It can optionally filter data from a specific UTC timestamp. ```APIDOC ## loadActivity ### Description Loads activity data from the Nightscout API based on optional time filter. ### Parameters #### Path Parameters - **nsUrl** (string) - Required - Nightscout URL. - **apiSecret** (string) - Required - Nightscout API secret. - **fromUtcString** (string) - Optional - UTC timestamp to filter data from. ### Returns `Promise`<([`Note`](modules/types.md#note) | [`Activity`](modules/types.md#activity) | [`Entry`](modules/types.md#entry))[] A promise that resolves with the loaded activity data. ### Example ```ts // Load activity data from Nightscout const apiUrl = "https://nightscout.example.com"; const apiSecret = "apiSecret123"; const fromDate = "2023-01-01T00:00:00.000Z"; // Optional UTC timestamp filter loadActivityData(apiUrl, apiSecret, fromDate) .then((activityData) => { console.log("Loaded activity data:", activityData); }) .catch((error) => { console.error("Error loading activity data:", error); }); ``` ``` -------------------------------- ### TypeDateISO Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/modules/types.md Represents a date and time string in ISO 8601 format (YYYY-MM-DDTHH:MM:SS.msZ). ```APIDOC Ƭ TypeDateISO: `${TDateISODate}T${TDateISOTime}Z` ``` -------------------------------- ### Upload Device Status to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads IOB/COB device status data to Nightscout's /api/v1/devicestatus/ endpoint. This data is used by loopers and closed-loop displays. ```typescript import { uploadDeviceStatus } from '@lsandini/cgmsim-lib'; await uploadDeviceStatus( { created_at: new Date().toISOString(), openaps: { openaps: { iob: 2.1, time: new Date().toISOString(), basaliob: 0.4, bolusiob: 1.7, }, suggested: { COB: 28, timestamp: new Date().toISOString(), }, }, }, 'https://nightscout.example.com', 'myApiSecret', ); ``` -------------------------------- ### uploadNotes Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/README.md Uploads notes to the Nightscout API. It requires the notes content, Nightscout URL, and API secret. ```APIDOC ## uploadNotes ### Description Uploads notes to the Nightscout API. ### Method `uploadNotes` ### Parameters #### Path Parameters - `notes` (string) - Required - The notes to upload. - `nsUrl` (string) - Required - Nightscout URL. - `apiSecret` (string) - Required - Nightscout API secret. ### Returns `Promise` A promise that resolves when the upload is complete. ### Request Example ```ts const notesContent = "This is a test note."; uploadNotes(notesContent, "https://nightscout.example.com", "apiSecret123") .then(() => { console.log("Notes uploaded successfully."); }) .catch((error) => { console.error("Error uploading notes:", error); }); ``` ``` -------------------------------- ### Upload CGM Reading to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a simulated blood glucose reading with trend direction to the Nightscout /api/v1/entries/ endpoint. Requires the Nightscout URL and API secret. ```typescript import { uploadEntries, arrows } from '@lsandini/cgmsim-lib'; const simResult = { sgv: 134 }; const trend = arrows(134, 130, 125, 119); await uploadEntries( { sgv: simResult.sgv, direction: trend.direction }, 'https://nightscout.example.com', 'myApiSecret', ); // POSTs: { sgv: 134, direction: 'FortyFiveUp', type: 'sgv', dateString: '...', date: 1713350400000 } ``` -------------------------------- ### Upload Treatment to Nightscout Source: https://context7.com/lsandini/cgmsim-lib/llms.txt Uploads a meal bolus or temporary basal treatment to Nightscout's /api/v1/treatments/ endpoint. Inapplicable fields are automatically nullified. ```typescript import { uploadTreatments } from '@lsandini/cgmsim-lib'; // Meal bolus await uploadTreatments( { eventType: 'Meal Bolus', insulin: 5, carbs: 50, created_at: new Date().toISOString(), }, 'https://nightscout.example.com', 'myApiSecret', ); // Temporary basal await uploadTreatments( { eventType: 'Temp Basal', rate: 1.2, duration: 60, durationInMilliseconds: 60 * 60 * 1000, created_at: new Date().toISOString(), }, 'https://nightscout.example.com', 'myApiSecret', ); ``` -------------------------------- ### TMinutes Source: https://github.com/lsandini/cgmsim-lib/blob/main/doc/modules/types.md Represents a two-digit minute. ```APIDOC Ƭ TMinutes: `${number}${number}` ```