hal.cpp 14 KB

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