Index: firmware/App/Modes/Dialysis.c =================================================================== diff -u -r94895e32fe18e78b98fe3bb7786838cf00afdbfa -r1a4fca64a161a9965f563f44f72e3251d1f7a929 --- firmware/App/Modes/Dialysis.c (.../Dialysis.c) (revision 94895e32fe18e78b98fe3bb7786838cf00afdbfa) +++ firmware/App/Modes/Dialysis.c (.../Dialysis.c) (revision 1a4fca64a161a9965f563f44f72e3251d1f7a929) @@ -1,28 +1,35 @@ -/**********************************************************************//** - * - * Copyright (c) 2020 Diality Inc. - All Rights Reserved. - * - * THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN - * WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. - * - * @file Dialysis.c - * - * @date 15-Jan-2020 - * @author S. Nash - * - * @brief State machine for the dialysis sub-mode of treatment mode. - * - **************************************************************************/ +/************************************************************************** +* +* Copyright (c) 2019-2020 Diality Inc. - All Rights Reserved. +* +* THIS CODE MAY NOT BE COPIED OR REPRODUCED IN ANY FORM, IN PART OR IN +* WHOLE, WITHOUT THE EXPLICIT PERMISSION OF THE COPYRIGHT OWNER. +* +* @file Dialysis.c +* +* @author (last) Sean Nash +* @date (last) 24-Sep-2020 +* +* @author (original) Sean +* @date (original) 15-Jan-2020 +* +***************************************************************************/ +#include + +#include "AirTrap.h" #include "BloodFlow.h" #include "Buttons.h" #include "Dialysis.h" #include "DialInFlow.h" #include "DialOutFlow.h" +#include "ModeTreatment.h" +#include "ModeTreatmentParams.h" #include "OperationModes.h" +#include "SystemCommMessages.h" #include "TaskGeneral.h" #include "Timers.h" -#include "ModeTreatment.h" +#include "Valves.h" /** * @addtogroup Dialysis @@ -31,18 +38,30 @@ // ********** private definitions ********** -#define MAX_UF_ACCURACY_ERROR_ML 250 ///< Maximum ultrafiltration accuracy error in mL over the entire treatment. -#define MAX_UF_ACCURACY_ERROR_ML_PER_HR 100 ///< Maximum ultrafiltration accuracy error in mL/hr. -#define UF_ACCURACY_CHECK_INTERVAL ((1 * MIN_PER_HOUR * SEC_PER_MIN * MS_PER_SECOND) / TASK_GENERAL_INTERVAL) ///< Ultrafiltration rate accuracy check interval count +#define MAX_UF_RATE_ML_PER_HOUR 2750.0 ///< Maximum ultrafiltration rate in mL/hour +#define MAX_UF_ACCURACY_ERROR_ML 250.0 ///< Maximum ultrafiltration accuracy error in mL over the entire treatment. +/// Saline bolus data broadcast interval (ms/task time) count. +static const U32 SALINE_BOLUS_DATA_PUB_INTERVAL = ( MS_PER_SECOND / TASK_GENERAL_INTERVAL ); +/// Ultrafiltration rate accuracy check interval count. +static const U32 UF_ACCURACY_CHECK_INTERVAL = ((1 * MIN_PER_HOUR * SEC_PER_MIN * MS_PER_SECOND) / TASK_GENERAL_INTERVAL); +#define MAX_SALINE_VOLUME_DELIVERED 800 ///< Maximum saline volume delivered for a treatment. +#define SALINE_BOLUS_RATE_ML_MIN 150 ///< Fixed rate for saline bolus delivery. +#define MIN_SALINE_BOLUS_VOLUME_PCT 0.8 ///< Minimum saline bolus volume measured by independent means (as % of target). +#define MAX_SALINE_BOLUS_VOLUME_PCT 1.2 ///< Maximum saline bolus volume measured by independent means (as % of target). + +#define MAX_ACTIVE_LOAD_CELL_CHANGE_G 50.0 ///< Maximum delta between new and previous measured UF volume. + // ********** private data ********** static DIALYSIS_STATE_T currentDialysisState; ///< Current state of the dialysis sub-mode state machine. static UF_STATE_T currentUFState; ///< Current state of the ultrafiltration state machine. +static SALINE_BOLUS_STATE_T currentSalineBolusState; ///< Current state of the saline bolus state machine. static F32 refUFVolume; ///< Current reference volume for ultrafiltration (Where should we be w/r/t ultrafiltration). static F32 measUFVolume; ///< Current total measured volume for ultrafiltration (Where are we w/r/t ultrafiltration). -static F32 resStartVolume; ///< Reservoir start volume for ultrafiltration (i.e. where did we start with current reservoir). +static F32 resStartVolume[ NUM_OF_DG_RESERVOIRS ]; ///< Reservoir start volume for ultrafiltration (i.e. where did we start with each reservoir). +static F32 resFinalVolume[ NUM_OF_DG_RESERVOIRS ]; ///< Reservoir final volume for ultrafiltration (i.e. where did we end after switch with each reservoir). static F32 measUFVolumeFromPriorReservoirs; ///< Current total ultrafiltration volume from previous reservoirs in current treatment. static U32 uFTimeMS; ///< Current elapsed ultrafiltration time (in ms). Used for calculating UF reference volume. @@ -53,40 +72,58 @@ static F32 maxUFVolumeML; ///< Currently set total ultrafiltration volume for treatment (from prescription). static F32 setUFRate; ///< Currently set ultrafiltration rate (from prescription). +static U32 salineBolusBroadcastTimerCtr; ///< Saline bolus data broadcast timer counter used to schedule when to transmit data. +static BOOL salineBolusStartRequested; ///< Flag indicates a saline bolus start has been requested by user. +static BOOL salineBolusAbortRequested; ///< Flag indicates a salien bolus abort has been requested by user. +static BOOL salineBolusAutoResumeUF; ///< Flag indicates UF should be auto-resumed after saline bolus completes. +static F32 totalSalineVolumeDelivered; ///< Volume (mL) in total of saline delivered so far (cumulative for all boluses including current one). +static F32 bolusSalineVolumeDelivered; ///< Volume (mL) of current bolus delivered so far. +static F32 bolusSalineVolumeDelivered_Safety; ///< Volume (mL) of current bolus delivered so far according to safety monitor. +static U32 bolusSalineMotorCount; ///< Blood pump motor rev count during saline bolus to calculate saline bolus volume independently for safety. +static U32 bolusSalineLastMotorCount; ///< Last blood pump count from last saline bolus volume update. +static U32 bolusSalineLastVolumeTimeStamp; ///< Time stamp for last saline volume update. + static U32 uFAccuracyCheckTimerCtr; ///< Timer counter to determine when next to check ultrafiltration accuracy. static F32 lastUFVolumeChecked; ///< Starting ultrafiltration volume for accuracy check. // ********** private function prototypes ********** static DIALYSIS_STATE_T handleDialysisUltrafiltrationState( void ); -static DIALYSIS_STATE_T handleDialysisSolutionInfusionState( void ); +static DIALYSIS_STATE_T handleDialysisSalineBolusState( void ); -static UF_STATE_T handleUFStartState( void ); -static UF_STATE_T handleUFPausedState( void ); -static UF_STATE_T handleUFRunningState( void ); -static UF_STATE_T handleUFCompletedOrOffState( void ); +static UF_STATE_T handleUFStartState( DIALYSIS_STATE_T *dialysisState ); +static UF_STATE_T handleUFPausedState( DIALYSIS_STATE_T *dialysisState ); +static UF_STATE_T handleUFRunningState( DIALYSIS_STATE_T *dialysisState ); +static UF_STATE_T handleUFOffState( DIALYSIS_STATE_T *dialysisState ); +static UF_STATE_T handleUFCompletedState( DIALYSIS_STATE_T *dialysisState ); -static void checkUFAccuracy( void ); +static SALINE_BOLUS_STATE_T handleSalineBolusIdleState( DIALYSIS_STATE_T *dialysisState ); +static SALINE_BOLUS_STATE_T handleSalineBolusWait4Pumps2Stop( DIALYSIS_STATE_T *dialysisState ); +static SALINE_BOLUS_STATE_T handleSalineBolusInProgressState( DIALYSIS_STATE_T *dialysisState ); +static SALINE_BOLUS_STATE_T handleSalineBolusMaxDeliveredState( DIALYSIS_STATE_T *dialysisState ); + +static void checkUFAccuracyAndVolume( void ); static void updateUFVolumes( void ); +static void publishSalineBolusData( void ); + /*********************************************************************//** * @brief - * The initDialysis function initializes the Dialysis sub-mode module. \n - * Calling this function will reset dialysis and therefore should only \n + * The initDialysis function initializes the Dialysis sub-mode module. + * Calling this function will reset dialysis and therefore should only * be called when a new treatment is due to begin. - * @details - * Inputs : none - * Outputs : Dialysis sub-mode module initialized. + * @details Inputs: none + * @details Outputs: Dialysis sub-mode module initialized. * @return none *************************************************************************/ void initDialysis( void ) { currentDialysisState = DIALYSIS_START_STATE; currentUFState = UF_START_STATE; + currentSalineBolusState = SALINE_BOLUS_STATE_IDLE; refUFVolume = 0.0; measUFVolume = 0.0; - resStartVolume = 0.0; measUFVolumeFromPriorReservoirs = 0.0; uFTimeMS = 0; @@ -97,39 +134,96 @@ maxUFVolumeML = 0.0; setUFRate = 0.0; + salineBolusBroadcastTimerCtr = 0; + totalSalineVolumeDelivered = 0.0; + uFAccuracyCheckTimerCtr = 0; lastUFVolumeChecked = 0.0; + + resetSalineBolus(); } /*********************************************************************//** * @brief - * The transitionToDialysis function prepares for transition to dialysis sub-mode. \n - * This function will reset anything required for resuming dialysis in a \n - * treatment that has already begun. It does not reset everything as dialysis \n - * may be stopped and resumed multiple times due to alarms or user intervention \n + * The resetSalineBolus function initializes the saline bolus variables + * at start of treatment or after stopping a bolus (e.g. alarm). Total + * saline bolus volume delivered will not be affected by this function. + * @details Inputs: none + * @details Outputs: Dialysis sub-mode module initialized. + * @return none + *************************************************************************/ +void resetSalineBolus( void ) +{ + salineBolusStartRequested = FALSE; + salineBolusAbortRequested = FALSE; + salineBolusAutoResumeUF = FALSE; + bolusSalineVolumeDelivered = 0.0; + bolusSalineVolumeDelivered_Safety = 0.0; + bolusSalineMotorCount = 0; + if ( currentSalineBolusState != SALINE_BOLUS_STATE_MAX_DELIVERED ) + { + currentSalineBolusState = SALINE_BOLUS_STATE_IDLE; + } +} + +/*********************************************************************//** + * @brief + * The transitionToDialysis function prepares for transition to dialysis sub-mode. + * This function will reset anything required for resuming dialysis in a + * treatment that has already begun. It does not reset everything as dialysis + * may be stopped and resumed multiple times due to alarms or user intervention * and we don't want to start the treatment all over again. - * @details - * Inputs : none - * Outputs : none + * @details Inputs: none + * @details Outputs: none * @return none *************************************************************************/ void transitionToDialysis( void ) { - // TODO - anything needed here? + // Set last UF timestamp so UF ref is resumed from this time + lastUFTimeStamp = getMSTimerCount(); + // Send dialysate outlet pump latest UF volumes + setDialOutUFVolumes( refUFVolume, measUFVolume ); + + // Inform DG interface that dialysis has started/resumed + dialysisResumed(); + + // Set valves for dialysis + setValvePosition( VDI, VALVE_POSITION_B_OPEN ); + setValvePosition( VDO, VALVE_POSITION_B_OPEN ); + setValvePosition( VBA, VALVE_POSITION_B_OPEN ); + setValvePosition( VBV, VALVE_POSITION_B_OPEN ); + // Restart pumps +#ifndef RUN_PUMPS_OPEN_LOOP + setBloodPumpTargetFlowRate( setBloodFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + setDialInPumpTargetFlowRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); +#else + setBloodPumpTargetFlowRate( setBloodFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); + setDialInPumpTargetFlowRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); +#endif + setDialOutPumpTargetRate( setDialysateFlowRate + (S32)setUFRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + // TODO - Heparin pump + // Tell DG to start heating dialysate + cmdStartDGTrimmerHeater(); + + startAirTrapControl(); + + // Set user alarm recovery actions allowed in this sub-mode + setAlarmUserActionEnabled( ALARM_USER_ACTION_RESUME, TRUE ); + setAlarmUserActionEnabled( ALARM_USER_ACTION_RINSEBACK, TRUE ); + setAlarmUserActionEnabled( ALARM_USER_ACTION_END_TREATMENT, TRUE ); } /*********************************************************************//** * @brief - * The setDialysisParams function sets the dialysis treatment parameters. \n - * This function should be called prior to beginning dialysis treatment \n + * The setDialysisParams function sets the dialysis treatment parameters. + * This function should be called prior to beginning dialysis treatment * and when the user changes one or more parameters during treatment. - * @details - * Inputs : none - * Outputs : dialysis treatment parameters are set. - * @param bPFlow : target blood pump flow rate (in mL/min). - * @param dPFlow : target dialysate inlet pump flow rate (in mL/min). - * @param maxUFVol : maximum ultrafiltration volume (in mL). - * @param uFRate : target ultrafiltration rate (in mL/min). + * @details Inputs: none + * @details Outputs: dialysis treatment parameters are set. + * @param bPFlow target blood pump flow rate (in mL/min) + * @param dPFlow target dialysate inlet pump flow rate (in mL/min) + * @param maxUFVol maximum ultrafiltration volume (in mL) + * @param uFRate target ultrafiltration rate (in mL/min) * @return none *************************************************************************/ void setDialysisParams( U32 bPFlow, U32 dPFlow, F32 maxUFVol, F32 uFRate ) @@ -138,54 +232,129 @@ setDialysateFlowRate = dPFlow; maxUFVolumeML = maxUFVol; setUFRate = uFRate; + + if ( TREATMENT_DIALYSIS_STATE == getTreatmentState() ) + { +#ifndef RUN_PUMPS_OPEN_LOOP + setBloodPumpTargetFlowRate( setBloodFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + setDialInPumpTargetFlowRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); +#else + setBloodPumpTargetFlowRate( setBloodFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); + setDialInPumpTargetFlowRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); +#endif + setDialOutPumpTargetRate( setDialysateFlowRate + (S32)setUFRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + } } /*********************************************************************//** * @brief - * The startDialysis function starts/resumes dialysis. This function \n - * will be called by Treatment Mode when beginning or resuming dialysis \n - * treatment. - * @details - * Inputs : none - * Outputs : Dialysis module prepared for immediate resumption. + * The stopDialysis function stops dialysis. This function will be called + * by Treatment Mode when an alarm occurs or the user pressed the stop button. + * Dialysis may be resumed later. + * @details Inputs: none + * @details Outputs: Blood and dialysate pumps stopped. Heparin pump stopped. * @return none *************************************************************************/ -void startDialysis( void ) +void stopDialysis( void ) { - U32 tempDPORate = (setDialysateFlowRate * 6) / 10; // TODO - temporary fudge factor - remove later + // Stop pumps + setBloodPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + setDialInPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + setDialOutPumpTargetRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + // TODO - stop Heparin pump + // Tell DG to stop heating dialysate + cmdStopDGTrimmerHeater(); +} - lastUFTimeStamp = getMSTimerCount(); - setDialOutUFVolumes( refUFVolume, measUFVolume ); - setBloodPumpTargetFlowRate( setBloodFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); - setDialInPumpTargetFlowRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); - // setDialOutPumpTargetRate( setDialysateFlowRate + (S32)setUFRate), MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); // TODO - restore later - setDialOutPumpTargetRate( tempDPORate + (S32)setUFRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); // TODO - test code - remove later - // TODO - Heparin pump +/*********************************************************************//** + * @brief + * The signalStartSalineBolus function handles user request to initiate a + * saline bolus. + * @details Inputs: TBD + * @details Outputs: TBD + * @return none + *************************************************************************/ +void signalStartSalineBolus( void ) +{ + BOOL accept = FALSE; + REQUEST_REJECT_REASON_CODE_T rejReason = REQUEST_REJECT_REASON_NONE; + U32 salineBolusVolume = getTreatmentParameterU32( TREATMENT_PARAM_SALINE_BOLUS_VOLUME ); + HD_OP_MODE_T currOpMode = getCurrentOperationMode(); + TREATMENT_STATE_T currTreatSubMode = getTreatmentState(); + SALINE_BOLUS_STATE_T currSalineBolusState = getSalineBolusState(); + + // Must be in treatment mode, dialysis sub-mode, saline bolus in idle state in order to start a saline bolus + if ( currOpMode != MODE_TREA ) + { + rejReason = REQUEST_REJECT_REASON_NOT_IN_TREATMENT_MODE; + } + else if ( currTreatSubMode != TREATMENT_DIALYSIS_STATE ) + { + rejReason = REQUEST_REJECT_REASON_INVALID_TREATMENT_STATE; + } + else if ( currSalineBolusState != SALINE_BOLUS_STATE_IDLE ) + { + rejReason = REQUEST_REJECT_REASON_SALINE_BOLUS_IN_PROGRESS; + } + else if ( totalSalineVolumeDelivered >= (F32)MAX_SALINE_VOLUME_DELIVERED ) + { + rejReason = REQUEST_REJECT_REASON_SALINE_MAX_VOLUME_REACHED; + } + else + { + accept = TRUE; + salineBolusStartRequested = TRUE; + } + + // Send response + sendSalineBolusResponse( accept, rejReason, salineBolusVolume ); } /*********************************************************************//** * @brief - * The stopDialysis function stops dialysis. This function will be called \n - * by Treatment Mode when an alarm occurs or the user pressed the stop button. \n - * Dialysis may be resumed later. - * @details - * Inputs : none - * Outputs : Blood and dialysate pumps stopped. Heparin pump stopped. + * The signalAbortSalineBolus function handles user request to abort a + * saline bolus. + * @details Inputs: TBD + * @details Outputs: TBD * @return none *************************************************************************/ -void stopDialysis( void ) +void signalAbortSalineBolus( void ) { - setBloodPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); - setDialInPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); - setDialOutPumpTargetRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + BOOL accept = FALSE; + REQUEST_REJECT_REASON_CODE_T rejReason = REQUEST_REJECT_REASON_NONE; + U32 salineBolusVolume = getTreatmentParameterU32( TREATMENT_PARAM_SALINE_BOLUS_VOLUME ); + HD_OP_MODE_T currOpMode = getCurrentOperationMode(); + TREATMENT_STATE_T currTreatSubMode = getTreatmentState(); + SALINE_BOLUS_STATE_T currSalineBolusState = getSalineBolusState(); + + // Must be in treatment mode, dialysis sub-mode, saline bolus in delivery state in order to abort a saline bolus + if ( currOpMode != MODE_TREA ) + { + rejReason = REQUEST_REJECT_REASON_NOT_IN_TREATMENT_MODE; + } + else if ( currTreatSubMode != TREATMENT_DIALYSIS_STATE ) + { + rejReason = REQUEST_REJECT_REASON_INVALID_TREATMENT_STATE; + } + else if ( currSalineBolusState != SALINE_BOLUS_STATE_IN_PROGRESS ) + { + rejReason = REQUEST_REJECT_REASON_SALINE_BOLUS_NOT_IN_PROGRESS; + } + else + { + accept = TRUE; + salineBolusAbortRequested = TRUE; + } + + // Send response + sendSalineBolusResponse( accept, rejReason, salineBolusVolume ); } /*********************************************************************//** * @brief * The getDialysisState function gets the current dialysis state (sub-mode). - * @details - * Inputs : currentDialysisState - * Outputs : none + * @details Inputs: currentDialysisState + * @details Outputs: none * @return currentDialysisState *************************************************************************/ DIALYSIS_STATE_T getDialysisState( void ) @@ -196,9 +365,8 @@ /*********************************************************************//** * @brief * The getUltrafiltrationState function gets the current ultrafiltration state. - * @details - * Inputs : currentUFState - * Outputs : none + * @details Inputs: currentUFState + * @details Outputs: none * @return currentUFState *************************************************************************/ UF_STATE_T getUltrafiltrationState( void ) @@ -208,108 +376,177 @@ /*********************************************************************//** * @brief + * The getSalineBolusState function gets the current saline bolus state. + * @details Inputs: currentSalineBolusState + * @details Outputs: none + * @return currentSalineBolusState + *************************************************************************/ +SALINE_BOLUS_STATE_T getSalineBolusState( void ) +{ + return currentSalineBolusState; +} + +/*********************************************************************//** + * @brief + * The getUltrafiltrationVolumeCollected function gets the current ultrafiltration + * volume collected so far for current treatment. + * @details Inputs: measUFVolume, measUFVolumeFromPriorReservoirs + * @details Outputs: none + * @return currentUFState + *************************************************************************/ +F32 getUltrafiltrationVolumeCollected( void ) +{ + F32 result = measUFVolume; + + return result; +} + +/*********************************************************************//** + * @brief * The pauseUF function pauses ultrafiltration. - * @details - * Inputs : currentDialysisState, currentUFState - * Outputs : currentUFState, outlet pump set point + * @details Inputs: currentDialysisState, currentUFState + * @details Outputs: currentUFState, outlet pump set point * @return TRUE if pause successful, FALSE if not *************************************************************************/ BOOL pauseUF( void ) { BOOL result = FALSE; + REQUEST_REJECT_REASON_CODE_T rejectReason = REQUEST_REJECT_REASON_NONE; TREATMENT_STATE_T trtState = getTreatmentState(); - OP_MODE currMode = getCurrentOperationMode(); + HD_OP_MODE_T currMode = getCurrentOperationMode(); if ( ( MODE_TREA == currMode ) && ( TREATMENT_DIALYSIS_STATE == trtState ) && ( DIALYSIS_UF_STATE == currentDialysisState ) && ( UF_RUNNING_STATE == currentUFState ) ) { - // set outlet pump to dialysate rate - result = setDialOutPumpTargetRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); - - if ( TRUE == result ) + result = TRUE; + // Set outlet pump to dialysate rate + setDialOutPumpTargetRate( setDialysateFlowRate, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + // Go to UF paused state + currentUFState = UF_PAUSED_STATE; + } + else + { + if ( MODE_TREA != currMode ) { - // go to UF paused state - currentUFState = UF_PAUSED_STATE; + rejectReason = REQUEST_REJECT_REASON_NOT_IN_TREATMENT_MODE; } + else if ( TREATMENT_DIALYSIS_STATE != trtState ) + { + rejectReason = REQUEST_REJECT_REASON_INVALID_TREATMENT_STATE; + } + else if ( DIALYSIS_UF_STATE != currentDialysisState ) + { + rejectReason = REQUEST_REJECT_REASON_SALINE_BOLUS_IN_PROGRESS; + } + else + { + rejectReason = REQUEST_REJECT_REASON_UF_NOT_IN_PROGESS; + } } + // Send response w/ reason code if rejected + sendUFPauseResumeResponse( result, rejectReason, currentUFState ); + // Send state data immediately for UI update + broadcastTreatmentTimeAndState(); + return result; } /*********************************************************************//** * @brief * The resumeUF function resumes ultrafiltration. - * @details - * Inputs : currentDialysisState, currentUFState - * Outputs : currentUFState, outlet pump set point + * @details Inputs: currentDialysisState, currentUFState + * @details Outputs: currentUFState, outlet pump set point * @return TRUE if resume successful, FALSE if not *************************************************************************/ BOOL resumeUF( void ) { BOOL result = FALSE; + REQUEST_REJECT_REASON_CODE_T rejectReason = REQUEST_REJECT_REASON_NONE; TREATMENT_STATE_T trtState = getTreatmentState(); - OP_MODE currMode = getCurrentOperationMode(); + HD_OP_MODE_T currMode = getCurrentOperationMode(); if ( ( MODE_TREA == currMode ) && ( TREATMENT_DIALYSIS_STATE == trtState ) && ( DIALYSIS_UF_STATE == currentDialysisState ) && ( UF_PAUSED_STATE == currentUFState ) ) { - // set outlet pump to dialysate rate + set UF rate - result = setDialOutPumpTargetRate( setDialysateFlowRate + FLOAT_TO_INT_WITH_ROUND( setUFRate ), MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); - - if ( TRUE == result ) + result = TRUE; + // Set outlet pump to dialysate rate + set UF rate + setDialOutPumpTargetRate( setDialysateFlowRate + FLOAT_TO_INT_WITH_ROUND( setUFRate ), MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + // Restart UF time accumulation for reference volume calculation + lastUFTimeStamp = getMSTimerCount(); + // Go to UF paused state + currentUFState = UF_RUNNING_STATE; + } + else + { + if ( MODE_TREA != currMode ) { - // restart UF time accumulation for reference volume calculation - lastUFTimeStamp = getMSTimerCount(); - // go to UF paused state - currentUFState = UF_RUNNING_STATE; + rejectReason = REQUEST_REJECT_REASON_NOT_IN_TREATMENT_MODE; } + else if ( TREATMENT_DIALYSIS_STATE != trtState ) + { + rejectReason = REQUEST_REJECT_REASON_INVALID_TREATMENT_STATE; + } + else if ( DIALYSIS_UF_STATE != currentDialysisState ) + { + rejectReason = REQUEST_REJECT_REASON_SALINE_BOLUS_IN_PROGRESS; + } + else + { + rejectReason = REQUEST_REJECT_REASON_UF_NOT_PAUSED; + } } + // Send response w/ reason code if rejected + sendUFPauseResumeResponse( result, rejectReason, currentUFState ); + // Send state data immediately for UI update + broadcastTreatmentTimeAndState(); + return result; } /*********************************************************************//** * @brief * The execDialysis function executes the Dialysis sub-mode state machine. - * @details - * Inputs : currentDialysisState - * Outputs : currentDialysisState + * @details Inputs: currentDialysisState + * @details Outputs: currentDialysisState * @return none *************************************************************************/ void execDialysis( void ) { - // check ultrafiltration accuracy during dialysis (even when ultrafiltration is paused). - checkUFAccuracy(); + // Check ultrafiltration max rate and accuracy during dialysis (even when ultrafiltration is paused). + checkUFAccuracyAndVolume(); - // dialysis state machine + // Dialysis state machine switch ( currentDialysisState ) { case DIALYSIS_START_STATE: - resStartVolume = getLoadCellWeightInGrams( LOAD_CELL_RESERVOIR_1_PRIMARY ); // always start dialysis w/ reservoir 1 currentDialysisState = DIALYSIS_UF_STATE; break; case DIALYSIS_UF_STATE: currentDialysisState = handleDialysisUltrafiltrationState(); break; - case DIALYSIS_SOLUTION_INFUSION_STATE: - currentDialysisState = handleDialysisSolutionInfusionState(); + case DIALYSIS_SALINE_BOLUS_STATE: + currentDialysisState = handleDialysisSalineBolusState(); break; default: - SET_ALARM_WITH_2_U32_DATA( ALARM_ID_SOFTWARE_FAULT, SW_FAULT_ID_DIALYSIS_INVALID_STATE, currentDialysisState ) + SET_ALARM_WITH_2_U32_DATA( ALARM_ID_HD_SOFTWARE_FAULT, SW_FAULT_ID_DIALYSIS_INVALID_STATE, currentDialysisState ) break; } + + // Publish saline bolus data at set interval (whether we are delivering one or not) + publishSalineBolusData(); } /*********************************************************************//** * @brief - * The handleDialysisUltrafiltrationState function handles the ultrafiltration \n + * The handleDialysisUltrafiltrationState function handles the ultrafiltration * state of the Dialysis state machine. - * @details - * Inputs : currentUFState - * Outputs : currentUFState + * @details Inputs: currentUFState + * @details Outputs: currentUFState * @return next Dialysis state. *************************************************************************/ static DIALYSIS_STATE_T handleDialysisUltrafiltrationState( void ) @@ -319,23 +556,28 @@ switch ( currentUFState ) { case UF_START_STATE: - currentUFState = handleUFStartState(); + currentUFState = handleUFStartState( &result ); break; case UF_PAUSED_STATE: - currentUFState = handleUFPausedState(); + currentUFState = handleUFPausedState( &result ); break; case UF_RUNNING_STATE: - currentUFState = handleUFRunningState(); + currentUFState = handleUFRunningState( &result ); break; - case UF_COMPLETED_OR_OFF_STATE: - currentUFState = handleUFCompletedOrOffState(); + case UF_OFF_STATE: + currentUFState = handleUFOffState( &result ); break; + case UF_COMPLETED_STATE: + currentUFState = handleUFCompletedState( &result ); + break; + default: - SET_ALARM_WITH_2_U32_DATA( ALARM_ID_SOFTWARE_FAULT, SW_FAULT_ID_DIALYSIS_INVALID_UF_STATE, currentUFState ) + SET_ALARM_WITH_2_U32_DATA( ALARM_ID_HD_SOFTWARE_FAULT, SW_FAULT_ID_DIALYSIS_INVALID_UF_STATE, currentUFState ) + currentUFState = UF_COMPLETED_STATE; break; } @@ -344,39 +586,60 @@ /*********************************************************************//** * @brief - * The handleDialysisSolutionInfusionState function handles the solution \n + * The handleDialysisSolutionInfusionState function handles the solution * infustion state of the Dialysis state machine. - * @details - * Inputs : TBD - * Outputs : TBD + * @details Inputs: currentSalineBolusState + * @details Outputs: currentSalineBolusState * @return next Dialysis state. *************************************************************************/ -static DIALYSIS_STATE_T handleDialysisSolutionInfusionState( void ) +static DIALYSIS_STATE_T handleDialysisSalineBolusState( void ) { - DIALYSIS_STATE_T result = DIALYSIS_SOLUTION_INFUSION_STATE; + DIALYSIS_STATE_T result = DIALYSIS_SALINE_BOLUS_STATE; - // TODO - + switch ( currentSalineBolusState ) + { + case SALINE_BOLUS_STATE_IDLE: + currentSalineBolusState = handleSalineBolusIdleState( &result ); + break; + case SALINE_BOLUS_STATE_WAIT_FOR_PUMPS_STOP: + currentSalineBolusState = handleSalineBolusWait4Pumps2Stop( &result ); + break; + + case SALINE_BOLUS_STATE_IN_PROGRESS: + currentSalineBolusState = handleSalineBolusInProgressState( &result ); + break; + + case SALINE_BOLUS_STATE_MAX_DELIVERED: + currentSalineBolusState = handleSalineBolusMaxDeliveredState( &result ); + break; + + default: + SET_ALARM_WITH_2_U32_DATA( ALARM_ID_HD_SOFTWARE_FAULT, SW_FAULT_ID_DIALYSIS_INVALID_SALINE_BOLUS_STATE, currentSalineBolusState ) + currentSalineBolusState = SALINE_BOLUS_STATE_MAX_DELIVERED; + break; + } + return result; } /*********************************************************************//** * @brief - * The handleUFStartState function handles the Start state of the \n + * The handleUFStartState function handles the Start state of the * ultrafiltration state machine. - * @details - * Inputs : maxUFVolumeML - * Outputs : if ultrafiltration prescribed, ultrafiltration time is + * @details Inputs: maxUFVolumeML + * @details Outputs: if ultrafiltration prescribed, ultrafiltration time is * initialized. + * @param dialysisState next dialysis state * @return next ultrafiltration state. *************************************************************************/ -static UF_STATE_T handleUFStartState( void ) +static UF_STATE_T handleUFStartState( DIALYSIS_STATE_T *dialysisState ) { UF_STATE_T result; if ( maxUFVolumeML < NEARLY_ZERO ) { - result = UF_COMPLETED_OR_OFF_STATE; + result = UF_OFF_STATE; } else { @@ -390,24 +653,43 @@ /*********************************************************************//** * @brief - * The handleUFPausedState function handles the Paused state of the \n + * The handleUFPausedState function handles the Paused state of the * ultrafiltration state machine. - * @details - * Inputs : none - * Outputs : if ultrafiltration resumption requested, UF time is set to resume. + * @details Inputs: none + * @details Outputs: if ultrafiltration resumption requested, UF time is set to resume. + * @param dialysisState next dialysis state * @return next ultrafiltration state. *************************************************************************/ -static UF_STATE_T handleUFPausedState( void ) +static UF_STATE_T handleUFPausedState( DIALYSIS_STATE_T *dialysisState ) { UF_STATE_T result = UF_PAUSED_STATE; - // calculate UF volumes and provide to dialysate outlet pump controller + // Calculate UF volumes and provide to dialysate outlet pump controller updateUFVolumes(); - // TODO - test code - remove later - if ( TRUE == isStopButtonPressed() ) + // Handle saline bolus start request from user + if ( TRUE == salineBolusStartRequested ) { - resumeUF(); + salineBolusAutoResumeUF = FALSE; + // Go to saline bolus state if we can + if ( SALINE_BOLUS_STATE_IDLE == currentSalineBolusState ) + { + *dialysisState = DIALYSIS_SALINE_BOLUS_STATE; + } + else + { + salineBolusStartRequested = FALSE; + } + } + // Handle auto-resume after saline bolus + else if ( TRUE == salineBolusAutoResumeUF ) + { + salineBolusAutoResumeUF = FALSE; + // Set outlet pump to dialysate rate + set UF rate + setDialOutPumpTargetRate( setDialysateFlowRate + FLOAT_TO_INT_WITH_ROUND( setUFRate ), MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + // Restart UF time accumulation for reference volume calculation + lastUFTimeStamp = getMSTimerCount(); + // Resume UF result = UF_RUNNING_STATE; } @@ -416,124 +698,473 @@ /*********************************************************************//** * @brief - * The handleUFRunningState function handles the Running state of the \n + * The handleUFRunningState function handles the Running state of the * ultrafiltration state machine. - * @details - * Inputs : ms timer, lastUFTimeStamp - * Outputs : UF timer incremented, UF volumes updated and provided to DPo \n + * @details Inputs: ms timer, lastUFTimeStamp + * @details Outputs: UF timer incremented, UF volumes updated and provided to DPo * pump controller. + * @param dialysisState next dialysis state * @return next ultrafiltration state. *************************************************************************/ -static UF_STATE_T handleUFRunningState( void ) +static UF_STATE_T handleUFRunningState( DIALYSIS_STATE_T *dialysisState ) { UF_STATE_T result = UF_RUNNING_STATE; U32 newTime = getMSTimerCount(); U32 msSinceLast = calcTimeBetween( lastUFTimeStamp, newTime ); - // update UF time + // Update UF time uFTimeMS += msSinceLast; lastUFTimeStamp = newTime; - // calculate UF volumes and provide to dialysate outlet pump controller + // Update UF ref volume in UF running state only + refUFVolume += ( ( (F32)msSinceLast / MS_PER_SECOND ) / SEC_PER_MIN ) * setUFRate; + + // Calculate UF volumes and provide to dialysate outlet pump controller updateUFVolumes(); - // if we've reached target UF volume, UF is complete - if ( measUFVolume >= maxUFVolumeML ) + // If we have reached target UF volume, UF is complete + if ( refUFVolume >= maxUFVolumeML ) { - result = UF_COMPLETED_OR_OFF_STATE; + result = UF_COMPLETED_STATE; } + // Handle saline bolus start request from user + else if ( TRUE == salineBolusStartRequested ) + { + if ( SALINE_BOLUS_STATE_IDLE == currentSalineBolusState ) + { + // Since we were doing UF prior to saline bolus, we want to auto-resume when done + salineBolusAutoResumeUF = TRUE; + // Go to UF paused state + result = UF_PAUSED_STATE; + // Go to saline bolus state + *dialysisState = DIALYSIS_SALINE_BOLUS_STATE; + } + else + { + salineBolusStartRequested = FALSE; + } + } - // TODO - test code - remove later - if ( TRUE == isStopButtonPressed() ) + return result; +} + +/*********************************************************************//** + * @brief + * The handleUFCompletedOrOffState function handles the UF Off state + * of the ultrafiltration state machine. + * @details Inputs: none + * @details Outputs: UF volumes updated and provided to DPo pump controller. + * @param dialysisState next dialysis state + * @return next ultrafiltration state + *************************************************************************/ +static UF_STATE_T handleUFOffState( DIALYSIS_STATE_T *dialysisState ) +{ + UF_STATE_T result = UF_OFF_STATE; + + // Calculate UF volumes and provide to dialysate outlet pump controller + updateUFVolumes(); + + // Handle saline bolus start request from user + if ( TRUE == salineBolusStartRequested ) { - pauseUF(); - result = UF_PAUSED_STATE; + salineBolusAutoResumeUF = FALSE; + // Go to saline bolus state + if ( SALINE_BOLUS_STATE_IDLE == currentSalineBolusState ) + { + *dialysisState = DIALYSIS_SALINE_BOLUS_STATE; + } + else + { + salineBolusStartRequested = FALSE; + } } return result; } /*********************************************************************//** * @brief - * The handleUFCompletedOrOffState function handles the UF Completed or Off \n - * state of the ultrafiltration state machine. - * @details - * Inputs : none - * Outputs : UF volumes updated and provided to DPo pump controller. + * The handleUFCompletedState function handles the UF Completed + * state of the ultrafiltration state machine. This is a terminal state. + * @details Inputs: none + * @details Outputs: UF volumes updated and provided to DPo pump controller. + * @param dialysisState next dialysis state * @return next ultrafiltration state *************************************************************************/ -static UF_STATE_T handleUFCompletedOrOffState( void ) +static UF_STATE_T handleUFCompletedState( DIALYSIS_STATE_T *dialysisState ) { - UF_STATE_T result = UF_COMPLETED_OR_OFF_STATE; + UF_STATE_T result = UF_COMPLETED_STATE; - // calculate UF volumes and provide to dialysate outlet pump controller + // Calculate UF volumes and provide to dialysate outlet pump controller updateUFVolumes(); - // TODO - test code - remove later - if ( TRUE == isStopButtonPressed() ) + // Handle saline bolus start request from user + if ( TRUE == salineBolusStartRequested ) { - // do nothing + salineBolusAutoResumeUF = FALSE; + // Go to saline bolus state + if ( SALINE_BOLUS_STATE_IDLE == currentSalineBolusState ) + { + *dialysisState = DIALYSIS_SALINE_BOLUS_STATE; + } + else + { + salineBolusStartRequested = FALSE; + } } return result; } /*********************************************************************//** * @brief - * The checkUFAccuracy function checks ultrafiltration accuracy for the last \n - * minute and triggers an alarm if out of spec. - * @details - * Inputs : uFAccuracyCheckTimerCtr, lastUFVolumeChecked, measUFVolume - * Outputs : uFAccuracyCheckTimerCtr, lastUFVolumeChecked - * @return none + * The handleSalineBolusIdleState function handles the idle state of the + * saline bolus state machine. + * @details Inputs: none + * @details Outputs: + * @param dialysisState next dialysis state + * @return next saline bolus state *************************************************************************/ -static void checkUFAccuracy( void ) +static SALINE_BOLUS_STATE_T handleSalineBolusIdleState( DIALYSIS_STATE_T *dialysisState ) { - // check UF accuracy at 1 hour intervals - if ( ++uFAccuracyCheckTimerCtr >= UF_ACCURACY_CHECK_INTERVAL ) + SALINE_BOLUS_STATE_T result = SALINE_BOLUS_STATE_IDLE; + + // Handle saline bolus start request from user + if ( TRUE == salineBolusStartRequested ) { - F32 uFMeasRatePerHr = measUFVolume - lastUFVolumeChecked; - F32 uFSetRatePerHr = ( setUFRate * (F32)MIN_PER_HOUR ); - F32 uFRateError = FABS( uFSetRatePerHr - uFMeasRatePerHr ); + salineBolusStartRequested = FALSE; + // Cmd all pumps to stop +#ifndef RUN_PUMPS_OPEN_LOOP + setBloodPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + setDialInPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); + setDialOutPumpTargetRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); +#else + setBloodPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); + setDialInPumpTargetFlowRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); + setDialOutPumpTargetRate( 0, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); +#endif + // Begin saline bolus + result = SALINE_BOLUS_STATE_WAIT_FOR_PUMPS_STOP; + } - // check UF accuracy - if ( uFRateError > (F32)MAX_UF_ACCURACY_ERROR_ML_PER_HR ) + return result; +} + +/*********************************************************************//** + * @brief + * The handleSalineBolusWait4Pumps2Stop function handles the wait for pumps + * to stop state of the saline bolus state machine. + * @details Inputs: none + * @details Outputs: + * @param dialysisState next dialysis state + * @return next saline bolus state + *************************************************************************/ +static SALINE_BOLUS_STATE_T handleSalineBolusWait4Pumps2Stop( DIALYSIS_STATE_T *dialysisState ) +{ + SALINE_BOLUS_STATE_T result = SALINE_BOLUS_STATE_WAIT_FOR_PUMPS_STOP; + + if ( ( FALSE == isBloodPumpRunning() ) && ( FALSE == isDialInPumpRunning() ) && ( FALSE == isDialOutPumpRunning() ) ) + { + // Reset bolus data before we start + bolusSalineVolumeDelivered = 0.0; + bolusSalineVolumeDelivered_Safety = 0.0; + bolusSalineMotorCount = 0; + bolusSalineLastMotorCount = getBloodPumpMotorCount(); + bolusSalineLastVolumeTimeStamp = getMSTimerCount(); + + // Bypass dialyzer + setValvePosition( VDI, VALVE_POSITION_C_CLOSE ); + setValvePosition( VDO, VALVE_POSITION_C_CLOSE ); + // Switch to saline bag + setValvePosition( VBA, VALVE_POSITION_C_CLOSE ); + // Start blood pump at saline bolus rate +#ifndef RUN_PUMPS_OPEN_LOOP + setBloodPumpTargetFlowRate( SALINE_BOLUS_FLOW_RATE, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); +#else + setBloodPumpTargetFlowRate( SALINE_BOLUS_FLOW_RATE, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); +#endif + // Start dialysate inlet pump at re-circ rate +#ifndef RUN_PUMPS_OPEN_LOOP + setDialInPumpTargetFlowRate( DIALYSATE_FLOW_RATE_FOR_RECIRC, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_CLOSED_LOOP ); +#else + setDialInPumpTargetFlowRate( DIALYSATE_FLOW_RATE_FOR_RECIRC, MOTOR_DIR_FORWARD, PUMP_CONTROL_MODE_OPEN_LOOP ); +#endif + // Begin saline bolus + result = SALINE_BOLUS_STATE_IN_PROGRESS; + } + + return result; +} + +/*********************************************************************//** + * @brief + * The handleSalineBolusInProgressState function handles the in-progress state of the + * saline bolus state machine. + * @details Inputs: none + * @details Outputs: + * @param dialysisState next dialysis state + * @return next saline bolus state + *************************************************************************/ +static SALINE_BOLUS_STATE_T handleSalineBolusInProgressState( DIALYSIS_STATE_T *dialysisState ) +{ + SALINE_BOLUS_STATE_T result = SALINE_BOLUS_STATE_IN_PROGRESS; + BOOL errorFound = FALSE; + F32 timeSinceLastVolumeUpdateMin = (F32)calcTimeSince( bolusSalineLastVolumeTimeStamp ) / (F32)( MS_PER_SECOND * SEC_PER_MIN ); + F32 bolusTargetVolume = (F32)getTreatmentParameterU32( TREATMENT_PARAM_SALINE_BOLUS_VOLUME ); + F32 bldFlowRate = getMeasuredBloodFlowRate(); // TODO - should I use raw flow instead of filtered here??? + F32 volSinceLastUpdateMl = bldFlowRate * timeSinceLastVolumeUpdateMin; + U32 bldPumpMotorCount = getBloodPumpMotorCount(); + U32 bldPumpMotorDelta = u32DiffWithWrap( bolusSalineLastMotorCount, bldPumpMotorCount ); + + // Update saline bolus volumes + bolusSalineLastVolumeTimeStamp = getMSTimerCount(); + bolusSalineVolumeDelivered += volSinceLastUpdateMl; + totalSalineVolumeDelivered += volSinceLastUpdateMl; + bolusSalineMotorCount += bldPumpMotorDelta; + bolusSalineLastMotorCount = bldPumpMotorCount; + bolusSalineVolumeDelivered_Safety = ( (F32)bolusSalineMotorCount * VOLUME_PER_BP_MOTOR_REV_ML ); // TODO - include upstream pressure compensation to this calc + +#ifndef DISABLE_SALINE_BOLUS_CHECKS + // TODO - check for empty saline bag + if ( 0 ) + { + SET_ALARM_WITH_1_F32_DATA( ALARM_ID_EMPTY_SALINE_BAG, 0.0 ); // TODO - give data supporting empty bag detection + errorFound = TRUE; + result = SALINE_BOLUS_STATE_IDLE; + } +#endif + + // Determine if we have reached maximum saline delivery volume + if ( ( totalSalineVolumeDelivered >= (F32)MAX_SALINE_VOLUME_DELIVERED ) ) + { + result = SALINE_BOLUS_STATE_MAX_DELIVERED; + } + else + { + // Determine if bolus is complete + if ( bolusSalineVolumeDelivered >= bolusTargetVolume ) { - SET_ALARM_WITH_2_F32_DATA( ALARM_ID_UF_RATE_ACCURACY_ERROR, uFSetRatePerHr, uFMeasRatePerHr ); + // If safety thinks we have under-delivered the bolus, throw a fault + if ( bolusSalineVolumeDelivered_Safety < ( bolusTargetVolume * MIN_SALINE_BOLUS_VOLUME_PCT ) ) + { +#ifndef DISABLE_SALINE_BOLUS_CHECKS + SET_ALARM_WITH_2_F32_DATA( ALARM_ID_SALINE_BOLUS_VOLUME_CHECK_FAILURE, bolusTargetVolume, bolusSalineVolumeDelivered_Safety ); + errorFound = TRUE; +#endif + } + result = SALINE_BOLUS_STATE_IDLE; } - // reset for next check + // User is aborting saline bolus + else if ( TRUE == salineBolusAbortRequested ) + { + salineBolusAbortRequested = FALSE; + result = SALINE_BOLUS_STATE_IDLE; + } + // Determine if safety thinks we have over-delivered the bolus + else if ( bolusSalineVolumeDelivered_Safety > ( bolusTargetVolume * MAX_SALINE_BOLUS_VOLUME_PCT ) ) + { +#ifndef DISABLE_SALINE_BOLUS_CHECKS + SET_ALARM_WITH_2_F32_DATA( ALARM_ID_SALINE_BOLUS_VOLUME_CHECK_FAILURE, bolusTargetVolume, bolusSalineVolumeDelivered_Safety ); + errorFound = TRUE; + result = SALINE_BOLUS_STATE_IDLE; +#endif + } + } + + // Are we stopping the bolus? + if ( result != SALINE_BOLUS_STATE_IN_PROGRESS ) + { + // Hard stop blood and dialysate pumps + signalBloodPumpHardStop(); + signalDialInPumpHardStop(); + // Send last saline bolus data + bolusSalineVolumeDelivered = 0.0; + salineBolusBroadcastTimerCtr = SALINE_BOLUS_DATA_PUB_INTERVAL; + publishSalineBolusData(); + // Dialysis back to UF state + *dialysisState = DIALYSIS_UF_STATE; + // End dialyzer bypass and resume dialysis if no alarms triggered + if ( FALSE == errorFound ) + { + // Resume UF if appropriate + if ( TRUE == salineBolusAutoResumeUF ) + { + currentUFState = UF_RUNNING_STATE; + } + // Resume dialysis + transitionToDialysis(); + } + } + + return result; +} + +/*********************************************************************//** + * @brief + * The handleSalineBolusMaxDeliveredState function handles the max saline delivered + * state of the saline bolus state machine. This is a terminal state. + * @details Inputs: none + * @details Outputs: + * @param dialysisState next dialysis state + * @return next saline bolus state + *************************************************************************/ +static SALINE_BOLUS_STATE_T handleSalineBolusMaxDeliveredState( DIALYSIS_STATE_T *dialysisState ) +{ + SALINE_BOLUS_STATE_T result = SALINE_BOLUS_STATE_MAX_DELIVERED; + + // This is a terminal state for a given treatment - no more saline may be delivered to patient + // If we get here, pop back to UF + *dialysisState = DIALYSIS_UF_STATE; + + return result; +} + +/*********************************************************************//** + * @brief + * The publishSalineBolusData function handles the max saline delivered + * state of the saline bolus state machine. This is a terminal state. + * @details Inputs: none + * @details Outputs: + * @param dialysisState next dialysis state + * @return next saline bolus state + *************************************************************************/ +static void publishSalineBolusData( void ) +{ + if ( ++salineBolusBroadcastTimerCtr >= SALINE_BOLUS_DATA_PUB_INTERVAL ) + { + SALINE_BOLUS_DATA_PAYLOAD_T data; + + data.maxSalineVolumeMl = MAX_SALINE_VOLUME_DELIVERED; + data.cumSalineVolumeMl = totalSalineVolumeDelivered; + data.bolSalineVolumeMl = bolusSalineVolumeDelivered; + broadcastSalineBolusData( data ); + salineBolusBroadcastTimerCtr = 0; + } +} + +/*********************************************************************//** + * @brief + * The checkUF function checks ultrafiltration accuracy for the last + * hour and checks total UF volume. Triggers an alarm if out of spec. + * @details Inputs: uFAccuracyCheckTimerCtr, lastUFVolumeChecked, measUFVolume + * @details Outputs: uFAccuracyCheckTimerCtr, lastUFVolumeChecked + * @return none + *************************************************************************/ +static void checkUFAccuracyAndVolume( void ) +{ + F32 uFMeasRate = measUFVolume - lastUFVolumeChecked; // Volumes are at start/end of 1 hour period, so implied rate is per hour + + // Check UF rate over last hour + if ( uFMeasRate > MAX_UF_RATE_ML_PER_HOUR ) + { +#ifndef DISABLE_UF_ALARMS + SET_ALARM_WITH_1_F32_DATA( ALARM_ID_UF_RATE_TOO_HIGH_ERROR, uFMeasRate ); +#endif + } + // Increment timer and see if time to start another 1 hour check period + if ( ++uFAccuracyCheckTimerCtr >= UF_ACCURACY_CHECK_INTERVAL ) + { + // Reset for next check interval lastUFVolumeChecked = measUFVolume; uFAccuracyCheckTimerCtr = 0; } - // check total UF volume error - if ( ( FABS( refUFVolume - measUFVolume ) ) >= (F32)MAX_UF_ACCURACY_ERROR_ML ) + // Check total UF volume error + if ( ( fabs( refUFVolume - measUFVolume ) ) >= (F32)MAX_UF_ACCURACY_ERROR_ML ) { +#ifndef DISABLE_UF_ALARMS SET_ALARM_WITH_2_F32_DATA( ALARM_ID_UF_VOLUME_ACCURACY_ERROR, refUFVolume, measUFVolume ); +#endif } } /*********************************************************************//** * @brief - * The updateUFVolumes function updates the ultrafiltration volumes based on \n - * set UF rate, latest UF elapsed time, and the latest load cell weight for the \n - * currently used reservoir. Updated UF volumes are then sent to the dialysate \n + * The updateUFVolumes function updates the ultrafiltration volumes based on + * set UF rate, latest UF elapsed time, and the latest load cell weight for the + * currently used reservoir. Updated UF volumes are then sent to the dialysate * outlet pump controller. - * @details - * Inputs : setUFRate, uFTimeMS, load cell weight - * Outputs : refUFVolume, measUFVolume + * @details Inputs: setUFRate, uFTimeMS, load cell weight + * @details Outputs: refUFVolume, measUFVolume * @return none *************************************************************************/ static void updateUFVolumes( void ) { - F32 latestResVolume = getLoadCellWeightInGrams( LOAD_CELL_RESERVOIR_1_PRIMARY ); // TODO - just res 1 for now - add reservoir switching, mgmt later. + DG_RESERVOIR_ID_T activeRes = getDGActiveReservoir(); + F32 latestResVolume = getReservoirWeightSmallFilter( activeRes ); +#ifndef DISABLE_UF_ALARMS + F32 deltaVolume = latestResVolume - resFinalVolume[ activeRes ]; - // calculate UF volumes and provide to dialysate outlet pump controller - refUFVolume = ( ( (F32)uFTimeMS / MS_PER_SECOND ) / SEC_PER_MIN ) * setUFRate; - measUFVolume = measUFVolumeFromPriorReservoirs + ( latestResVolume - resStartVolume ); - setDialOutUFVolumes( refUFVolume, measUFVolume ); + // ensure volume change is not too excessive - indication that load cell was impacted by some kind of shock + if ( fabs(deltaVolume) > MAX_ACTIVE_LOAD_CELL_CHANGE_G ) + { + ALARM_ID_T deltaAlarm = ( getDGActiveReservoir() == DG_RESERVOIR_1 ? ALARM_ID_HD_LOAD_CELL_ACCELERATION_RES_1_ALARM : ALARM_ID_HD_LOAD_CELL_ACCELERATION_RES_2_ALARM ); + SET_ALARM_WITH_1_F32_DATA( deltaAlarm, deltaVolume ); + } + else +#endif + { + // Calculate UF volumes and provide to dialysate outlet pump controller + measUFVolume = measUFVolumeFromPriorReservoirs + ( latestResVolume - resStartVolume[ activeRes ] ); + resFinalVolume[ activeRes ] = latestResVolume; + setDialOutUFVolumes( refUFVolume, measUFVolume ); + } } -/**@}*/ +/*********************************************************************//** + * @brief + * The setStartReservoirVolume function updates the baseline volume of the + * next reservoir to be drawn from before it is switched to (i.e. while it + * is the inactive reservoir) in order to get a more stable volume. + * @details Inputs: active reservoir, load cell reading from inactive reservoir + * @details Outputs: resStartVolume[] + * @param reservoirID reservoir ID to update the baseline volume. + * @return none + *************************************************************************/ +void setStartReservoirVolume( DG_RESERVOIR_ID_T reservoirID ) +{ + F32 resVolume = getReservoirWeightLargeFilter( reservoirID ); + // Set starting baseline volume for next reservoir before we switch to it + resStartVolume[ reservoirID ] = resVolume; + resFinalVolume[ reservoirID ] = resVolume; +} +/*********************************************************************//** + * @brief + * The signalReservoirsSwitched function informs this module that the + * reservoirs have been switched. The UF volume from prior reservoirs is + * tentatively added to with a load cell reading of the inactive reservoir. + * @details Inputs: resFinalVolume[], resStartVolume[] + * @details Outputs: measUFVolumeFromPriorReservoirs + * @return none + *************************************************************************/ +void signalReservoirsSwitched( void ) +{ + DG_RESERVOIR_ID_T inactiveRes = getDGInactiveReservoir(); + + // Update UF volume from prior reservoirs per tentative res volume for last reservoir + measUFVolumeFromPriorReservoirs += ( resFinalVolume[ inactiveRes ] - resStartVolume[ inactiveRes ] ); +} + +/*********************************************************************//** + * @brief + * The setFinalReservoirVolume function updates the UF volume from prior reservoirs + * with a more stable final reservoir volume of the prior reservoir after it + * had a moment to settle. + * @details Inputs: active reservoir, load cell reading from inactive reservoir + * @details Outputs: measUFVolumeFromPriorReservoirs, resFinalVolume[], resStartVolume[] + * @return none + *************************************************************************/ +void setFinalReservoirVolume( void ) +{ + DG_RESERVOIR_ID_T inactiveRes = getDGInactiveReservoir(); + F32 resVolume = getReservoirWeightLargeFilter( inactiveRes ); + + // Update UF volume from prior reservoirs per final res volume for last reservoir a bit after we have switched and reservoir has settled + measUFVolumeFromPriorReservoirs -= ( resFinalVolume[ inactiveRes ] - resStartVolume[ inactiveRes ] ); + resFinalVolume[ inactiveRes ] = resVolume; + measUFVolumeFromPriorReservoirs += ( resFinalVolume[ inactiveRes ] - resStartVolume[ inactiveRes ] ); +} + +/**@}*/