hal.cpp 14 KB

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