hal.cpp 13 KB

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