int main(int argc, char **argv) { // Setup setup_config(argc,argv); setup_state(); setup_sigs(); // Objects logger.setup(); server.setup(); sensor.setup(); heater.setup(); // Thread if(pthread_create( &serverThread, NULL, serverPoll, NULL) != 0) logger.fail("Server thread creation failure"); float chosenSetPoint; int sensorResult = 0; clock_t nextLoop; conf.update = 1000/conf.update; timeTick(); nextLoop = state.time + conf.update; logger.info("Starting up Coffeed"); while(state.run) { // Time update timeTick(); if(state.time >= nextLoop) { // Get sensor data sensorResult = sensor.update(); // If active choose set point if(state.active) { if(state.brewmode == TRUE) chosenSetPoint = conf.brewPoint; else chosenSetPoint = conf.steamPoint; // Sensor fault if(!sensorResult) { logger.fail("Sensor read failure"); state.active = FALSE; heater.off(); } // Tuning mode else if(state.tuning != FALSE) { // Begin if(state.tuning == 2) { state.tuning = TRUE; heater.setPower(50); aTune.cancel(); //aTune.setNoiseBand(1); //aTune.setOutputStep(50); //aTune.setLookbackSec(20); //aTune.setControlType(1); logger.info("Autotuning BEGIN %f %f %f",conf.pgain,conf.igain,conf.dgain); } // While (1) we want to tune + (2) update is not done else if(state.tuning == TRUE && aTune.update() == FALSE) { logger.info("tuning"); } // Tuning complete because state.tuning = TRUE but aTune == TRUE else { logger.info("tuning successful am I right?"); // Done conf.pgain = aTune.getKp(); conf.igain = aTune.getKi(); conf.dgain = aTune.getKd(); logger.info("Autotuning FINISH %f %f %f",conf.pgain,conf.igain,conf.dgain); state.tuning = FALSE; } } // Regular control else { // PID result state.pidResult = pid.result(chosenSetPoint, state.tempPoint); // Set Heater Duty heater.setPower( state.pidResult ); // Log logger.debug("PID Result %d temperature %f setP %f brewP %f steamP %f", state.pidResult, state.tempPoint, chosenSetPoint, conf.brewPoint, conf.steamPoint); } } // Inactive system else { // Tuning can't happen in a inactive system if(state.tuning != FALSE) { state.tuning = FALSE; aTune.cancel(); } if(state.brewmode) state.brewmode = TRUE; chosenSetPoint = 0; heater.off(); } // Get Heater Duty // This should be centralized to the heater state.power = heater.getPower(); // Schedule the next loop after the whole operation nextLoop = state.time + conf.update; } else { // Sleep until we need you usleep(1000 * (nextLoop - state.time)); } } logger.info("Shutting down Coffeed"); }