hal.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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. //sweep counter to log every brew
  31. timer Int0Timer(&halInt0TimerHandler);
  32. timer Int1Timer(&halInt1TimerHandler);
  33. timer idleTimer(&halIdleTimerHandler);
  34. time_t heatingCycle[] = {0, 0};
  35. timespec flowTimestep[] = {{0,0},{0,0}};
  36. uint8_t flowIndex = 0;
  37. timespec pumpCycle[] = {{0,0},{0,0}};
  38. //delay of the debounce in milliseconds
  39. #define DELAY_DEBOUNCE 50
  40. //display turn off after idle time in min
  41. //minimal time is 2min
  42. #define IDLE_TIME 10
  43. /**
  44. * Initializes HAL
  45. */
  46. void halInit(void) {
  47. pinMode(RELAIS_HEAT, OUTPUT);
  48. pinMode(RELAIS_PUMP, OUTPUT);
  49. pinMode(RELAIS_POWER, OUTPUT);
  50. pinMode(PIN_PRESSURE_CTRL, INPUT);
  51. pinMode(PIN_PROXIMITY_SENSOR, INPUT);
  52. pinMode(PIN_INT0, INPUT);
  53. pinMode(PIN_INT1, INPUT);
  54. pinMode(PIN_FLOW, INPUT);
  55. pinMode(PIN_DISP, OUTPUT);
  56. idleTimer.setDivider(1200); //1 min
  57. idleCounter = 0;
  58. idle = false;
  59. clock_gettime(CLOCK_REALTIME, &flowTimestep[0]);
  60. clock_gettime(CLOCK_REALTIME, &flowTimestep[1]);
  61. halDisplayOn();
  62. if (optPower) {
  63. halMachineOn();
  64. } else {
  65. halMachineOff();
  66. }
  67. sleep(1); //wait till the machine eventually turned on when optPower
  68. pinState[3] = halIsHeating();
  69. Int0Timer.setDivider(4); //200ms
  70. Int1Timer.setDivider(4);
  71. Int0Time = 0;
  72. Int1Time = 0;
  73. flagIgnoreRlsInt0 = false;
  74. flagIgnoreRlsInt1 = false;
  75. if (wiringPiISR(PIN_INT0, INT_EDGE_BOTH, &halInt0) < 0) {
  76. logger_error("Unable to setup ISR0: %s\n", strerror(errno));
  77. return;
  78. }
  79. if (wiringPiISR(PIN_INT1, INT_EDGE_BOTH, &halInt1) < 0) {
  80. logger_error("Unable to setup ISR1: %s\n", strerror(errno));
  81. return;
  82. }
  83. if (wiringPiISR(PIN_FLOW, INT_EDGE_FALLING, &halIntFlow) < 0) {
  84. logger_error("Unable to setup ISRFLOW: %s\n", strerror(errno));
  85. return;
  86. }
  87. if (wiringPiISR(PIN_PRESSURE_CTRL, INT_EDGE_BOTH, &halIntPressure) < 0) {
  88. logger_error("Unable to setup ISRPressure: %s\n", strerror(errno));
  89. return;
  90. }
  91. if (wiringPiISR(PIN_PROXIMITY_SENSOR, INT_EDGE_BOTH, &halIntProximity) < 0) {
  92. logger_error("Unable to setup ISRProximity: %s\n", strerror(errno));
  93. return;
  94. }
  95. // in long term a manual brew detection would be nice
  96. }
  97. /**
  98. * Switches relais on
  99. * @param relais Relais ID
  100. */
  101. void halRelaisOn(int relais) {
  102. halRelaisSet(relais, LOW);
  103. }
  104. /**
  105. * Turn the display off
  106. */
  107. void halDisplayOff(){
  108. digitalWrite(PIN_DISP, LOW);
  109. }
  110. /**
  111. * Turn the display on
  112. */
  113. void halDisplayOn(){
  114. digitalWrite(PIN_DISP, HIGH);
  115. }
  116. /**
  117. * Switches relais off
  118. * @param relais Relais ID
  119. */
  120. void halRelaisOff(int relais) {
  121. halRelaisSet(relais, HIGH);
  122. }
  123. /**
  124. * Switches relais to state
  125. * @param relais Relais ID
  126. * @param state LOW(0) or HIGH(1)
  127. */
  128. void halRelaisSet(int relais, int state) {
  129. if (state != HIGH && state != LOW)
  130. return;
  131. switch (relais) {
  132. case RELAIS_POWER:
  133. case RELAIS_HEAT:
  134. case RELAIS_PUMP:
  135. digitalWrite(relais, state);
  136. break;
  137. }
  138. }
  139. /**
  140. * Returns the state of the relais relais
  141. * Returns HIGH when Relais is ON
  142. * @param relais Relais ID
  143. */
  144. int halGetRelaisState(int relais) {
  145. switch (relais) {
  146. case RELAIS_POWER:
  147. case RELAIS_HEAT:
  148. case RELAIS_PUMP:
  149. return !digitalRead(relais);
  150. break;
  151. }
  152. return -1;
  153. }
  154. /**
  155. * Interrupt routine for Int0 (Top button)
  156. */
  157. void halInt0(void) {
  158. //wait for a debounce
  159. delay(DELAY_DEBOUNCE);
  160. if (halGetInt0() && !pinState[0]) { //released
  161. logger(V_HAL, "Int0 released\n");
  162. pinState[0] = 1;
  163. if (flagIgnoreRlsInt0) {
  164. flagIgnoreRlsInt0 = false;
  165. } else {
  166. Int0Time = 0;
  167. Int0Timer.stop();
  168. halSendSignal(SigInt0Rls);
  169. }
  170. } else if(!halGetInt0() && pinState[0]) { //pressed
  171. logger(V_HAL, "Int0 pushed\n");
  172. pinState[0] = 0;
  173. halSendSignal(SigInt0Psh);
  174. Int0Time = 0;
  175. Int0Timer.start();
  176. }
  177. }
  178. /**
  179. *
  180. */
  181. void halInt0TimerHandler(void) {
  182. Int0Time += 200;
  183. if (Int0Time >= (TIME_BUTTONLONGPRESS * 1000)) {
  184. halSendSignal(SigInt0RlsLong);
  185. flagIgnoreRlsInt0 = true;
  186. Int0Time = 0;
  187. Int0Timer.stop();
  188. }
  189. }
  190. /**
  191. *
  192. */
  193. void halIdleTimerHandler(void) {
  194. if(++idleCounter == IDLE_TIME){
  195. halEnterIdle();
  196. }
  197. }
  198. /**
  199. * Interrupt routine for Int1 (Bottom button)
  200. */
  201. void halInt1(void) {
  202. delay(DELAY_DEBOUNCE);
  203. if (halGetInt1() && !pinState[1]) {
  204. logger(V_HAL, "Int1 released\n");
  205. pinState[1] = 1;
  206. if (flagIgnoreRlsInt1) {
  207. flagIgnoreRlsInt1 = false;
  208. } else {
  209. Int1Time = 0;
  210. Int1Timer.stop();
  211. halSendSignal(SigInt1Rls);
  212. }
  213. } else if(!halGetInt1() && pinState[1]) {
  214. logger(V_HAL, "Int1 pushed\n");
  215. pinState[1] = 0;
  216. halSendSignal(SigInt1Psh);
  217. Int1Time = 0;
  218. Int1Timer.start();
  219. }
  220. }
  221. /*
  222. *
  223. */
  224. void halInt1TimerHandler(void) {
  225. Int1Time += 200;
  226. if (Int1Time >= (TIME_BUTTONLONGPRESS * 1000)) {
  227. halSendSignal(SigInt1RlsLong);
  228. flagIgnoreRlsInt1 = true;
  229. Int1Time = 0;
  230. Int1Timer.stop();
  231. }
  232. }
  233. /**
  234. * Interrupt routine for the flow sensor
  235. * It counts the edgdes and stores the value in flowcnt
  236. */
  237. void halIntFlow(void) {
  238. //halRelaisOff(RELAIS_POWER);
  239. logger(V_HAL, "IntFlow triggered #%d total: %.2fml\n", flowcnt, halGetFlow());
  240. flowcnt++;
  241. //subroutine to log the flow to the database
  242. timespec deltaT;
  243. clock_gettime(CLOCK_REALTIME, &flowTimestep[flowIndex]);
  244. timespec_diff(&flowTimestep[((flowIndex + 1) % 2)], &flowTimestep[flowIndex], &deltaT);
  245. if (sqlLogFlow(2, halGetFlow()*1000, deltaT.tv_sec * 1000 + deltaT.tv_nsec/1000000)) {
  246. logger_error("hal.cpp: could not log flow to database!");
  247. return;
  248. }
  249. flowIndex = (flowIndex + 1) % 2;
  250. }
  251. /**
  252. * Interrupt routine for the pressure control
  253. * It captures the time at closing point and opening point
  254. * Reading heating time via the getHeatingTime function
  255. */
  256. void halIntPressure(void) {
  257. logger(V_HAL, "IntPressure Control triggered\n");
  258. if (halIsHeating() && !pinState[3]) {
  259. pinState[3] = 1;
  260. time(&heatingCycle[0]);
  261. halSendSignal(SigPressCls);
  262. } else if(!halIsHeating() && pinState[3]) {
  263. pinState[3] = 0;
  264. time(&heatingCycle[1]);
  265. halSendSignal(SigPressOpn);
  266. }
  267. }
  268. /**
  269. * Function to read the heating time in sec
  270. * If called during a heating process, it returns the time elapsed since the heating started
  271. * If called after a heating process, it returns the total time elapsed during the heating cycle
  272. */
  273. double halgetHeatingTime(void){
  274. //TODO check return value on negative times
  275. if (halIsHeating()) {
  276. logger(V_HAL, "Hot Heating Time: %f\n", difftime(time(NULL), heatingCycle[0]));
  277. return difftime(time(0), heatingCycle[0]);
  278. }
  279. else {
  280. logger(V_HAL, "Heating time: %f\n", difftime(heatingCycle[1], heatingCycle[0]));
  281. return difftime(heatingCycle[1], heatingCycle[0]);
  282. }
  283. }
  284. /**
  285. * Method to handle toggle of the proximity sensor
  286. */
  287. void halIntProximity(void) {
  288. delay(DELAY_DEBOUNCE);
  289. if (halProxSensorCovered() && !pinState[2]) {
  290. logger(V_HAL, "IntProximity triggered\n");
  291. pinState[2] = 1;
  292. halSendSignal(SigProxCvrd);
  293. } else if(!halProxSensorCovered() && pinState[2]){
  294. logger(V_HAL, "IntProximity triggered\n");
  295. pinState[2] = 0;
  296. halSendSignal(SigProxOpn);
  297. }
  298. }
  299. /**
  300. * Returns total flow through sensor in ml
  301. */
  302. float halGetFlow(void) {
  303. return flowcnt * FLOW_ML_PULSE;
  304. }
  305. /*
  306. * Returns the last total flow through the sensor in ml after reset
  307. */
  308. float halGetLastFlow(void) {
  309. return lastFlowcnt * FLOW_ML_PULSE;
  310. }
  311. /**
  312. * Resets the Flow counter
  313. */
  314. void halResetFlow(void) {
  315. logger(V_HAL, "Flow counter reset, amount so far: %.2f ml\n", halGetFlow());
  316. lastFlowcnt = flowcnt;
  317. flowcnt = 0;
  318. }
  319. /**
  320. * Reads the status of the Pressure Control
  321. * @return 1 (true) for closed Pressure Control(heating) and 0 (false) for open
  322. */
  323. bool halIsHeating(void) {
  324. if (digitalRead(PIN_PRESSURE_CTRL) == 0) {
  325. return true;
  326. } else {
  327. return false;
  328. }
  329. }
  330. /**
  331. * Returns status of the proximity switch
  332. * @return 1 if the proximity switch is covered and 0 if uncovered
  333. */
  334. bool halProxSensorCovered(void) {
  335. if(digitalRead(PIN_PROXIMITY_SENSOR) == 0){
  336. return false;
  337. } else {
  338. return true;
  339. }
  340. }
  341. /**
  342. * Returns the value of the top button Int0 (low active)
  343. * @return LOW or HIGH
  344. */
  345. int halGetInt0(void) {
  346. return digitalRead(PIN_INT0);
  347. }
  348. /**
  349. * Returns the value of the bottom button Int1 (low active)
  350. * @return LOW or HIGH
  351. */
  352. int halGetInt1(void) {
  353. return digitalRead(PIN_INT1);
  354. }
  355. /**
  356. * send Signal to coffee thread
  357. * @param val Integer value assigned to signal
  358. */
  359. void halSendSignal(HalSig val) {
  360. //catch if machine is idle and drop button event
  361. switch (val) {
  362. case SigInt0Psh:
  363. case SigInt1Psh:
  364. if (idle) {
  365. return;
  366. }
  367. break;
  368. case SigInt0Rls:
  369. case SigInt0RlsLong:
  370. case SigInt1Rls:
  371. case SigInt1RlsLong:
  372. if (idle) {
  373. halLeaveIdle();
  374. return;
  375. }
  376. break;
  377. default:
  378. break;
  379. }
  380. sigval value = { 0 };
  381. value.sival_int = (int) val;
  382. try {
  383. if (pthread_sigqueue(thread[THREAD_COFFEE], SIGUSR2, value)) {
  384. logger_error("hal.cpp: Failed to queue signal %d %s\n", val, strerror(errno));
  385. //No Signals reach the state machine anymore...
  386. exit(EXIT_FAILURE);
  387. }
  388. } catch (int e) {
  389. logger_error("Whoops.. %d\n", e);
  390. }
  391. }
  392. /**
  393. * Turn machine on
  394. */
  395. void halMachineOn(void) {
  396. halRelaisOn(RELAIS_HEAT);
  397. halRelaisOff(RELAIS_PUMP);
  398. halRelaisOn(RELAIS_POWER);
  399. idleTimer.stop();
  400. logger(V_HAL, "Turning machine on\n");
  401. }
  402. /**
  403. * Turn machine off
  404. */
  405. void halMachineOff(void) {
  406. halRelaisOff(RELAIS_HEAT);
  407. halRelaisOff(RELAIS_PUMP);
  408. halRelaisOff(RELAIS_POWER);
  409. idleCounter = 0;
  410. idleTimer.start();
  411. logger(V_HAL, "Turning machine off\n");
  412. }
  413. /**
  414. *
  415. */
  416. void halEnterIdle(void){
  417. logger(V_HAL, "Entering Idle Mode\n");
  418. idleTimer.stop();
  419. halDisplayOff();
  420. idle = true;
  421. }
  422. /**
  423. *
  424. */
  425. void halLeaveIdle(void){
  426. idleCounter = 0;
  427. logger(V_HAL, "Leaving Idle Mode\n");
  428. halDisplayOn();
  429. idleTimer.start();
  430. idle = false;
  431. }
  432. /**
  433. * Wrapper function to turn the pump on
  434. * and to measure how long the pump is running
  435. */
  436. void halPumpOn(void){
  437. halRelaisOn(RELAIS_PUMP);
  438. clock_gettime(CLOCK_REALTIME, &pumpCycle[0]);
  439. }
  440. /**
  441. * Wrapper function to turn the pump off
  442. * and to measure how long the pump is running
  443. */
  444. void halPumpOff(void){
  445. halRelaisOff(RELAIS_PUMP);
  446. clock_gettime(CLOCK_REALTIME, &pumpCycle[1]);
  447. }
  448. /**
  449. * Function to get the elapsed time the pump is running in ms
  450. * when the pump is on, this function returns the time between turning the pump on and the call
  451. * when the pump is off, this function returns the time elapsed in the last pump cycle
  452. */
  453. double halGetPumpTime(void){
  454. timespec now;
  455. timespec diff = {0,0};
  456. if(halGetRelaisState(RELAIS_PUMP) == HIGH){//pump is on
  457. clock_gettime(CLOCK_REALTIME, &now);
  458. timespec_diff(&pumpCycle[0], &now, &diff);
  459. }
  460. else {
  461. timespec_diff(&pumpCycle[0], &pumpCycle[1], &diff);
  462. }
  463. return diff.tv_sec * 1000 + diff.tv_nsec/1000000;
  464. }
  465. /**
  466. * Function to calculate the difference between two timespecs
  467. */
  468. void timespec_diff(timespec *start, timespec *stop, timespec *result) {
  469. long int secDiff = stop->tv_sec - start->tv_sec;
  470. long int nsecDiff = stop->tv_nsec - start->tv_nsec;
  471. if (secDiff > 0) {
  472. if (nsecDiff >= 0) {
  473. result->tv_sec = secDiff;
  474. result->tv_nsec = nsecDiff;
  475. } else if (nsecDiff < 0) {
  476. result->tv_sec = --secDiff;
  477. result->tv_nsec = 1000000000 + nsecDiff;
  478. }
  479. } else if (secDiff < 0) {
  480. if (nsecDiff >= 0) {
  481. result->tv_sec = ++secDiff;
  482. result->tv_nsec = -(1000000000 - nsecDiff);
  483. } else if (nsecDiff < 0) {
  484. result->tv_sec = secDiff;
  485. result->tv_nsec = nsecDiff;
  486. }
  487. } else if (secDiff == 0){
  488. result->tv_sec = secDiff;
  489. result->tv_nsec = nsecDiff;
  490. }
  491. return;
  492. }