hal.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664
  1. /*
  2. * hal.cpp
  3. *
  4. * Created on: Aug 3, 2016
  5. * Author: Philipp Hinz, Sebastian Vendt
  6. */
  7. #include <wiringPi.h>
  8. #include <stdlib.h>
  9. #include <stdint.h>
  10. #include <errno.h>
  11. #include <string.h>
  12. #include <signal.h>
  13. #include <ctime>
  14. #include <time.h>
  15. #include <unistd.h>
  16. #include "hal.h"
  17. #include "global.h"
  18. #include "logger.h"
  19. #include "timer.h"
  20. #include "database.h"
  21. typedef struct timespec timespec;
  22. volatile int flowcnt = 0;
  23. int lastFlowcnt = 0;
  24. int Int0Time, Int1Time;
  25. int idleCounter;
  26. bool idle;
  27. bool flagIgnoreRlsInt0, flagIgnoreRlsInt1;
  28. //storage for the last state of the buttons, the proximity sensor and the pressure sensor
  29. int pinState[4] = {1, 1, 1, 0};
  30. //state of the rotary encoder
  31. //0: rotary1 state at t-1
  32. //1: rotary2 state at t-1
  33. //2: rotary1 state at t
  34. //3: rotary2 state at t
  35. int rotaryState[4] = {1, 0, 0, 1};
  36. //sweep counter to log every brew
  37. uint16_t logcycle = 1;
  38. timer Int0Timer(&halInt0TimerHandler);
  39. timer Int1Timer(&halInt1TimerHandler);
  40. timer idleTimer(&halIdleTimerHandler);
  41. time_t heatingCycle[] = {0, 0};
  42. timespec flowTimestep[] = {{0,0},{0,0}};
  43. uint8_t flowIndex = 0;
  44. int16_t tickCounter = 0;
  45. timespec pumpCycle[] = {{0,0},{0,0}};
  46. //delay of the debounce in milliseconds
  47. #define DELAY_DEBOUNCE 50
  48. #define DELAY_MICRODEB 2
  49. //display turn off after idle time in min
  50. //minimal time is 2min
  51. #define IDLE_TIME 10
  52. /**
  53. * Initializes HAL
  54. */
  55. void halInit(void) {
  56. pinMode(RELAIS_HEAT, OUTPUT);
  57. pinMode(RELAIS_PUMP, OUTPUT);
  58. pinMode(RELAIS_POWER, OUTPUT);
  59. pinMode(PIN_PRESSURE_CTRL, INPUT);
  60. pinMode(PIN_PROXIMITY_SENSOR, INPUT);
  61. pinMode(PIN_INT0, INPUT);
  62. pinMode(PIN_INT1, INPUT);
  63. pinMode(PIN_FLOW, INPUT);
  64. pinMode(PIN_DISP, OUTPUT);
  65. pinMode(PIN_ROTARY1, INPUT);
  66. pinMode(PIN_ROTARY2, INPUT);
  67. idleTimer.setDivider(1200); //1 min
  68. idleCounter = 0;
  69. idle = false;
  70. clock_gettime(CLOCK_REALTIME, &flowTimestep[0]);
  71. clock_gettime(CLOCK_REALTIME, &flowTimestep[1]);
  72. halDisplayOn();
  73. if (optPower) {
  74. halMachineOn();
  75. } else {
  76. halMachineOff();
  77. }
  78. sleep(1); //wait till the machine eventually turned on when optPower
  79. pinState[3] = halIsHeating();
  80. Int0Timer.setDivider(4); //200ms
  81. Int1Timer.setDivider(4);
  82. Int0Time = 0;
  83. Int1Time = 0;
  84. flagIgnoreRlsInt0 = false;
  85. flagIgnoreRlsInt1 = false;
  86. event_subscribe("terminate", &halTerminate);
  87. if (wiringPiISR(PIN_INT0, INT_EDGE_BOTH, &halInt0) < 0) {
  88. logger_error("Unable to setup ISR0: %s\n", strerror(errno));
  89. return;
  90. }
  91. if (wiringPiISR(PIN_INT1, INT_EDGE_BOTH, &halInt1) < 0) {
  92. logger_error("Unable to setup ISR1: %s\n", strerror(errno));
  93. return;
  94. }
  95. if (wiringPiISR(PIN_FLOW, INT_EDGE_FALLING, &halIntFlow) < 0) {
  96. logger_error("Unable to setup ISRFLOW: %s\n", strerror(errno));
  97. return;
  98. }
  99. if (wiringPiISR(PIN_PRESSURE_CTRL, INT_EDGE_BOTH, &halIntPressure) < 0) {
  100. logger_error("Unable to setup ISRPressure: %s\n", strerror(errno));
  101. return;
  102. }
  103. if (wiringPiISR(PIN_PROXIMITY_SENSOR, INT_EDGE_BOTH, &halIntProximity) < 0) {
  104. logger_error("Unable to setup ISRProximity: %s\n", strerror(errno));
  105. return;
  106. }
  107. if (wiringPiISR(PIN_ROTARY1, INT_EDGE_BOTH, &halIntRotary) < 0) {
  108. logger_error("Unable to setup ISRRotary2: %s\n", strerror(errno));
  109. return;
  110. }
  111. //TODO when machine is turned off above the logcycle 1 is written back from cache...
  112. if (!(logcycle = sqlGetConf(CFGSweepCounter))) {
  113. logger_error("hal.cpp: Couldn't read the logcycle counter from the database\n");
  114. //pthread_exit(EXIT_SUCCESS);
  115. exit(EXIT_FAILURE);
  116. }
  117. }
  118. /**
  119. * Switches relais on
  120. * @param relais Relais ID
  121. */
  122. void halRelaisOn(int relais) {
  123. halRelaisSet(relais, LOW);
  124. }
  125. /**
  126. * Turn the display off
  127. */
  128. void halDisplayOff(){
  129. digitalWrite(PIN_DISP, LOW);
  130. }
  131. /**
  132. * Turn the display on
  133. */
  134. void halDisplayOn(){
  135. digitalWrite(PIN_DISP, HIGH);
  136. }
  137. /**
  138. * Switches relais off
  139. * @param relais Relais ID
  140. */
  141. void halRelaisOff(int relais) {
  142. halRelaisSet(relais, HIGH);
  143. }
  144. /**
  145. * Switches relais to state
  146. * @param relais Relais ID
  147. * @param state LOW(0) or HIGH(1)
  148. */
  149. void halRelaisSet(int relais, int state) {
  150. if (state != HIGH && state != LOW)
  151. return;
  152. switch (relais) {
  153. case RELAIS_POWER:
  154. case RELAIS_HEAT:
  155. case RELAIS_PUMP:
  156. digitalWrite(relais, state);
  157. break;
  158. }
  159. }
  160. /**
  161. * Returns the state of the relais relais
  162. * Returns HIGH when Relais is ON
  163. * @param relais Relais ID
  164. */
  165. int halGetRelaisState(int relais) {
  166. switch (relais) {
  167. case RELAIS_POWER:
  168. case RELAIS_HEAT:
  169. case RELAIS_PUMP:
  170. return !digitalRead(relais);
  171. break;
  172. }
  173. return -1;
  174. }
  175. /**
  176. *
  177. */
  178. void halIntRotary(void) {
  179. //delay(DELAY_MICRODEB);
  180. rotaryState[2] = digitalRead(PIN_ROTARY1);
  181. rotaryState[3] = digitalRead(PIN_ROTARY2);
  182. if (rotaryState[0] != rotaryState[2]) {
  183. //check for the status of the other pin
  184. if (rotaryState[1] != rotaryState[3]) {
  185. if ((rotaryState[2] == HIGH && rotaryState[3] == LOW) || (rotaryState[2] == LOW && rotaryState[3] == HIGH)) {
  186. //clockwise rotation
  187. tickCounter++;
  188. if (!(abs(tickCounter) % ROTARY_STEPSIZE)) {
  189. //logger(V_HAL, "rotary encoder CW \n");
  190. halSendSignal(SigRotCW);
  191. tickCounter = 0;
  192. }
  193. } else if ((rotaryState[2] == HIGH && rotaryState[3] == HIGH) || (rotaryState[2] == LOW && rotaryState[3] == LOW)) {
  194. //counterclockwise rotation
  195. tickCounter--;
  196. if (!(abs(tickCounter) % ROTARY_STEPSIZE)) {
  197. //logger(V_HAL, "rotary encoder CCW \n");
  198. halSendSignal(SigRotCCW);
  199. tickCounter = 0;
  200. }
  201. }
  202. rotaryState[1] = rotaryState[3];
  203. }
  204. rotaryState[0] = rotaryState[2];
  205. }
  206. }
  207. /**
  208. * Interrupt routine for Int0 (Top button)
  209. */
  210. void halInt0(void) {
  211. //wait for a debounce
  212. delay(DELAY_DEBOUNCE);
  213. if (halGetInt0() && !pinState[0]) { //released
  214. logger(V_HAL, "Int0 released\n");
  215. pinState[0] = 1;
  216. if (flagIgnoreRlsInt0) {
  217. flagIgnoreRlsInt0 = false;
  218. } else {
  219. Int0Time = 0;
  220. Int0Timer.stop();
  221. halSendSignal(SigInt0Rls);
  222. }
  223. } else if(!halGetInt0() && pinState[0]) { //pressed
  224. logger(V_HAL, "Int0 pushed\n");
  225. pinState[0] = 0;
  226. halSendSignal(SigInt0Psh);
  227. Int0Time = 0;
  228. Int0Timer.start();
  229. }
  230. }
  231. /**
  232. *
  233. */
  234. void halInt0TimerHandler(void) {
  235. Int0Time += 200;
  236. if (Int0Time >= (TIME_BUTTONLONGPRESS * 1000)) {
  237. halSendSignal(SigInt0RlsLong);
  238. flagIgnoreRlsInt0 = true;
  239. Int0Time = 0;
  240. Int0Timer.stop();
  241. }
  242. }
  243. /**
  244. *
  245. */
  246. void halIdleTimerHandler(void) {
  247. if(++idleCounter == IDLE_TIME){
  248. halEnterIdle();
  249. }
  250. }
  251. /**
  252. * Interrupt routine for Int1 (Bottom button)
  253. */
  254. void halInt1(void) {
  255. delay(DELAY_DEBOUNCE);
  256. if (halGetInt1() && !pinState[1]) {
  257. logger(V_HAL, "Int1 released\n");
  258. pinState[1] = 1;
  259. if (flagIgnoreRlsInt1) {
  260. flagIgnoreRlsInt1 = false;
  261. } else {
  262. Int1Time = 0;
  263. Int1Timer.stop();
  264. halSendSignal(SigInt1Rls);
  265. }
  266. } else if(!halGetInt1() && pinState[1]) {
  267. logger(V_HAL, "Int1 pushed\n");
  268. pinState[1] = 0;
  269. halSendSignal(SigInt1Psh);
  270. Int1Time = 0;
  271. Int1Timer.start();
  272. }
  273. }
  274. /*
  275. *
  276. */
  277. void halInt1TimerHandler(void) {
  278. Int1Time += 200;
  279. if (Int1Time >= (TIME_BUTTONLONGPRESS * 1000)) {
  280. halSendSignal(SigInt1RlsLong);
  281. flagIgnoreRlsInt1 = true;
  282. Int1Time = 0;
  283. Int1Timer.stop();
  284. }
  285. }
  286. /**
  287. * Interrupt routine for the flow sensor
  288. * It counts the edges and stores the value in flowcnt
  289. */
  290. void halIntFlow(void) {
  291. //halRelaisOff(RELAIS_POWER);
  292. logger(V_HAL, "IntFlow triggered #%d total: %.2fml\n", flowcnt, halGetFlow());
  293. flowcnt++;
  294. //detect a manual brewing process
  295. //TODO to be able to detect a manual brewing process we need to have the following
  296. //autoclear the flowcnt after certain idle time
  297. //detect when the the flow is triggered but the pump is not started from software
  298. //here we need to suppress the false alarms when the pump is turned off and slowly running out
  299. //subroutine to log the flow to the database
  300. timespec deltaT;
  301. clock_gettime(CLOCK_REALTIME, &flowTimestep[flowIndex]);
  302. timespec_diff(&flowTimestep[((flowIndex + 1) % 2)], &flowTimestep[flowIndex], &deltaT);
  303. if (sqlLogFlow(logcycle, halGetFlow()*1000, deltaT.tv_sec * 1000 + deltaT.tv_nsec/1000000)) {
  304. logger_error("hal.cpp: could not log flow to database!");
  305. return;
  306. }
  307. flowIndex = (flowIndex + 1) % 2;
  308. }
  309. /**
  310. * Interrupt routine for the pressure control
  311. * It captures the time at closing point and opening point
  312. * Reading heating time via the getHeatingTime function
  313. */
  314. void halIntPressure(void) {
  315. logger(V_HAL, "IntPressure Control triggered\n");
  316. if (halIsHeating() && !pinState[3]) {
  317. pinState[3] = 1;
  318. time(&heatingCycle[0]);
  319. halSendSignal(SigPressCls);
  320. } else if(!halIsHeating() && pinState[3]) {
  321. pinState[3] = 0;
  322. time(&heatingCycle[1]);
  323. halSendSignal(SigPressOpn);
  324. }
  325. }
  326. /**
  327. * Function to read the heating time in sec
  328. * If called during a heating process, it returns the time elapsed since the heating started
  329. * If called after a heating process, it returns the total time elapsed during the heating cycle
  330. */
  331. double halgetHeatingTime(void){
  332. //TODO check return value on negative times
  333. //TODO move the tracking of the heating time into hal.cpp and fix issue of wrong tracking -> inital pressure close is not
  334. //recognized and so heatingCycle has no time
  335. if (halIsHeating()) {
  336. logger(V_HAL, "Hot Heating Time: %f\n", difftime(time(NULL), heatingCycle[0]));
  337. return difftime(time(0), heatingCycle[0]);
  338. }
  339. else {
  340. logger(V_HAL, "Heating time: %f\n", difftime(heatingCycle[1], heatingCycle[0]));
  341. return difftime(heatingCycle[1], heatingCycle[0]);
  342. }
  343. }
  344. /**
  345. * Method to handle toggle of the proximity sensor
  346. */
  347. void halIntProximity(void) {
  348. delay(DELAY_DEBOUNCE);
  349. if (halProxSensorCovered() && !pinState[2]) {
  350. logger(V_HAL, "IntProximity triggered\n");
  351. pinState[2] = 1;
  352. halSendSignal(SigProxCvrd);
  353. } else if(!halProxSensorCovered() && pinState[2]){
  354. logger(V_HAL, "IntProximity triggered\n");
  355. pinState[2] = 0;
  356. halSendSignal(SigProxOpn);
  357. }
  358. }
  359. /**
  360. * Returns total flow through sensor in ml
  361. */
  362. float halGetFlow(void) {
  363. return flowcnt * FLOW_ML_PULSE;
  364. }
  365. /*
  366. * Returns the last total flow through the sensor in ml after reset
  367. */
  368. float halGetLastFlow(void) {
  369. return lastFlowcnt * FLOW_ML_PULSE;
  370. }
  371. /**
  372. * Resets the Flow counter
  373. */
  374. void halResetFlow(void) {
  375. logger(V_HAL, "Flow counter reset, amount so far: %.2f ml\n", halGetFlow());
  376. lastFlowcnt = flowcnt;
  377. flowcnt = 0;
  378. }
  379. /**
  380. * Reads the status of the Pressure Control
  381. * @return 1 (true) for closed Pressure Control(heating) and 0 (false) for open
  382. */
  383. bool halIsHeating(void) {
  384. if (digitalRead(PIN_PRESSURE_CTRL) == 0) {
  385. return true;
  386. } else {
  387. return false;
  388. }
  389. }
  390. /**
  391. * Returns status of the proximity switch
  392. * @return 1 if the proximity switch is covered and 0 if uncovered
  393. */
  394. bool halProxSensorCovered(void) {
  395. if(digitalRead(PIN_PROXIMITY_SENSOR) == 0){
  396. return false;
  397. } else {
  398. return true;
  399. }
  400. }
  401. /**
  402. * Returns the value of the top button Int0 (low active)
  403. * @return LOW or HIGH
  404. */
  405. int halGetInt0(void) {
  406. return digitalRead(PIN_INT0);
  407. }
  408. /**
  409. * Returns the value of the bottom button Int1 (low active)
  410. * @return LOW or HIGH
  411. */
  412. int halGetInt1(void) {
  413. return digitalRead(PIN_INT1);
  414. }
  415. /**
  416. * send Signal to coffee thread
  417. * @param val Integer value assigned to signal
  418. */
  419. void halSendSignal(HalSig val) {
  420. //reboot pi when lower button is pressed long
  421. if (val == SigInt1RlsLong) {
  422. event_trigger("terminate");
  423. sleep(3);
  424. system("reboot");
  425. }
  426. //catch if machine is idle and drop button event
  427. switch (val) {
  428. case SigInt0Psh:
  429. case SigInt1Psh:
  430. if (idle) {
  431. return;
  432. }
  433. break;
  434. case SigInt0Rls:
  435. case SigInt0RlsLong:
  436. case SigInt1Rls:
  437. case SigRotCCW:
  438. case SigRotCW:
  439. if (idle) {
  440. halLeaveIdle();
  441. return;
  442. }
  443. break;
  444. default:
  445. break;
  446. }
  447. sigval value = { 0 };
  448. value.sival_int = (int) val;
  449. try {
  450. if (pthread_sigqueue(thread[THREAD_COFFEE], SIGUSR2, value)) {
  451. logger_error("hal.cpp: Failed to queue signal %d %s\n", val, strerror(errno));
  452. //No Signals reach the state machine anymore...
  453. exit(EXIT_FAILURE);
  454. }
  455. } catch (int e) {
  456. logger_error("Whoops.. %d\n", e);
  457. }
  458. }
  459. /**
  460. * Turn machine on
  461. */
  462. void halMachineOn(void) {
  463. halRelaisOn(RELAIS_HEAT);
  464. halRelaisOff(RELAIS_PUMP);
  465. halRelaisOn(RELAIS_POWER);
  466. idleTimer.stop();
  467. logger(V_HAL, "Turning machine on\n");
  468. }
  469. /**
  470. * Turn machine off
  471. */
  472. void halMachineOff(void) {
  473. halRelaisOff(RELAIS_HEAT);
  474. halRelaisOff(RELAIS_PUMP);
  475. halRelaisOff(RELAIS_POWER);
  476. idleCounter = 0;
  477. idleTimer.start();
  478. halWriteBackCache();
  479. logger(V_HAL, "Turning machine off\n");
  480. }
  481. /**
  482. *
  483. */
  484. void halEnterIdle(void){
  485. logger(V_HAL, "Entering Idle Mode\n");
  486. idleTimer.stop();
  487. halDisplayOff();
  488. idle = true;
  489. }
  490. /**
  491. *
  492. */
  493. void halLeaveIdle(void){
  494. idleCounter = 0;
  495. logger(V_HAL, "Leaving Idle Mode\n");
  496. halDisplayOn();
  497. idleTimer.start();
  498. idle = false;
  499. }
  500. /**
  501. * Wrapper function to turn the pump on
  502. * and to measure how long the pump is running
  503. * @param cycle the number of the sweep in the database
  504. */
  505. void halPumpOn(){
  506. halRelaisOn(RELAIS_PUMP);
  507. clock_gettime(CLOCK_REALTIME, &pumpCycle[0]);
  508. }
  509. /**
  510. *
  511. */
  512. void halIncreaseLogCycleCounter(void){
  513. logcycle = logcycle + 1;
  514. }
  515. /**
  516. * Wrapper function to turn the pump off
  517. * and to measure how long the pump is running
  518. */
  519. void halPumpOff(void){
  520. halRelaisOff(RELAIS_PUMP);
  521. clock_gettime(CLOCK_REALTIME, &pumpCycle[1]);
  522. }
  523. /**
  524. * Function to get the elapsed time the pump is running in ms
  525. * when the pump is on, this function returns the time between turning the pump on and the call
  526. * when the pump is off, this function returns the time elapsed in the last pump cycle
  527. */
  528. double halGetPumpTime(void){
  529. timespec now;
  530. timespec diff = {0,0};
  531. if(halGetRelaisState(RELAIS_PUMP) == HIGH){//pump is on
  532. clock_gettime(CLOCK_REALTIME, &now);
  533. timespec_diff(&pumpCycle[0], &now, &diff);
  534. }
  535. else {
  536. timespec_diff(&pumpCycle[0], &pumpCycle[1], &diff);
  537. }
  538. return diff.tv_sec * 1000 + diff.tv_nsec/1000000;
  539. }
  540. /**
  541. * Function to calculate the difference between two timespecs
  542. */
  543. void timespec_diff(timespec *start, timespec *stop, timespec *result) {
  544. long int secDiff = stop->tv_sec - start->tv_sec;
  545. long int nsecDiff = stop->tv_nsec - start->tv_nsec;
  546. if (secDiff > 0) {
  547. if (nsecDiff >= 0) {
  548. result->tv_sec = secDiff;
  549. result->tv_nsec = nsecDiff;
  550. } else if (nsecDiff < 0) {
  551. result->tv_sec = --secDiff;
  552. result->tv_nsec = 1000000000 + nsecDiff;
  553. }
  554. } else if (secDiff < 0) {
  555. if (nsecDiff >= 0) {
  556. result->tv_sec = ++secDiff;
  557. result->tv_nsec = -(1000000000 - nsecDiff);
  558. } else if (nsecDiff < 0) {
  559. result->tv_sec = secDiff;
  560. result->tv_nsec = nsecDiff;
  561. }
  562. } else if (secDiff == 0){
  563. result->tv_sec = secDiff;
  564. result->tv_nsec = nsecDiff;
  565. }
  566. return;
  567. }
  568. /*
  569. * Handler for Termination of the hal
  570. */
  571. void halTerminate(event_t *event){
  572. halWriteBackCache();
  573. }
  574. /*
  575. * writing back non volatile variables of the hal to the database: SweepCounter
  576. */
  577. void halWriteBackCache(){
  578. if (sqlSetConf(CFGSweepCounter, logcycle)) {
  579. logger_error("hal.cpp: Couldn't write logcycle to database");
  580. return;
  581. }
  582. logger(V_BREW, "Writing back logcycle %d\n", logcycle);
  583. }