Index: firmware/App/Controllers/BalancingChamber.c =================================================================== diff -u -r7d24ef2e6a4130b3a049e6106a0371fc6503271f -r7a9cfc7590be84e1c4af6a04ca92c598d49cf9de --- firmware/App/Controllers/BalancingChamber.c (.../BalancingChamber.c) (revision 7d24ef2e6a4130b3a049e6106a0371fc6503271f) +++ firmware/App/Controllers/BalancingChamber.c (.../BalancingChamber.c) (revision 7a9cfc7590be84e1c4af6a04ca92c598d49cf9de) @@ -1,29 +1,35 @@ /************************************************************************** * -* Copyright (c) 2024-2024 Diality Inc. - All Rights Reserved. +* Copyright (c) 2025-2026 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 BalancingChamber.c * -* @author (last) Vinayakam Mani -* @date (last) 24-Oct-2024 +* @author (last) Jashwant Gantyada +* @date (last) 29-Jul-2026 * * @author (original) Vinayakam Mani -* @date (original) 24-Oct-2024 +* @date (original) 28-Jan-2025 * ***************************************************************************/ +#include // For sqrtf + #include "BalancingChamber.h" #include "Conductivity.h" #include "ConcentratePumps.h" #include "DialysatePumps.h" +#include "DryBiCart.h" #include "FpgaDD.h" #include "Heaters.h" -#include "ModeStandby.h" +#include "Level.h" +#include "MessageSupport.h" #include "Messaging.h" -#include "OperationModes.h" +#include "MixingControl.h" +#include "ModeGenDialysate.h" +#include "ModeStandby.h" #include "Pressure.h" #include "TaskGeneral.h" #include "TDInterface.h" @@ -40,13 +46,35 @@ #define BAL_CHAMBER_DATA_PUBLISH_INTERVAL ( 250 / TASK_GENERAL_INTERVAL ) ///< Interval (ms/task time) at which the balancing chamber data published. #define BAL_CHAMBER_FILL_PRES_DROP_MS ( 200 / TASK_GENERAL_INTERVAL ) ///< Time (ms/tasktime) to confirm the balancing chamber filling started and corrosponding valves opened. -#define BAL_CHAMBER_FILL_COMPLETE_MS ( 300 / TASK_GENERAL_INTERVAL ) ///< Time (ms/tasktime) to confirm the balancing chamber fill completed and pressure is within range +#define BAL_CHAMBER_FILL_COMPLETE_MS ( 100 / TASK_GENERAL_INTERVAL ) ///< Time (ms/tasktime) to confirm the balancing chamber fill completed and pressure is within range +#define SPENT_FILL_COMPLETE_QD_LOW_RISE_MAX_MLPM 300.0F ///< For Qd <= 300 mL/min (Diener 1000). +#define SPENT_FILL_COMPLETE_DP_RISE_PSIG 0.5F ///< Minimum 100 ms spent pressure rise (current minus n-2) to count as a rise hit at low Qd. +#define SPENT_FILL_COMPLETE_DP_RISE_HIGH_QD_PSIG 3.0F ///< Minimum spent pressure rise for Diener 2000 or Qd > 300 mL/min. +#define SPENT_FILL_SLOPE_SPENT_PRESSURE_HIGH_PSIG 2.0F ///< Above this spent pressure rise, only one rise hit is required. +#define SPENT_FILL_SLOPE_MAX_RISE_HITS 2 ///< Rise hits required when Qd <= 150 in the low spent-pressure band. +#define SPENT_FILL_DETECT_COUNT_TOL_PCT 1.0F ///< Allowed detection timing tolerance as a fraction of expected BC switching count. +#define SPENT_DIFF_COUNT_ZERO 0 ///< Zero count difference for spent side fill comparing target count +#define D48_SPEED_ADJUST_FACTOR 0.5F ///< D48 speed adjustment factor ( 50% of speed adjustment = 0.5) +#define D48_SPEED_RANGE_LIMIT 0.25F ///< D48 speed adjustment range check limit ( D48 speed can vary +/-25% of initial calculated speed) +#define BICARB_CHAMBER_PERIODIC_FILL_TIME ( 1 * SEC_PER_MIN * \ + ( MS_PER_SECOND / TASK_GENERAL_INTERVAL ) ) ///< Periodic bicarb chamber fill request 60 sec x 20 = 1200 +#define NUMBER_OF_CYCLES_BASED_ON_FLOWRATE 4 ///< NUmber of Balancing Chamber cycles required to update the new Qd rate. +#define BAL_CHAMBER_FILL_TIMEOUT_FACTOR 3.0F ///< Balancing Chamber fill timeout factor (300% of observed fill count) +#define COMP_SLOPE -0.000376F ///< Balancing chamber temperature compensation slope factor +#define COMP_INTERCEPT 1.007269F ///< Balancing chamber temperature compensation intercept factor +/// Bicarb (D10) pump speed from instantaneous mix volume: speed = 240 - sqrt(230400 - 96000*v)/2 +#define BC_BICARB_SPEED_OFFSET_MLPM 240.0F ///< Bicarb speed formula offset (mL/min). +#define BC_BICARB_SPEED_DISC_CONST 230400.0F ///< Bicarb speed formula discriminant constant. +#define BC_BICARB_SPEED_DISC_VOL_COEF 96000.0F ///< Bicarb speed formula volume coefficient. +#define BC_ACID_SPEED_OFFSET_MLPM 160.0F ///< Acid speed formula offset (mL/min). +#define BC_ACID_SPEED_DISC_CONSTANT 102400.0F ///< Acid speed formula discriminant constant. +#define BC_ACID_SPEED_DISC_VOL_COEF 96000.0F ///< Acid speed formula volume coefficient. /// Payload record structure for balancing chamber switch only request typedef struct { - U32 startStop; ///< balancing chamber switching only start:1 and stop: 0 - F32 flowrate; ///< dialysate flowrate in ml/min + U32 startStop; ///< Balancing chamber switching only start:1 and stop: 0 + F32 flowrate; ///< Dialysate flowrate in ml/min } BC_SWITCHING_ONLY_START_CMD_PAYLOAD_T; // ********** private data ********** @@ -57,12 +85,14 @@ static U32 balChamberValveClosePeriod; ///< Close balancing chamber valves with the defined time prior switching state. static U32 currentBalChamberSwitchingCounter; ///< Counter (in task interval) to monitor the timing spent during balancing chamber fill/drain operation. static BOOL isBalChamberFillInProgress; ///< Flag indicating balancing chamber fill/drain is in progress. -static BOOL isPressureStalbilizedDuringFill; ///< Flag indicating that the pressure is stablized due to fill complete. +static BOOL isPressureStabilizedDuringFill; ///< Flag indicating that the pressure is stabilized due to fill complete. static BAL_CHAMBER_SW_STATE_T balChamberSWState; ///< Current balancing chamber switching state ( state 1 or state 2). static U32 balChamberDataPublicationTimerCounter; ///< Used to schedule balancing chamber data publication to CAN bus. static U32 balChamberFillPressureDropCounter; ///< Counter to check balancing chamber valves opened and there by pressure drop is seen. static OVERRIDE_U32_T balChamberDataPublishInterval; ///< Balancing chamber data publish interval. -static BOOL balanceChamberSwitchingOnly; ///< Balancing chamber switching without any pressure check and dosing delivery. +static BOOL balanceChamberSwitchingOnly; ///< Balancing chamber switching without any pressure check and dosing delivery +static BOOL balanceChamberSwitchingOnlyOnRequested; ///< Flag indicating that a request was made to activate balancing chamber switching only +static BOOL balanceChamberSwitchingOnlyOffRequested; ///< Flag indicating that a request was made to deactivate balancing chamber switching only static BOOL isPressureDroppedDuringFill; ///< Flag indicating that the pressure is dropped due to BC fill (state 1 or state 2) in progress condition. static BOOL isFirstCycleBCSwitchingCompleted; ///< Flag indicating that first time balancing chamber swithcing is done to trigger alarms from next cycle onwards. static U32 balChamberFillCompleteStablePressureCounter; ///< Counter to check balancing chamber fill complete and stable pressure is met. @@ -71,18 +101,52 @@ static F32 lastTdDialysateFlowrate; ///< Previous TD dialysate flow rate static F32 freshDialPressure; ///< Fresh side dialysate pressure static F32 spentDialPressure; ///< Spent side dialysate pressure +static U32 currentBalChamberFillCounter; ///< Counter (in task interval) to monitor the timing spent for the spent side fill operation. +static U32 balChamberFillTimeoutCount; ///< Timeout count (in task interval) to detect BC fill timeout. +static S32 diffSpentFillCompleteCount; ///< Difference between spent target fill to actual fill count +static BOOL isSpentFillComplete; ///< Flag indicating spent side fill complete. +static BOOL isFreshSideValvesClosed; ///< Flag indicating fresh-side BC valves are closed while spent side may still be filling. +static F32 lastPrevSpentDialPressure; ///< Low-Qd slope: spent pressure last sample of dosing (tick before VALVES_CLOSE); then n-2 in VC. +static F32 prevSpentDialPressure; ///< Spent pressure previous sample (n-1) during VALVES_CLOSE for low-Qd slope detection. +static U32 spentFillRiseHitCount; ///< Low-Qd slope: counted rise hits (only incremented when in timing window). +static U32 spentFillRiseMissCounter; ///< Missed samples after a rise hit before resetting hit count. +static BOOL isBalChamberSwitchingActive; ///< Flag indicating balancing chamber switching is active or not. +static BOOL isBalChamberSwitchingOnRequested; ///< Flag indicating that a request was made to activate balancing chamber switching. +static BOOL isBalChamberSwitchingOffRequested; ///< Flag indicating that a request was made to deactivate balancing chamber switching. +static F32 pendingTdDialysateFlowrate; ///< Pending TD dialysate flow rate; applied at FillEnd after a BC switch completes. +static BOOL isBalChamberSwitchingPeriodUpdatePending; ///< BC switching period update pending apply at fill end. +static U32 bcSwitchingBasedOnClosedPeriodCounter; ///< Valve-close segments remaining before first-cycle relaxations clear after Qd timing apply. +static F32 balancingError; ///< Balancing error that has been calculated during balancing chamber switching. +//TODO: remove later once level sensor working +static U32 bicarbChamberPeriodicFillCounter; +// Balancing chamber state change tracker +static BAL_CHAMBER_EXEC_STATE_T prevBalChamberState; ///< Balancing chamber Previous State tracking variable + // ********** private function prototypes ********** static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1FillStart( void ); static BAL_CHAMBER_EXEC_STATE_T handleBalChamberConcentrateControl(void); -static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1ValvesClose( void ); +static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1FillDetectComplete( void ); static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1FillEnd(void); static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2FillStart( void ); -static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2ValvesClose( void ); +static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2FillDetectComplete( void ); static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2FillEnd(void); +static BAL_CHAMBER_EXEC_STATE_T handleBalChamberStateIdle( void ); static void publishBalChamberData( void ); static U32 getBalChamberDataPublishInterval( void ); +static void checkSpentFillComplete( F32 spentDialPressure ); +static BOOL isSpentFillCompleteByPressure( F32 spentDialPressure, F32 qdMlpm ); +static void applyBalChamberSwitchingPeriod( F32 tdDialysateFlowrate ); +static BOOL isBalChamberTimeBasedSwitching( void ); +static void scheduleFirstCycleRelaxAfterQdApply( void ); +static void valveControlForBCState1FreshSideClose( void ); +static void valveControlForBCState2FreshSideClose( void ); +static void closeFreshSideValvesWhenFillComplete( void ); +static void calculateBalancingChamberError( void ); +static F32 getBicarbConcentratePumpSpeedMlMin( F32 bicarbVolumeMl ); +static F32 getAcidConcentratePumpSpeedMlMin( F32 acidVolumeMl ); +static void startBalChamberConcPumpDosing( F32 acidVolume, F32 bicarbVolume ); /*********************************************************************//** * @brief @@ -93,7 +157,7 @@ *************************************************************************/ void initBalanceChamber( void ) { - balChamberExecState = BAL_CHAMBER_STATE_START; + balChamberExecState = BAL_CHAMBER_STATE_IDLE; balChamberSWState = BAL_CHAMBER_SW_STATE1; balChamberSwitchingFreq.data = 0.0F; balChamberSwitchingFreq.ovData = 0.0F; @@ -112,11 +176,12 @@ bicarbDoseVolume.ovInitData = 0.0F; bicarbDoseVolume.override = OVERRIDE_RESET; balanceChamberSwitchingOnly = FALSE; + balanceChamberSwitchingOnlyOnRequested = FALSE; + balanceChamberSwitchingOnlyOffRequested = FALSE; balChamberSwitchingPeriod = 0; balChamberValveClosePeriod = 0; isBalChamberFillInProgress = FALSE; - currentBalChamberSwitchingCounter = 0; - isPressureStalbilizedDuringFill = FALSE; + isPressureStabilizedDuringFill = FALSE; lastTdDialysateFlowrate = 0.0F; balChamberDataPublicationTimerCounter = 0; balChamberFillPressureDropCounter = 0; @@ -125,10 +190,121 @@ isPressureDroppedDuringFill = FALSE; freshDialPressure = 0.0F; spentDialPressure = 0.0F; + balChamberFillTimeoutCount = 0; + diffSpentFillCompleteCount = 0; + lastPrevSpentDialPressure = 0.0F; + prevSpentDialPressure = 0.0F; + currentBalChamberSwitchingCounter = 0; + currentBalChamberFillCounter = 0; + spentFillRiseHitCount = 0; + spentFillRiseMissCounter = 0; + isSpentFillComplete = FALSE; + isFreshSideValvesClosed = FALSE; + isBalChamberSwitchingActive = FALSE; + isBalChamberSwitchingOnRequested = FALSE; + isBalChamberSwitchingOffRequested = FALSE; + pendingTdDialysateFlowrate = 0.0F; + isBalChamberSwitchingPeriodUpdatePending = FALSE; + bcSwitchingBasedOnClosedPeriodCounter = 0; + balancingError = 0.0F; + prevBalChamberState = BAL_CHAMBER_STATE_IDLE; + //TODO:remove once level sensor working + bicarbChamberPeriodicFillCounter = 0; } /*********************************************************************//** * @brief + * The getAcidConcentratePumpSpeedMlMin function computes D11 pump speed + * from the instantaneous acid mix volume: + * speed = 160 - sqrt(102400 - 96000*v) / 2 + * Result is clamped to [CONCENTRATE_PUMP_MIN_SPEED, CONCENTRATE_PUMP_MAX_SPEED]. + * @details \b Inputs: acidVolumeMl + * @details \b Outputs: none + * @param acidVolumeMl Instantaneous acid mix volume (mL) + * @return Acid concentrate pump speed (mL/min) + *************************************************************************/ +static F32 getAcidConcentratePumpSpeedMlMin( F32 acidVolumeMl ) +{ + F32 discriminant = BC_ACID_SPEED_DISC_CONSTANT - ( BC_ACID_SPEED_DISC_VOL_COEF * acidVolumeMl ); + F32 result = 0.0F; + + if ( discriminant < 0.0F ) + { + discriminant = 0.0F; + } + + result = BC_ACID_SPEED_OFFSET_MLPM - ( sqrtf( discriminant ) / 2.0F ); + + if ( result > CONCENTRATE_PUMP_MAX_SPEED ) + { + result = CONCENTRATE_PUMP_MAX_SPEED; + } + else if ( result < 0.0F ) + { + result = CONCENTRATE_PUMP_MIN_SPEED; + } + + return result; +} +/*********************************************************************//** + * @brief + * The getBicarbConcentratePumpSpeedMlMin function computes D10 pump speed + * from the instantaneous bicarb mix volume: + * speed = 240 - sqrt(230400 - 96000*v) / 2 + * Result is clamped to [CONCENTRATE_PUMP_MIN_SPEED, CONCENTRATE_PUMP_MAX_SPEED]. + * @details \b Inputs: bicarbVolumeMl + * @details \b Outputs: none + * @param bicarbVolumeMl Instantaneous bicarb mix volume (mL) + * @return Bicarb concentrate pump speed (mL/min) + *************************************************************************/ +static F32 getBicarbConcentratePumpSpeedMlMin( F32 bicarbVolumeMl ) +{ + F32 discriminant = BC_BICARB_SPEED_DISC_CONST - ( BC_BICARB_SPEED_DISC_VOL_COEF * bicarbVolumeMl ); + F32 result = 0.0F; + + if ( discriminant < 0.0F ) + { + discriminant = 0.0F; + } + + result = BC_BICARB_SPEED_OFFSET_MLPM - ( sqrtf( discriminant ) / 2.0F ); + + if ( result > CONCENTRATE_PUMP_MAX_SPEED ) + { + result = CONCENTRATE_PUMP_MAX_SPEED; + } + else if ( result < 0.0F ) + { + result = CONCENTRATE_PUMP_MIN_SPEED; + } + + return result; +} + +/*********************************************************************//** + * @brief + * The startBalChamberConcPumpDosing function starts acid and bicarb dosing. + * Acid (D11) runs at fixed 100 mL/min. Bicarb (D10) speed is computed from + * the instantaneous bicarb mix volume on every BC dose start. + * @details \b Inputs: acidVolume, bicarbVolume + * @details \b Outputs: concentrate pumps + * @param acidVolume Acid dose volume (mL) + * @param bicarbVolume Bicarb dose volume (mL) + * @return none + *************************************************************************/ +static void startBalChamberConcPumpDosing( F32 acidVolume, F32 bicarbVolume ) +{ + F32 acidSpeed = getAcidConcentratePumpSpeedMlMin( acidVolume ); + F32 bicarbSpeed = getBicarbConcentratePumpSpeedMlMin( bicarbVolume ); + + setConcentratePumpTargetSpeed( D11_PUMP, acidSpeed, acidVolume ); + setConcentratePumpTargetSpeed( D10_PUMP, bicarbSpeed, bicarbVolume ); + requestConcentratePumpOn( D11_PUMP ); + requestConcentratePumpOn( D10_PUMP ); +} + +/*********************************************************************//** + * @brief * The transitionToBalChamberFill function prepares for transition to * balancing chamber fill/switching operations. * @details \b Inputs: none @@ -155,6 +331,70 @@ if ( lastTdDialysateFlowrate != tdDialysateFlowrate ) { + // Defer Qd timing update to FillEnd at end of the current BC switch + if ( ( TRUE == isBalChamberSwitchingActive ) && ( BAL_CHAMBER_STATE_IDLE != balChamberExecState ) ) + { + pendingTdDialysateFlowrate = tdDialysateFlowrate; + isBalChamberSwitchingPeriodUpdatePending = TRUE; + } + // Apply immediately when BC is inactive or still idle + else + { + pendingTdDialysateFlowrate = tdDialysateFlowrate; + isBalChamberSwitchingPeriodUpdatePending = TRUE; + applyBalChamberSwitchingPeriod( pendingTdDialysateFlowrate ); + scheduleFirstCycleRelaxAfterQdApply(); + } + } + else + { + pendingTdDialysateFlowrate = 0.0F; + isBalChamberSwitchingPeriodUpdatePending = FALSE; + } +} + +/*********************************************************************//** + * @brief + * The getBicarbDoseVol function gets the bicarb dose volume + * @details \b Inputs: bicarbDoseVolume + * @details \b Outputs: none + * @return TRUE if successful, FALSE if not. + *************************************************************************/ +F32 getBicarbDoseVol( void ) +{ + F32 result = getF32OverrideValue( &bicarbDoseVolume ); + + return result; +} + +/*********************************************************************//** + * @brief + * The getAcidDoseVol function gets acid mix volume + * @details \b Inputs: acidDoseVolume + * @details \b Outputs: none + * @return TRUE if successful, FALSE if not. + *************************************************************************/ +F32 getAcidDoseVol( void ) +{ + F32 result = getF32OverrideValue( &acidDoseVolume ); + + return result; +} + +/*********************************************************************//** + * @brief + * The applyBalChamberSwitchingPeriod function applies the active balancing + * chamber switching time based on the provided dialysis flow rate. + * @details \b Inputs: Dialysis flow rate. + * @details \b Outputs: balChamberSwitchingFreq,balChamberSwitchingPeriod + * @return none + *************************************************************************/ +static void applyBalChamberSwitchingPeriod( F32 tdDialysateFlowrate ) +{ + if ( TRUE == isBalChamberSwitchingPeriodUpdatePending ) + { + U32 initialPumpSpeed = 0; + // update the balancing chamber switching frequency balChamberSwitchingFreq.data = tdDialysateFlowrate / BAL_CHAMBER_FILL_VOLUME_ML; @@ -167,6 +407,9 @@ //Update last td dialysate flow rate lastTdDialysateFlowrate = tdDialysateFlowrate; + // Update fill timeout count based on the switching period (e.g. 300% of period) + balChamberFillTimeoutCount = (U32)( (F32)balChamberSwitchingPeriod * BAL_CHAMBER_FILL_TIMEOUT_FACTOR ); + //Reset the BC switching flag for new Qd. isFirstCycleBCSwitchingCompleted = FALSE; @@ -176,27 +419,107 @@ //Testing balChamberValveClosePeriod = balChamberSwitchingPeriod; balChamberValveClosePeriod -= 1; // Close valves prior 50 msecond for testing + + currentBalChamberFillCounter = 0; + currentBalChamberSwitchingCounter = 0; + spentFillRiseHitCount = 0; + spentFillRiseMissCounter = 0; + isSpentFillComplete = FALSE; + isFreshSideValvesClosed = FALSE; + spentDialPressure = getFilteredPressure( D51_PRES ); + lastPrevSpentDialPressure = spentDialPressure; + prevSpentDialPressure = spentDialPressure; + + initialPumpSpeed = getCalculatedD48PumpSpeedForBCFill(); + setD48PumpSpeedForBCFill( initialPumpSpeed ); + setDialysatePumpTargetRPM( D48_PUMP, initialPumpSpeed, TRUE ); + + pendingTdDialysateFlowrate = 0.0F; + isBalChamberSwitchingPeriodUpdatePending = FALSE; } } /*********************************************************************//** * @brief + * The scheduleFirstCycleRelaxAfterQdApply function configures how many BC + * switches still use first-cycle relaxations after a Qd timing update. + * @details \b Inputs: none + * @details \b Outputs: bcSwitchingBasedOnClosedPeriodCounter + * @return none + *************************************************************************/ +static void scheduleFirstCycleRelaxAfterQdApply( void ) +{ + bcSwitchingBasedOnClosedPeriodCounter = NUMBER_OF_CYCLES_BASED_ON_FLOWRATE; +} + +/*********************************************************************//** + * @brief + * The isBalChamberTimeBasedSwitching function checks whether the nominal + * (pre-clamp) D48 starting speed should use fixed-speed, time-based balancing + * chamber switching. + * @details \b Inputs: nominal ceiled D48 speed + * @details \b Outputs: none + * @return TRUE if time-based switching should be used; otherwise FALSE. + *************************************************************************/ +static BOOL isBalChamberTimeBasedSwitching( void ) +{ + BOOL state = FALSE; + F32 dialFlowRate = getBalChamberActiveDialysateFlowrate(); + + state = ( dialFlowRate <= BAL_CHAMBER_OPEN_LOOP_FLOW_RATE_BAND_4 )? TRUE : FALSE; + + return state; +} + +/*********************************************************************//** + * @brief * The execBalancingChamberControl function executes the balancing chamber state machine. - * @details \b Inputs: balChamberExecState - * @details \b Outputs: balChamberExecState + * @details \b Inputs: balChamberExecState, prevBalChamberState + * @details \b Outputs: balChamberExecState prevBalChamberState * @details \b Alarm: ALARM_ID_DD_SOFTWARE_FAULT when wrong balancing chamber state invoked. * @return current state. *************************************************************************/ U32 execBalancingChamberControl( void ) { + LVL_STATE_T bicarbChamberLevel = getBicarbChamberLevelStatus(); + // Increment counter indicating fill is in progress. currentBalChamberSwitchingCounter += 1; + currentBalChamberFillCounter += 1; - // execute current balancing chamber exec state + if ( ( FALSE == getTestConfigStatus( TEST_CONFIG_DD_DISABLE_DRY_BICARB ) ) && ( balChamberExecState > BAL_CHAMBER_STATE_IDLE ) ) + { +#ifdef CONDUCTIVE_LEVEL_SENSOR_ENABLED + if ( LVL_STATE_LOW == bicarbChamberLevel ) + { + if ( FALSE == setBicarbChamberFillRequested() ) + { + // TODO + //drybicart state machines are combined and so this is not an issue in future + //set alarm ? + } + } +#else // time based chamber F fill + // Increment counter for dry bicarb chamber fill + bicarbChamberPeriodicFillCounter += 1; + // Fill bicarb chamber once every 60secs. + if ( bicarbChamberPeriodicFillCounter >= BICARB_CHAMBER_PERIODIC_FILL_TIME ) + { + if ( FALSE == setBicarbChamberFillRequested() ) + { + // TODO + //drybicart state machines are combined and so this is not an issue in future + //set alarm ? + } + bicarbChamberPeriodicFillCounter = 0; + } +#endif + } + switch ( balChamberExecState ) { - case BAL_CHAMBER_STATE_START: - balChamberExecState = BAL_CHAMBER_STATE1_FILL_START; + case BAL_CHAMBER_STATE_IDLE: + balChamberExecState = handleBalChamberStateIdle(); break; case BAL_CHAMBER_STATE1_FILL_START: @@ -207,8 +530,8 @@ balChamberExecState = handleBalChamberConcentrateControl(); break; - case BAL_CHAMBER_STATE1_VALVES_CLOSE: - balChamberExecState = handleBalChamberState1ValvesClose(); + case BAL_CHAMBER_STATE1_FILL_DETECT_COMPLETE: + balChamberExecState = handleBalChamberState1FillDetectComplete(); break; case BAL_CHAMBER_STATE1_FILL_END: @@ -223,8 +546,8 @@ balChamberExecState = handleBalChamberConcentrateControl(); break; - case BAL_CHAMBER_STATE2_VALVES_CLOSE: - balChamberExecState = handleBalChamberState2ValvesClose(); + case BAL_CHAMBER_STATE2_FILL_DETECT_COMPLETE: + balChamberExecState = handleBalChamberState2FillDetectComplete(); break; case BAL_CHAMBER_STATE2_FILL_END: @@ -233,10 +556,21 @@ default: SET_ALARM_WITH_2_U32_DATA( ALARM_ID_DD_SOFTWARE_FAULT, SW_FAULT_ID_BAL_CHAMBER_INVALID_EXEC_STATE, balChamberExecState ) - balChamberExecState = BAL_CHAMBER_STATE_START; + balChamberExecState = BAL_CHAMBER_STATE_IDLE; break; } + if ( prevBalChamberState != balChamberExecState ) + { + if ( ( BAL_CHAMBER_STATE_IDLE == balChamberExecState ) || + ( BAL_CHAMBER_STATE1_FILL_START == balChamberExecState ) || + ( BAL_CHAMBER_STATE2_FILL_START == balChamberExecState ) ) + { + SEND_EVENT_WITH_2_U32_DATA( DD_EVENT_BC_STATE_CHANGE, prevBalChamberState, balChamberExecState ); + } + } + prevBalChamberState = balChamberExecState; + //Publish balancing chamber data publishBalChamberData(); @@ -245,6 +579,26 @@ /*********************************************************************//** * @brief + * The requestBalChamberSwitching function activates or deactivates balancing chamber switching. + * @details \b Inputs: none + * @details \b Outputs: isBalChamberSwitchingOnRequested, isBalChamberSwitchingOffRequested + * @param activate - TRUE to activate and FALSE to deactivate. + * @return none. + *************************************************************************/ +void requestBalChamberSwitching( BOOL activate ) +{ + if ( TRUE == activate ) + { + isBalChamberSwitchingOnRequested = TRUE; + } + else + { + isBalChamberSwitchingOffRequested = TRUE; + } +} + +/*********************************************************************//** + * @brief * The valveControlForBCState1FillStart function actuates the valve combination * for state 1 fill/drain process. * @details \b Inputs: none @@ -394,33 +748,138 @@ /*********************************************************************//** * @brief + * The valveControlForBCSpentSideOnlyOpenState function opens the spent side + * balancing chamber valves and closes the fresh side valves. + * @details \b Inputs: none + * @details \b Outputs: valve states + * @return none. + *************************************************************************/ +void valveControlForBCSpentSideOnlyOpenState( void ) +{ + // Open spent side valves D23,D24,D25,D26 + setValveState( D23_VALV, VALVE_STATE_OPEN ); + setValveState( D25_VALV, VALVE_STATE_OPEN ); + setValveState( D24_VALV, VALVE_STATE_OPEN ); + setValveState( D26_VALV, VALVE_STATE_OPEN ); + + // Close fresh balancing chamber valves D19,D20,D21,D22 + setValveState( D19_VALV, VALVE_STATE_CLOSED ); + setValveState( D20_VALV, VALVE_STATE_CLOSED ); + setValveState( D21_VALV, VALVE_STATE_CLOSED ); + setValveState( D22_VALV, VALVE_STATE_CLOSED ); +} + +/*********************************************************************//** + * @brief + * The valveControlForBCState1FreshSideClose function closes only the fresh-side + * balancing chamber valves opened during state 1 fill. + * @details \b Inputs: none + * @details \b Outputs: valve states + * @return none. + *************************************************************************/ +static void valveControlForBCState1FreshSideClose( void ) +{ + setValveState( D19_VALV, VALVE_STATE_CLOSED ); + setValveState( D24_VALV, VALVE_STATE_CLOSED ); +} + +/*********************************************************************//** + * @brief + * The valveControlForBCState2FreshSideClose function closes only the fresh-side + * balancing chamber valves opened during state 2 fill. + * @details \b Inputs: none + * @details \b Outputs: valve states + * @return none. + *************************************************************************/ +static void valveControlForBCState2FreshSideClose( void ) +{ + setValveState( D26_VALV, VALVE_STATE_CLOSED ); + setValveState( D21_VALV, VALVE_STATE_CLOSED ); +} + +/*********************************************************************//** + * @brief + * The closeFreshSideValvesWhenFillComplete function closes the fresh-side BC + * valves once fresh fill is detected, without waiting for spent fill. + * @details \b Inputs: balChamberSWState, isPressureStabilizedDuringFill, isFreshSideValvesClosed + * @details \b Outputs: isFreshSideValvesClosed, valve states + * @return none. + *************************************************************************/ +static void closeFreshSideValvesWhenFillComplete( void ) +{ + if ( ( TRUE == isPressureStabilizedDuringFill ) && ( FALSE == isFreshSideValvesClosed ) ) + { + if ( BAL_CHAMBER_SW_STATE1 == balChamberSWState ) + { + valveControlForBCState1FreshSideClose(); + } + else + { + valveControlForBCState2FreshSideClose(); + } + + isFreshSideValvesClosed = TRUE; + } +} + +/*********************************************************************//** + * @brief * The handleBalChamberState1FillStart function handles the balancing chamber * state 1 fill and time to fill chamber counter being updated. * @details \b Inputs: Pressure * @details \b Outputs: valve states * @details \b Alarm: ALARM_ID_DD_BC_STATE1_FILL_START_PRESSURE_OUT_OF_RANGE - * when pressure is not in range during balacing chamber fill start. + * when pressure is not in range during balancing chamber fill start. * @return next balancing chamber state. *************************************************************************/ static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1FillStart( void ) { + F32 acidVolume; + F32 bicarbVolume; BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE1_FILL_START; - currentBalChamberSwitchingCounter = 0; + + balChamberSWState = BAL_CHAMBER_SW_STATE1; isBalChamberFillInProgress = FALSE; - isPressureStalbilizedDuringFill = FALSE; + isPressureStabilizedDuringFill = FALSE; isPressureDroppedDuringFill = FALSE; - balChamberSWState = BAL_CHAMBER_SW_STATE1; + lastPrevSpentDialPressure = 0.0F; + prevSpentDialPressure = 0.0F; + currentBalChamberSwitchingCounter = 0; + currentBalChamberFillCounter = 0; + spentFillRiseHitCount = 0; + spentFillRiseMissCounter = 0; + isSpentFillComplete = FALSE; + isFreshSideValvesClosed = FALSE; - F32 acidVolume = getF32OverrideValue( &acidDoseVolume ); - F32 bicarbVolume = getF32OverrideValue( &bicarbDoseVolume ); - freshDialPressure = getFilteredPressure( D18_PRES ); - spentDialPressure = getFilteredPressure( D51_PRES ); + if ( FALSE == getTestConfigStatus( TEST_CONFIG_DD_DISABLE_DRY_BICARB ) ) + { + bicarbVolume = getBicarbMixVol(); + acidVolume = getAcidMixVol(); + } + else // wet bicarb + { + acidVolume = getF32OverrideValue( &acidDoseVolume ); + bicarbVolume = getF32OverrideValue( &bicarbDoseVolume ); + } - // Check fresh and spent dialysate pressure in range or BC switch only flag set - if ( ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) && - ( ( spentDialPressure >= SPENT_DIAL_PRESSURE_MIN_PSIG ) && ( spentDialPressure <= SPENT_DIAL_PRESSURE_MAX_PSIG ) ) || - ( TRUE == getBalChamberSwitchingOnlyStatus() ) || ( TRUE == getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) ) ) + freshDialPressure = getFilteredPressure( D18_PRES ); + spentDialPressure = getFilteredPressure( D51_PRES ); + + if ( TRUE == getTestConfigStatus( TEST_CONFIG_DD_FP_ENABLE_BETA_1_0_HW ) ) { + //Set Trimmer heater Target temp every BC cycle to catch up fresh dialysate temp + setHeaterTargetTemperature( D45_HEAT, getFilteredTemperatureValue( D4_TEMP ) ); + } + else + { + //Set Trimmer heater Target temp every BC cycle to catch up fresh dialysate temp + setHeaterTargetTemperature( D45_HEAT, getFilteredTemperatureValue( D99_TEMP ) ); + } + + // Check fresh dialysate pressure in range or BC switch only flag set or BC pressure alarms are disabled + if ( ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) || + ( TRUE == getBalChamberSwitchingOnlyStatus() ) || ( TRUE == getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) ) ) + { //Valve control for state 1 fill valveControlForBCState1FillStart(); @@ -430,21 +889,20 @@ // Deliver dosing during generate dialysate mode if ( TRUE != getBalChamberSwitchingOnlyStatus() ) { - // start acid and bicarb pump with the expected quantity - setConcentratePumpTargetSpeed( D11_PUMP, CONCENTRATE_PUMP_MAX_SPEED, acidVolume ); - setConcentratePumpTargetSpeed( D10_PUMP, CONCENTRATE_PUMP_MAX_SPEED, bicarbVolume ); - requestConcentratePumpOn( D11_PUMP ); - requestConcentratePumpOn( D10_PUMP ); + startBalChamberConcPumpDosing( acidVolume, bicarbVolume ); } state = BAL_CHAMBER_STATE1_BICARB_ACID_DOSING_CNTRL; } else { - if ( getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) + if ( getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) { //Alarm when pressure is not in range SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE1_FILL_START_PRESSURE_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; } } @@ -454,18 +912,21 @@ /*********************************************************************//** * @brief * The handleBalChamberConcentrateControl function handles the Acid and Bicarb - * concentrate doisng and checks the conductivity of the dialysate for the treatment. + * concentrate dosing and checks the conductivity of the dialysate for the treatment. * @details \b Inputs: balChamberSWState , Concentrate volume * @details \b Outputs: isPressureDroppedDuringFill, state * @return next balancing chamber state. *************************************************************************/ static BAL_CHAMBER_EXEC_STATE_T handleBalChamberConcentrateControl( void ) { BAL_CHAMBER_EXEC_STATE_T state; - freshDialPressure = getFilteredPressure( D18_PRES ); - spentDialPressure = getFilteredPressure( D51_PRES ); - if ( BAL_CHAMBER_SW_STATE1 == balChamberSWState ) + freshDialPressure = getFilteredPressure( D18_PRES ); + spentDialPressure = getFilteredPressure( D51_PRES ); + lastPrevSpentDialPressure = prevSpentDialPressure; + prevSpentDialPressure = spentDialPressure; + + if ( BAL_CHAMBER_SW_STATE1 == balChamberSWState ) { state = BAL_CHAMBER_STATE1_BICARB_ACID_DOSING_CNTRL; } @@ -490,11 +951,14 @@ { if ( BAL_CHAMBER_SW_STATE1 == balChamberSWState ) { - state = BAL_CHAMBER_STATE1_VALVES_CLOSE; + // Low-Qd spent slope: baseline = spent pressure on last dosing tick (this task period) before VALVES_CLOSE. + prevSpentDialPressure = spentDialPressure; + state = BAL_CHAMBER_STATE1_FILL_DETECT_COMPLETE; } else { - state = BAL_CHAMBER_STATE2_VALVES_CLOSE; + prevSpentDialPressure = spentDialPressure; + state = BAL_CHAMBER_STATE2_FILL_DETECT_COMPLETE; } } @@ -503,46 +967,79 @@ /*********************************************************************//** * @brief - * The handleBalChamberState1ValvesClose function check for the balancing chamber + * The handleBalChamberState1FillDetectComplete function check for the balancing chamber * fill complete and close the currently opened valves. * @details \b Inputs: currentBalChamberSwitchingCounter, spent and fresh dialysate pressure * @details \b Outputs: isPressureStalbilizedDuringFill,isBalChamberFillInProgress * @return next balancing chamber state. *************************************************************************/ -static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1ValvesClose( void ) +static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1FillDetectComplete( void ) { - BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE1_VALVES_CLOSE; + BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE1_FILL_DETECT_COMPLETE; + BOOL isFirstCycleNotDone = FALSE; + BOOL isFillCompleteOrFirstCycle = FALSE; - freshDialPressure = getFilteredPressure( D18_PRES ); - spentDialPressure = getFilteredPressure( D51_PRES ); + freshDialPressure = getFilteredPressure( D18_PRES ); + spentDialPressure = getFilteredPressure( D51_PRES ); - // Check fresh and spent dialysate pressure back in range to indicate fill complete. - if ( getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) + // After the first BC cycle, fault if fill never completes at the Qd-based timeout. + if ( ( currentBalChamberFillCounter > balChamberFillTimeoutCount ) && ( TRUE != getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) ) ) { - if ( ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) && - ( ( spentDialPressure >= SPENT_DIAL_PRESSURE_MIN_PSIG ) && ( spentDialPressure <= SPENT_DIAL_PRESSURE_MAX_PSIG ) ) ) + SET_ALARM_WITH_2_U32_DATA( ALARM_ID_DD_BC_FILL_TIMEOUT_FAULT, currentBalChamberFillCounter, balChamberFillTimeoutCount ); + + SEND_EVENT_WITH_2_U32_DATA( DD_EVENT_BC_FILL_TIMEOUT, isPressureStabilizedDuringFill, isSpentFillComplete ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; + } + + // Check fresh dialysate pressure back in range to indicate fresh fill complete. + if ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) + { + if ( ++balChamberFillCompleteStablePressureCounter >= BAL_CHAMBER_FILL_COMPLETE_MS ) { - if ( ++balChamberFillCompleteStablePressureCounter >= BAL_CHAMBER_FILL_COMPLETE_MS ) - { - // stabilized pressure indicating fill is complete - isPressureStalbilizedDuringFill = TRUE; - } + // stabilized pressure indicating fresh side fill is complete + isPressureStabilizedDuringFill = TRUE; } } - else + + // Close fresh side valves only upon fresh fill completion by detecting pressure rise. + closeFreshSideValvesWhenFillComplete(); + + // Check Spent side fill complete + checkSpentFillComplete( spentDialPressure ); + + isFirstCycleNotDone = ( ( FALSE == isFirstCycleBCSwitchingCompleted ) && + ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) ) ? TRUE : FALSE; + + if ( FALSE == getBalChamberSwitchingOnlyStatus() ) { - isPressureStalbilizedDuringFill = FALSE; + isFillCompleteOrFirstCycle = ( ( ( TRUE == isSpentFillComplete ) && ( TRUE == isFreshSideValvesClosed ) ) || + ( TRUE == isFirstCycleNotDone ) ) ? TRUE : FALSE; } - // Switching time met or pressure in range, close valves - if ( ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) || - ( TRUE == isPressureStalbilizedDuringFill ) ) + if ( ( TRUE == isFillCompleteOrFirstCycle ) || + ( ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) && ( TRUE == getBalChamberSwitchingOnlyStatus() ) ) ) { // close the state 1 opened valves valveControlForBCState1FillEnd(); isBalChamberFillInProgress = FALSE; + if ( FALSE == getBalChamberSwitchingOnlyStatus() ) + { + setDialysatePumpTargetRPM( D48_PUMP, getD48PumpSpeedForBCFill(), TRUE ); + } - //Transition to next state + if ( bcSwitchingBasedOnClosedPeriodCounter > 0 ) + { + bcSwitchingBasedOnClosedPeriodCounter -= 1; + } + + if ( 0 == bcSwitchingBasedOnClosedPeriodCounter ) + { + isFirstCycleBCSwitchingCompleted = TRUE; + } + + // Transition to next state state = BAL_CHAMBER_STATE1_FILL_END; } @@ -552,57 +1049,90 @@ /*********************************************************************//** * @brief * The handleBalChamberState1FillEnd function check for the balancing chamber - * switching period and tranistion to next state switching. - * @details \b Inputs: currentBalChamberSwitchingCounter, balChamberSwitchingPeriod + * switching period and transition to next state switching. + * @details \b Inputs: currentBalChamberSwitchingCounter, balChamberSwitchingPeriod, + * isBalChamberSwitchingOffRequested, balanceChamberSwitchingOnlyOffRequested * @details \b Outputs: balChamberFillPressureDropCounter,balChamberFillCompleteStablePressureCounter + * isBalChamberSwitchingOnRequested, isBalChamberSwitchingOffRequested, isBalChamberSwitchingActive, + * balanceChamberSwitchingOnlyOffRequested * @details \b Alarm: ALARM_ID_DD_BC_STATE1_FILL_PRESSURE_DROP_OUT_OF_RANGE - * when pressure drop is not in range during balacing chamber fill in progress. - * @details \b Alarm: ALARM_ID_DD_BC_STATE1_FILL_END_PRESSURE_OUT_OF_RANGE - * when pressure is not in range during balacing chamber fill complete. + * when pressure drop is not in range during balancing chamber fill in progress. * @return next balancing chamber state. *************************************************************************/ static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState1FillEnd( void ) { BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE1_FILL_END; - // On completion of cycle time, transition to next state - if ( currentBalChamberSwitchingCounter >= balChamberSwitchingPeriod ) + balChamberFillPressureDropCounter = 0; + balChamberFillCompleteStablePressureCounter = 0; + + if ( TRUE != getBalChamberSwitchingOnlyStatus() ) { - balChamberFillPressureDropCounter = 0; - balChamberFillCompleteStablePressureCounter = 0; + if ( TRUE == isBalChamberSwitchingPeriodUpdatePending ) + { + applyBalChamberSwitchingPeriod( pendingTdDialysateFlowrate ); + scheduleFirstCycleRelaxAfterQdApply(); + } - if ( TRUE != getBalChamberSwitchingOnlyStatus() ) + if ( getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) { - if ( getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) + if ( ( TRUE != isPressureDroppedDuringFill ) && ( TRUE == isFirstCycleBCSwitchingCompleted ) ) { - if ( ( TRUE != isPressureDroppedDuringFill ) && ( TRUE == isFirstCycleBCSwitchingCompleted ) ) - { - // When fill initiated, pressure is not dropped to the expected range, possible valve failures. - SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE1_FILL_PRESSURE_DROP_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); - } - else if ( TRUE != isPressureStalbilizedDuringFill ) - { - // Alarm when switching time expired, but still pressure not in range which indicates fill is not yet completed. - SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE1_FILL_END_PRESSURE_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); - } - else - { - // Move to next state when pressure is in range. - state = BAL_CHAMBER_STATE2_FILL_START; - } + // When fill initiated, pressure is not dropped to the expected range, possible valve failures. + SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE1_FILL_PRESSURE_DROP_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; } else { - // Allow to proceed next state even though pressure is not stabilized. + // Move to next state when pressure is in range. state = BAL_CHAMBER_STATE2_FILL_START; } } else { + // Allow to proceed next state even though pressure is not stabilized. state = BAL_CHAMBER_STATE2_FILL_START; } } + else + { // For Balancing Chamber Switch Only command, change state as per the switching period + if ( currentBalChamberSwitchingCounter >= balChamberSwitchingPeriod ) + { + state = BAL_CHAMBER_STATE2_FILL_START; + } + } + // Clear the switching only on request flag. + balanceChamberSwitchingOnlyOnRequested = FALSE; + + // Check if switching only off was requested + if ( TRUE == balanceChamberSwitchingOnlyOffRequested ) + { + // Clear the Switch only off request flag + balanceChamberSwitchingOnlyOffRequested = FALSE; + + //Clear the switch only flag + setBalChamberSwitchingOnlyStatus( FALSE ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; + } + + // Keep Clearing the On request flag in case an On request was made while the switching is active + isBalChamberSwitchingOnRequested = FALSE; + + // Check if a request made was to deactivate the balancing chamber switching. + if ( TRUE == isBalChamberSwitchingOffRequested ) + { + //Clear the request flag to indicate that the request was processed. + isBalChamberSwitchingOffRequested = FALSE; + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; + } + return state; } @@ -613,28 +1143,57 @@ * @details \b Inputs: fresh and spent dialysate pressure * @details \b Outputs: valve states * @details \b Alarm: ALARM_ID_DD_BC_STATE2_FILL_START_PRESSURE_OUT_OF_RANGE - * when pressure is not in range during balacing chamber state 2 fill start. + * when pressure is not in range during balancing chamber state 2 fill start. * @return next balancing chamber state. *************************************************************************/ static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2FillStart( void ) { + F32 acidVolume; + F32 bicarbVolume; BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE2_FILL_START; - currentBalChamberSwitchingCounter = 0; + isBalChamberFillInProgress = FALSE; - isPressureStalbilizedDuringFill = FALSE; + isPressureStabilizedDuringFill = FALSE; isPressureDroppedDuringFill = FALSE; balChamberSWState = BAL_CHAMBER_SW_STATE2; + lastPrevSpentDialPressure = 0.0F; + prevSpentDialPressure = 0.0F; + currentBalChamberSwitchingCounter = 0; + currentBalChamberFillCounter = 0; + spentFillRiseHitCount = 0; + spentFillRiseMissCounter = 0; + isSpentFillComplete = FALSE; + isFreshSideValvesClosed = FALSE; - F32 acidVolume = getF32OverrideValue( &acidDoseVolume ); - F32 bicarbVolume = getF32OverrideValue( &bicarbDoseVolume ); - freshDialPressure = getFilteredPressure( D18_PRES ); - spentDialPressure = getFilteredPressure( D51_PRES ); + if ( FALSE == getTestConfigStatus( TEST_CONFIG_DD_DISABLE_DRY_BICARB ) ) + { + bicarbVolume = getBicarbMixVol(); + acidVolume = getAcidMixVol(); + } + else + { + acidVolume = getF32OverrideValue( &acidDoseVolume ); + bicarbVolume = getF32OverrideValue( &bicarbDoseVolume ); + } - // Check fresh and spent dialysate pressure in range - if ( ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) && - ( ( spentDialPressure >= SPENT_DIAL_PRESSURE_MIN_PSIG ) && ( spentDialPressure <= SPENT_DIAL_PRESSURE_MAX_PSIG ) ) || - ( TRUE == getBalChamberSwitchingOnlyStatus() ) || ( TRUE == getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) ) ) + freshDialPressure = getFilteredPressure( D18_PRES ); + spentDialPressure = getFilteredPressure( D51_PRES ); + + if ( TRUE == getTestConfigStatus( TEST_CONFIG_DD_FP_ENABLE_BETA_1_0_HW ) ) { + //Set Trimmer heater Target temp every BC cycle to catch up fresh dialysate temp + setHeaterTargetTemperature( D45_HEAT, getFilteredTemperatureValue( D4_TEMP ) ); + } + else + { + //Set Trimmer heater Target temp every BC cycle to catch up fresh dialysate temp + setHeaterTargetTemperature( D45_HEAT, getFilteredTemperatureValue( D99_TEMP ) ); + } + + // Check fresh dialysate pressure in range + if ( ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) || + ( TRUE == getBalChamberSwitchingOnlyStatus() ) || ( TRUE == getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) ) ) + { // Valve control for state 2 fill valveControlForBCState2FillStart(); @@ -644,67 +1203,100 @@ // Deliver dosing during generate dialysate mode if ( TRUE != getBalChamberSwitchingOnlyStatus() ) { - // start acid and bicarb pump with the expected quantity - setConcentratePumpTargetSpeed( D11_PUMP, CONCENTRATE_PUMP_MAX_SPEED, acidVolume ); - setConcentratePumpTargetSpeed( D10_PUMP, CONCENTRATE_PUMP_MAX_SPEED, bicarbVolume ); - requestConcentratePumpOn( D11_PUMP ); - requestConcentratePumpOn( D10_PUMP ); + startBalChamberConcPumpDosing( acidVolume, bicarbVolume ); } state = BAL_CHAMBER_STATE2_BICARB_ACID_DOSING_CNTRL; } else { - if ( getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) + if ( getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) { //Alarm when pressure is not in range SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE2_FILL_START_PRESSURE_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; } } + return state; } /*********************************************************************//** * @brief - * The handleBalChamberState2ValvesClose function check for the balancing chamber + * The handleBalChamberState2FillDetectComplete function check for the balancing chamber * fill complete and close the currently opened valves. * @details \b Inputs: currentBalChamberSwitchingCounter, spent and fresh dialysate pressure * @details \b Outputs: isPressureStalbilizedDuringFill,isBalChamberFillInProgress * @return next balancing chamber state. *************************************************************************/ -static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2ValvesClose( void ) +static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2FillDetectComplete( void ) { - BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE2_VALVES_CLOSE; + BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE2_FILL_DETECT_COMPLETE; + BOOL isFirstCycleNotDone = FALSE; + BOOL isFillCompleteOrFirstCycle = FALSE; - freshDialPressure = getFilteredPressure( D18_PRES ); - spentDialPressure = getFilteredPressure( D51_PRES ); + freshDialPressure = getFilteredPressure( D18_PRES ); + spentDialPressure = getFilteredPressure( D51_PRES ); - // Check fresh and spent dialysate pressure back in range to indicate fill complete. - if ( getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) + // After the first BC cycle, fault if fill never completes at the Qd-based timeout. + if ( ( currentBalChamberFillCounter > balChamberFillTimeoutCount ) && ( TRUE != getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) ) ) { - if ( ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) && - ( ( spentDialPressure >= SPENT_DIAL_PRESSURE_MIN_PSIG ) && ( spentDialPressure <= SPENT_DIAL_PRESSURE_MAX_PSIG ) ) ) + SET_ALARM_WITH_2_U32_DATA( ALARM_ID_DD_BC_FILL_TIMEOUT_FAULT, currentBalChamberFillCounter, balChamberFillTimeoutCount ); + + SEND_EVENT_WITH_2_U32_DATA( DD_EVENT_BC_FILL_TIMEOUT, isPressureStabilizedDuringFill, isSpentFillComplete ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; + } + + // Check fresh dialysate pressure back in range to indicate fresh fill complete. + if ( ( freshDialPressure >= FRESH_DIAL_PRESSURE_MIN_PSIG ) && ( freshDialPressure <= FRESH_DIAL_PRESSURE_MAX_PSIG ) ) + { + if ( ++balChamberFillCompleteStablePressureCounter >= BAL_CHAMBER_FILL_COMPLETE_MS ) { - if ( ++balChamberFillCompleteStablePressureCounter >= BAL_CHAMBER_FILL_COMPLETE_MS ) - { - // stabilized pressure indicating fill is complete - isPressureStalbilizedDuringFill = TRUE; - } + // stabilized pressure indicating fresh side fill is complete + isPressureStabilizedDuringFill = TRUE; } } - else + + // Close fresh side valves only upon fresh fill completion by detecting pressure rise. + closeFreshSideValvesWhenFillComplete(); + + // Check Spent side fill complete + checkSpentFillComplete( spentDialPressure ); + + isFirstCycleNotDone = ( ( FALSE == isFirstCycleBCSwitchingCompleted ) && + ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) ) ? TRUE : FALSE; + + if ( FALSE == getBalChamberSwitchingOnlyStatus() ) { - isPressureStalbilizedDuringFill = FALSE; + isFillCompleteOrFirstCycle = ( ( ( TRUE == isSpentFillComplete ) && ( TRUE == isFreshSideValvesClosed ) ) || + ( TRUE == isFirstCycleNotDone ) ) ? TRUE : FALSE; } - // Check switching cycle time or pressure check for valve closure - if ( ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) || - ( TRUE == isPressureStalbilizedDuringFill ) ) + if ( ( TRUE == isFillCompleteOrFirstCycle ) || + ( ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) && ( TRUE == getBalChamberSwitchingOnlyStatus() ) ) ) { // close the valves valveControlForBCState2FillEnd(); isBalChamberFillInProgress = FALSE; + if ( FALSE == getBalChamberSwitchingOnlyStatus() ) + { + setDialysatePumpTargetRPM( D48_PUMP, getD48PumpSpeedForBCFill(), TRUE ); + } + if ( bcSwitchingBasedOnClosedPeriodCounter > 0 ) + { + bcSwitchingBasedOnClosedPeriodCounter -= 1; + } + + if ( 0 == bcSwitchingBasedOnClosedPeriodCounter ) + { + isFirstCycleBCSwitchingCompleted = TRUE; + } + //Transition to next state state = BAL_CHAMBER_STATE2_FILL_END; } @@ -716,68 +1308,292 @@ * @brief * The handleBalChamberState2FillEnd function check for the balancing chamber * switching period complete and transition to next state. - * @details \b Inputs: currentBalChamberSwitchingCounter, balChamberSwitchingPeriod - * @details \b Outputs: isPressureStalbilizedDuringFill,isBalChamberFillInProgress + * @details \b Inputs: currentBalChamberSwitchingCounter, balChamberSwitchingPeriod, + * isBalChamberSwitchingOffRequested, balanceChamberSwitchingOnlyOffRequested + * @details \b Outputs: isPressureStabilizedDuringFill,isBalChamberFillInProgress, + * isBalChamberSwitchingOnRequested, isBalChamberSwitchingOffRequested, isBalChamberSwitchingActive, + * balanceChamberSwitchingOnlyOffRequested * @details \b Alarm: ALARM_ID_DD_BC_STATE2_FILL_PRESSURE_DROP_OUT_OF_RANGE * when pressure is not in range during balacing chamber state 2 fill in progress. - * @details \b Alarm: ALARM_ID_DD_BC_STATE2_FILL_END_PRESSURE_OUT_OF_RANGE - * when pressure is not in range during balacing chamber state 2 fill complete. * @return next balancing chamber state. *************************************************************************/ static BAL_CHAMBER_EXEC_STATE_T handleBalChamberState2FillEnd( void ) { BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE2_FILL_END; - // On completion of cycle time, transition to next state - if ( currentBalChamberSwitchingCounter >= balChamberSwitchingPeriod ) + balChamberFillPressureDropCounter = 0; + balChamberFillCompleteStablePressureCounter = 0; + + if ( TRUE != getBalChamberSwitchingOnlyStatus() ) { - balChamberFillPressureDropCounter = 0; - balChamberFillCompleteStablePressureCounter = 0; + if ( TRUE == isBalChamberSwitchingPeriodUpdatePending ) + { + applyBalChamberSwitchingPeriod( pendingTdDialysateFlowrate ); + scheduleFirstCycleRelaxAfterQdApply(); + } - // Pressure alarm check - if ( TRUE != getBalChamberSwitchingOnlyStatus() ) + if ( getTestConfigStatus( TEST_CONFIG_DD_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) { - if ( getTestConfigStatus( TEST_CONFIG_DISABLE_BC_PRESSURE_ALARMS ) != TRUE ) + if ( ( TRUE != isPressureDroppedDuringFill ) && ( TRUE == isFirstCycleBCSwitchingCompleted ) ) { - if ( ( TRUE != isPressureDroppedDuringFill ) && ( TRUE == isFirstCycleBCSwitchingCompleted ) ) - { - // When fill initiated, pressure is not dropped to the expected range, possible valve failures. - SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE2_FILL_PRESSURE_DROP_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); - } - else if ( TRUE != isPressureStalbilizedDuringFill ) - { - // Alarm when switching time expired, but still pressure not in range which indicates fill is not completed. - SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE2_FILL_END_PRESSURE_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); - } - else - { - // Move to next state when pressure is in range. - state = BAL_CHAMBER_STATE1_FILL_START; + // When fill initiated, pressure is not dropped to the expected range, possible valve failures. + SET_ALARM_WITH_2_F32_DATA( ALARM_ID_DD_BC_STATE2_FILL_PRESSURE_DROP_OUT_OF_RANGE, freshDialPressure, spentDialPressure ); - // Trigger pressure drop alarm after first cycle of balancing chamber switching complete - if ( FALSE == isFirstCycleBCSwitchingCompleted ) - { - isFirstCycleBCSwitchingCompleted = TRUE; - } - } + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; } else { - // Allow to proceed next state even though pressure is not stabilized. + // Move to next state when pressure is in range. state = BAL_CHAMBER_STATE1_FILL_START; } } else { + // Allow to proceed next state even though pressure is not stabilized. state = BAL_CHAMBER_STATE1_FILL_START; } } + else + { // For Balancing Chamber Switch Only command, change state as per the switching period + if ( currentBalChamberSwitchingCounter >= balChamberSwitchingPeriod ) + { + state = BAL_CHAMBER_STATE1_FILL_START; + } + } + // Clear the switching only on request flag. + balanceChamberSwitchingOnlyOnRequested = FALSE; + + // Check if switching only off was requested + if ( TRUE == balanceChamberSwitchingOnlyOffRequested ) + { + // Clear the Switch only off request flag + balanceChamberSwitchingOnlyOffRequested = FALSE; + + //Clear the switch only flag + setBalChamberSwitchingOnlyStatus( FALSE ); + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; + } + + // Keep Clearing the On request flag in case an On request was made while the switching is active + isBalChamberSwitchingOnRequested = FALSE; + + // Check if a request made was to deactivate the balancing chamber switching. + if ( TRUE == isBalChamberSwitchingOffRequested ) + { + // Clear the request flag to indicate that the request was processed. + isBalChamberSwitchingOffRequested = FALSE; + + // Move to the idle state + state = BAL_CHAMBER_STATE_IDLE; + } + return state; } /*********************************************************************//** * @brief + * The handleBalChamberStateIdle function handles balancing chamber idle state. + * @details \b Inputs: isBalChamberSwitchingOnRequested + * @details \b Outputs: isBalChamberSwitchingOnRequested, isBalChamberSwitchingOffRequested, + * isBalChamberSwitchingActive + * @return next balancing chamber state. + *************************************************************************/ +static BAL_CHAMBER_EXEC_STATE_T handleBalChamberStateIdle( void ) +{ + BAL_CHAMBER_EXEC_STATE_T state = BAL_CHAMBER_STATE_IDLE; + + // Clear the switching only off request flag. + balanceChamberSwitchingOnlyOffRequested = FALSE; + + // Check if the switching only on was requested + if ( TRUE == balanceChamberSwitchingOnlyOnRequested ) + { + // Clear the switching only on request flag. + balanceChamberSwitchingOnlyOnRequested = FALSE; + + // then set BC switching only flag to ignore pressure check and dosing. + setBalChamberSwitchingOnlyStatus( TRUE ); + + // Set flag to indicate that balancing chamber switching is active + isBalChamberSwitchingActive = TRUE; + + // Move to the start state1 + state = BAL_CHAMBER_STATE1_FILL_START; + } + + // Keep Clearing the off request flag in case an off request was made while we were already in the idle state + isBalChamberSwitchingOffRequested = FALSE; + + // Clear flag to indicate that balancing chamber switching is inactive + isBalChamberSwitchingActive = FALSE; + + // Check if a request made was to activate the balancing chamber switching. + if ( TRUE == isBalChamberSwitchingOnRequested ) + { + //Clear request was processed. + isBalChamberSwitchingOnRequested = FALSE; + + // Set flag to indicate that balancing chamber switching is active + isBalChamberSwitchingActive = TRUE; + + // Move to the start state1 + state = BAL_CHAMBER_STATE1_FILL_START; + } + + return state; +} + +/*********************************************************************//** + * @brief + * The isSpentFillCompleteByPressure function evaluates whether the spent side of the + * balancing chamber fill is complete from D51 pressure. + * @details \b Inputs: spentDialPressure, qdMlpm, valve-close period, fill counter, + * Diener pump test config, and D51 slope history. + * @details \b Outputs: spentFillRiseHitCount, spentFillRiseMissCounter, + * lastPrevSpentDialPressure, prevSpentDialPressure. + * @param spentDialPressure filtered spent dialysate pressure (PSIG). + * @param qdMlpm dialysate flow rate (mL/min). + * @return TRUE if spent fill is detected this task period; FALSE otherwise. + *************************************************************************/ +static BOOL isSpentFillCompleteByPressure( F32 spentDialPressure, F32 qdMlpm ) +{ + BOOL useLowQdRiseThreshold = ( ( ( TRUE != getTestConfigStatus( TEST_CONFIG_DD_ENABLE_DIENER_2000_PUMP ) ) && + ( qdMlpm <= SPENT_FILL_COMPLETE_QD_LOW_RISE_MAX_MLPM ) ) ? TRUE : FALSE ); + F32 riseThresholdPsig = ( TRUE == useLowQdRiseThreshold ) ? SPENT_FILL_COMPLETE_DP_RISE_PSIG : + SPENT_FILL_COMPLETE_DP_RISE_HIGH_QD_PSIG; + BOOL state; + + // Gate slope hits near expected valve-close count (current vs balChamberValveClosePeriod +/- tolerance). + U32 detectTolCount = (U32)( (F32)balChamberValveClosePeriod * SPENT_FILL_DETECT_COUNT_TOL_PCT ); + U32 maxDetectCount = balChamberValveClosePeriod + detectTolCount; + U32 minDetectCount = balChamberValveClosePeriod - detectTolCount; + BOOL isDetectionInCountWindow = ( ( currentBalChamberFillCounter >= minDetectCount ) && + ( currentBalChamberFillCounter <= maxDetectCount ) ) ? TRUE : FALSE; + F32 riseDeltaPsi = spentDialPressure - lastPrevSpentDialPressure; + BOOL riseHit = ( riseDeltaPsi > riseThresholdPsig ) ? TRUE : FALSE; + U32 requiredRiseCount; + + // Mid band between low/high spent pressure rise: require two rise hits. + if ( riseDeltaPsi > SPENT_FILL_SLOPE_SPENT_PRESSURE_HIGH_PSIG ) + { + requiredRiseCount = 1U; + } + else + { + requiredRiseCount = 2U; + } + + if ( ( TRUE == riseHit ) && ( TRUE == isDetectionInCountWindow ) ) + { + spentFillRiseHitCount += 1; + spentFillRiseMissCounter = 0; + } + else if ( spentFillRiseHitCount > 0 ) + { + if ( ( FALSE == riseHit ) && ( TRUE == isDetectionInCountWindow ) ) + { + spentFillRiseMissCounter += 1; + + if ( spentFillRiseMissCounter >= 2 ) + { + spentFillRiseHitCount = 0; + spentFillRiseMissCounter = 0; + } + } + } + + lastPrevSpentDialPressure = prevSpentDialPressure; + prevSpentDialPressure = spentDialPressure; + + state = ( spentFillRiseHitCount >= requiredRiseCount ) ? TRUE : FALSE; + return state; +} + +/*********************************************************************//** + * @brief + * The checkSpentFillComplete function checks the pressure difference for + * spent side fill completion and adjusts the D48 pump speed to align the + * fill timing close to the switching period time. + * @details \b Inputs: balChamberExecState + * @details \b Outputs: none + * @param spentDialPressure to check the switching time for BC and set D48 speed based on it. + * @return the current state of balancing chamber states. + *************************************************************************/ +static void checkSpentFillComplete( F32 spentDialPressure ) +{ + U32 absDiffSpentFillCount = 0; + U32 adjustedSpeed = 0; + U32 spentDialPumpSpeed = getD48PumpSpeedForBCFill(); + U32 initialD48PumpSpeed = getCalculatedD48PumpSpeedForBCFill(); + U32 minD48Speed = initialD48PumpSpeed - ( initialD48PumpSpeed * D48_SPEED_RANGE_LIMIT ); + U32 maxD48Speed = initialD48PumpSpeed + ( initialD48PumpSpeed * D48_SPEED_RANGE_LIMIT ); + U32 d48SpeedPostRangeCheck = 0; + F32 qdMlpm = getBalChamberActiveDialysateFlowrate(); + BOOL result = FALSE; + BOOL isSpentFillCompleteDetected = FALSE; + + if ( TRUE == isBalChamberTimeBasedSwitching() ) + { + if ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) + { + isSpentFillComplete = TRUE; + } + } + else + { + isSpentFillCompleteDetected = isSpentFillCompleteByPressure( spentDialPressure, qdMlpm ); + + if ( ( TRUE == isSpentFillCompleteDetected ) && ( isSpentFillComplete != TRUE ) ) + { + // Check spent fill time against the balancing chamber closing period + if ( balChamberValveClosePeriod > 0 ) + { + diffSpentFillCompleteCount = balChamberValveClosePeriod - currentBalChamberFillCounter; + absDiffSpentFillCount = abs(diffSpentFillCompleteCount); + adjustedSpeed = ( ( (F32)absDiffSpentFillCount / (F32)balChamberValveClosePeriod ) * spentDialPumpSpeed ) * D48_SPEED_ADJUST_FACTOR; + + // Skip D48 trim in deadband: diff 0..-2 counts (0..100 ms at 50 ms/task); positive band only (larger negative may mean under-fill). + result = ( ( diffSpentFillCompleteCount <= 0 ) && ( diffSpentFillCompleteCount >= -2 ) ) ? TRUE : FALSE; + + if ( FALSE == result ) + { + if ( diffSpentFillCompleteCount < SPENT_DIFF_COUNT_ZERO ) + { + // Increase the D48 pump speed + spentDialPumpSpeed += adjustedSpeed; + } + else + { + //Decrease the D48 pump speed + spentDialPumpSpeed -= adjustedSpeed; + } + + d48SpeedPostRangeCheck = RANGE( spentDialPumpSpeed, minD48Speed, maxD48Speed ); + + // Do not turn on the pump if the switching only is enabled in the standby mode. + if ( FALSE == getBalChamberSwitchingOnlyStatus() ) + { + // Update the D48 pump speed + setD48PumpSpeedForBCFill( d48SpeedPostRangeCheck ); + } + } + } + + //Update spent fill is complete + if ( currentBalChamberSwitchingCounter >= balChamberValveClosePeriod ) + { + isSpentFillComplete = TRUE; + } + } + } +} + +/*********************************************************************//** + * @brief * The getCurrentBalancingChamberExecState function returns the current state * of the balancing chamber. * @details \b Inputs: balChamberExecState @@ -804,6 +1620,66 @@ /*********************************************************************//** * @brief + * The getBalChamberFreshSideValvesClosedStatus function returns whether the + * fresh-side balancing chamber valves are closed for the current switch state. + * @details \b Inputs: isFreshSideValvesClosed + * @details \b Outputs: none + * @return TRUE when fresh-side BC valves are closed. + *************************************************************************/ +BOOL getBalChamberFreshSideValvesClosedStatus( void ) +{ + return isFreshSideValvesClosed; +} + +/*********************************************************************//** + * @brief + * The getBalChamberFreshFillCompleteStatus function returns whether fresh-side + * fill completed during the current BC switch cycle. + * @details \b Inputs: isPressureStabilizedDuringFill + * @details \b Outputs: none + * @return TRUE when fresh-side fill is complete. + *************************************************************************/ +BOOL getBalChamberFreshFillCompleteStatus( void ) +{ + return isPressureStabilizedDuringFill; +} + +/*********************************************************************//** + * @brief + * The getBalChamberSpentFillCompleteStatus function returns whether spent-side + * fill completed during the current BC switch cycle. + * @details \b Inputs: isSpentFillComplete + * @details \b Outputs: none + * @return TRUE when spent-side fill is complete. + *************************************************************************/ +BOOL getBalChamberSpentFillCompleteStatus( void ) +{ + return isSpentFillComplete; +} + +/*********************************************************************//** + * @brief + * The isBalChamberSwitchImminent function returns whether the balancing chamber + * is within the valve-close window (50 ms) before switching. + * @details \b Inputs: currentBalChamberSwitchingCounter, balChamberValveClosePeriod + * @details \b Outputs: none + * @return TRUE when BC switch is imminent. + *************************************************************************/ +BOOL isBalChamberSwitchImminent( void ) +{ + BOOL result = FALSE; + + if ( ( balChamberValveClosePeriod > 0 ) && + ( currentBalChamberSwitchingCounter >= balChamberSwitchingPeriod ) ) + { + result = TRUE; + } + + return result; +} + +/*********************************************************************//** + * @brief * The getBalChamberSwitchingFreq function gets the balancing chamber switching * frequency value. * @details \b Inputs: balChamberSwitchingFreq @@ -824,15 +1700,30 @@ /*********************************************************************//** * @brief + * The getBalChamberActiveDialysateFlowrate function gets the Qd currently + * applied to balancing chamber timing. + * @details \b Inputs: lastTdDialysateFlowrate + * @details \b Outputs: none + * @return active balancing chamber dialysate flow rate + *************************************************************************/ +F32 getBalChamberActiveDialysateFlowrate( void ) +{ + return lastTdDialysateFlowrate; +} + +/*********************************************************************//** + * @brief * The setBalChamberSwitchingOnlyStatus function sets the balancing chamber * switching only On/Off status. - * @details \b Inputs: balanceChamberSwitchingOnly + * @details \b Inputs: balanceChamberSwitchingOnly, isBalChamberSwitchingActive * @details \b Outputs: none + * @param OnOff to set the BC switch status * @return none *************************************************************************/ void setBalChamberSwitchingOnlyStatus( BOOL OnOff ) { balanceChamberSwitchingOnly = OnOff; + SEND_EVENT_WITH_2_U32_DATA( DD_EVENT_BC_SWITCH_ONLY_MODE_CHANGE, balanceChamberSwitchingOnly, isBalChamberSwitchingActive ); } /*********************************************************************//** @@ -884,6 +1775,50 @@ /*********************************************************************//** * @brief + * The calculateBalancingChamberError function calculates the balancing error + * based on the fresh and spent dialysate temperature differences. + * @details \b Inputs: D4 and D50 temperature + * @details \b Outputs: balancing error + * @return balancing error the balancing error that impacts ultrafilteration. + *************************************************************************/ +static void calculateBalancingChamberError( void ) +{ + F32 freshDensity = 0.0F; + F32 spentDensity = 0.0F; + F32 compFreshFlowrate = 0.0F; + F32 compSpentFlowrate = 0.0F; + + // Fresh side dialysate density + if ( getTestConfigStatus( TEST_CONFIG_DD_FP_ENABLE_BETA_1_0_HW ) == TRUE ) + { + freshDensity = ( COMP_SLOPE * getFilteredTemperatureValue( D4_TEMP ) ) + COMP_INTERCEPT; + } + else + { + freshDensity = ( COMP_SLOPE * getFilteredTemperatureValue( D99_TEMP ) ) + COMP_INTERCEPT; + } + + spentDensity = ( COMP_SLOPE * getFilteredTemperatureValue( D50_TEMP ) ) + COMP_INTERCEPT; // spent side dialysate density + compFreshFlowrate = getTDDialysateFlowrate() * freshDensity; // Qd * fresh density + compSpentFlowrate = getTDDialysateFlowrate() * spentDensity; // Qd * spent density + balancingError = compFreshFlowrate - compSpentFlowrate; // Error in g/min +} + +/*********************************************************************//** + * @brief + * The getBalancingChamberError function gets the calculated balancing chamber + * error that may be used for adjusting the ultrafiltration rate. + * @details \b Inputs: balancingError + * @details \b Outputs: none + * @return balancing chamber error + *************************************************************************/ +F32 getBalancingChamberError( void ) +{ + return balancingError; +} + +/*********************************************************************//** + * @brief * The publishBalChamberData function broadcasts the balancing chamber * execution data at defined interval. * @details \b Inputs: balChamberDataPublicationTimerCounter @@ -901,11 +1836,11 @@ data.balChamberExecState = (U32)balChamberExecState; data.balChamberSWState = (U32)balChamberSWState; data.balChamberSWFreq = getBalChamberSwitchingFreq(); - data.balChamberSwPeriod = balChamberSwitchingPeriod; - data.isBalChamberFillInProgress = isBalChamberFillInProgress; - data.currentBalChamberSwitchingCounter = currentBalChamberSwitchingCounter; - data.isPressureStalbilizedDuringFill = isPressureStalbilizedDuringFill; + data.isSpentFillComplete = isSpentFillComplete; + data.currentBalChamberSwitchingCounter = currentBalChamberFillCounter; + data.isPressureStabilizedDuringFill = isPressureStabilizedDuringFill; data.balChamberSWOnlyState = balanceChamberSwitchingOnly; + data.isBalChamberSwitchingActive = isBalChamberSwitchingActive; broadcastData( MSG_ID_DD_BAL_CHAMBER_DATA, COMM_BUFFER_OUT_CAN_DD_BROADCAST, (U08*)&data, sizeof( BAL_CHAMBER_DATA_T ) ); @@ -993,7 +1928,6 @@ * chamber switching only without dosing delivery and pressure check condition. * @details \b Inputs: tester logged in * @details \b Outputs: tdDialysateFlowrate,balanceChamberSwitchingOnly - * pendingBalanceChamberSwOnlyRequest * @param message set message from Dialin which includes the balancing chamber * to start/stop switching and update switching rate based on the flow rate. * @return TRUE if set request is successful, FALSE if not @@ -1002,7 +1936,7 @@ { BOOL result = FALSE; - // Verify tester has logged in with TD + // Verify tester has logged in with DD if ( TRUE == isTestingActivated() ) { // Verify payload length is valid @@ -1020,17 +1954,18 @@ setTDDialysateFlowrate( payload.flowrate ); // update switching rate transitionToBalChamberFill(); - // then set BC switching only flag to ignore pressure check and dosing. - setBalChamberSwitchingOnlyStatus( TRUE ); + // Set the flag to indicate that a request was made to start the switching only + balanceChamberSwitchingOnlyOnRequested = TRUE; // Now, if the current operating mode is standby mode idle state, execute the balancing chamber switching only control result = requestBCSwitchingOnlyStart(); } //Handle stop command if ( FALSE == payload.startStop ) { - //Reset the flag - setBalChamberSwitchingOnlyStatus( FALSE ); + // Set the flag to indicate that a request was made to stop the switching only + balanceChamberSwitchingOnlyOffRequested = TRUE; + //Stop the BC switching execution only control requestBCSwitchingOnlyStop(); result = TRUE;