Skip to content

Commit

Permalink
Merge pull request #133 from 3timeslazy/nightscout-v3
Browse files Browse the repository at this point in the history
Make `readConfig` source of truth
  • Loading branch information
timoschlueter committed Apr 5, 2024
2 parents 6c53220 + 5f867a9 commit f685250
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 41 deletions.
42 changes: 40 additions & 2 deletions src/config.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,31 @@
import { LLU_API_ENDPOINTS } from './constants/llu-api-endpoints';

function readConfig() {
const requiredEnvs = ['NIGHTSCOUT_API_TOKEN', 'NIGHTSCOUT_URL'];
const requiredEnvs = [
'NIGHTSCOUT_API_TOKEN',
'NIGHTSCOUT_URL',
'LINK_UP_USERNAME',
'LINK_UP_PASSWORD',
];
for (let envName of requiredEnvs) {
if (!process.env[envName]) {
throw Error(`Required environment variable ${envName} is not set`);
exitLog(`Required environment variable ${envName} is not set`)
}
}

if (process.env.LOG_LEVEL) {
if (!['info', 'debug'].includes(process.env.LOG_LEVEL.toLowerCase())) {
exitLog(`LOG_LEVEL should be either 'info' or 'debug', but got '${process.env.LOG_LEVEL}'`);
}
}
if (process.env.LINK_UP_REGION) {
if (!LLU_API_ENDPOINTS.hasOwnProperty(process.env.LINK_UP_REGION)) {
exitLog(`LINK_UP_REGION should be one of ${Object.keys(LLU_API_ENDPOINTS)}, but got ${process.env.LINK_UP_REGION}`);
}
}
if (process.env.LINK_UP_TIME_INTERVAL) {
if (isNaN(parseInt(process.env.LINK_UP_TIME_INTERVAL))) {
exitLog(`LINK_UP_TIME_INTERVAL expected to be an integer, but got '${process.env.LINK_UP_TIME_INTERVAL}'`);
}
}

Expand All @@ -13,10 +36,25 @@ function readConfig() {
return {
nightscoutApiToken: process.env.NIGHTSCOUT_API_TOKEN as string,
nightscoutBaseUrl: url.toString(),
linkUpUsername: process.env.LINK_UP_USERNAME as string,
linkUpPassword: process.env.LINK_UP_PASSWORD as string,

logLevel: process.env.LOG_LEVEL || 'info',
singleShot: process.env.SINGLE_SHOT === 'true',

nightscoutApiV3: process.env.NIGHTSCOUT_API_V3 === 'true',
nightscoutDisableHttps: process.env.NIGHTSCOUT_DISABLE_HTTPS === 'true',
nightscoutDevice: process.env.DEVICE_NAME || 'nightscout-librelink-up',

linkUpRegion: process.env.LINK_UP_REGION || 'EU',
linkUpTimeInterval: Number(process.env.LINK_UP_TIME_INTERVAL) || 5,
linkUpConnection: process.env.LINK_UP_CONNECTION as string,
};
}

function exitLog(msg: string) {
console.log(msg);
process.exit(1);
}

export default readConfig;
62 changes: 23 additions & 39 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,50 +51,34 @@ const logger = createLogger({
logFormat
),
transports: [
new transports.Console({level: process.env.LOG_LEVEL || "info"}),
new transports.Console({level: config.logLevel}),
]
});

axios.interceptors.response.use(response =>
{
return response;
}, error =>
{
if (error.response)
{
logger.error(JSON.stringify(error.response.data));
}
else
axios.interceptors.response.use(
response => response,
error =>
{
logger.error(error.message);
if (error.response)
{
logger.error(JSON.stringify(error.response.data));
}
else
{
logger.error(error.message);
}
return error;
}
return error;
});
);

const USER_AGENT = "Mozilla/5.0 (iPhone; CPU iPhone OS 16_5_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/16.5 Mobile/15E148 Safari/604.1";

/**
* LibreLink Up Credentials
*/
const LINK_UP_USERNAME = process.env.LINK_UP_USERNAME;
const LINK_UP_PASSWORD = process.env.LINK_UP_PASSWORD;

/**
* LibreLink Up API Settings (Don't change this unless you know what you are doing)
*/
const LIBRE_LINK_UP_VERSION = "4.7.0";
const LIBRE_LINK_UP_PRODUCT = "llu.ios";
const LINK_UP_REGION = process.env.LINK_UP_REGION || "EU";
const LIBRE_LINK_UP_URL = getLibreLinkUpUrl(LINK_UP_REGION);

function getLibreLinkUpUrl(region: string): string
{
if (LLU_API_ENDPOINTS.hasOwnProperty(region))
{
return LLU_API_ENDPOINTS[region];
}
return LLU_API_ENDPOINTS.EU;
}
const LIBRE_LINK_UP_URL = LLU_API_ENDPOINTS[config.linkUpRegion];

/**
* last known authTicket
Expand All @@ -108,13 +92,13 @@ const libreLinkUpHttpHeaders: LibreLinkUpHttpHeaders = {
"product": LIBRE_LINK_UP_PRODUCT
}

if (process.env.SINGLE_SHOT === "true")
if (config.singleShot)
{
main().then();
}
else
{
const schedule = "*/" + (process.env.LINK_UP_TIME_INTERVAL || 5) + " * * * *";
const schedule = `*/${config.linkUpTimeInterval} * * * *`;
logger.info("Starting cron schedule: " + schedule)
cron.schedule(schedule, () =>
{
Expand Down Expand Up @@ -146,7 +130,7 @@ async function main(): Promise<void>
}

await uploadToNightScout(glucoseGraphData);
}
}

export async function login(): Promise<AuthTicket | null>
{
Expand All @@ -156,8 +140,8 @@ export async function login(): Promise<AuthTicket | null>
const response: { data: LoginResponse } = await axios.post(
url,
{
email: LINK_UP_USERNAME,
password: LINK_UP_PASSWORD,
email: config.linkUpUsername,
password: config.linkUpPassword,
},
{
headers: libreLinkUpHttpHeaders,
Expand Down Expand Up @@ -255,14 +239,14 @@ export async function getLibreLinkUpConnection(): Promise<string | null>

dumpConnectionData(connectionData);

if (!process.env.LINK_UP_CONNECTION)
if (!config.linkUpConnection)
{
logger.warn("You did not specify a Patient-ID in the LINK_UP_CONNECTION environment variable.");
logPickedUpConnection(connectionData[0]);
return connectionData[0].patientId;
}

const connection = connectionData.filter(connectionEntry => connectionEntry.patientId === process.env.LINK_UP_CONNECTION)[0];
const connection = connectionData.filter(connectionEntry => connectionEntry.patientId === config.linkUpConnection)[0];
if (!connection)
{
logger.error("The specified Patient-ID was not found.");
Expand Down Expand Up @@ -317,7 +301,7 @@ export async function createFormattedMeasurements(measurementData: GraphData): P
async function uploadToNightScout(measurementData: GraphData): Promise<void>
{
const formattedMeasurements: Entry[] = await createFormattedMeasurements(measurementData);

if (formattedMeasurements.length > 0)
{
logger.info("Trying to upload " + formattedMeasurements.length + " glucose measurement items to Nightscout");
Expand Down

0 comments on commit f685250

Please sign in to comment.