main.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. /*---------------------------------------------------------------*
  2. * Automotive GPS logger (C)ChaN, 2014 *
  3. * Modified k4be, 2022 *
  4. *---------------------------------------------------------------*/
  5. #include <avr/io.h>
  6. #include <avr/interrupt.h>
  7. #include <avr/sleep.h>
  8. #include <util/delay.h>
  9. #include <avr/pgmspace.h>
  10. #include <avr/wdt.h>
  11. #include <string.h>
  12. #include <stdlib.h>
  13. #include "main.h"
  14. #include "ff.h"
  15. #include "diskio.h"
  16. #include "uart0.h"
  17. #include "uart1.h"
  18. #include "xprintf.h"
  19. #include "stime.h"
  20. #include "ds18b20.h"
  21. #include "I2C.h"
  22. #include "expander.h"
  23. #include "HD44780-I2C.h"
  24. #include "gpx.h"
  25. #include "display.h"
  26. #include "working_modes.h"
  27. #include "timec.h"
  28. /*FUSES = {0xFF, 0x11, 0xFE};*/ /* ATmega644PA fuses: Low, High, Extended.
  29. This is the fuse settings for this project. The fuse bits will be included
  30. in the output hex file with program code. However some old flash programmers
  31. cannot load the fuse bits from hex file. If it is the case, remove this line
  32. and use these values to program the fuse bits. */
  33. volatile struct system_s System;
  34. FATFS Fatfs; /* File system object for each logical drive */
  35. FIL gps_log; /* File object */
  36. FIL system_log; /* System log file */
  37. char Line[100]; /* Line buffer */
  38. time_t utc; /* current time */
  39. struct location_s location;
  40. void start_bootloader(void) {
  41. typedef void (*do_reboot_t)(void);
  42. const do_reboot_t do_reboot = (do_reboot_t)((FLASHEND - 1023) >> 1);
  43. cli();
  44. uart1_deinit();
  45. /* close_files(0); // FIXME not working
  46. display_state(DISPLAY_STATE_BOOTLOADER);*/
  47. LCD_Clear(); /* Do not call display.c here! */
  48. LCD_GoTo(0,0);
  49. LCD_WriteTextP(PSTR("Aktualizacja"));
  50. LCD_GoTo(8,1);
  51. LCD_WriteTextP(PSTR("softu..."));
  52. TCCR0A = TCCR1A = TCCR2A = 0; // make sure interrupts are off and timers are reset.
  53. do_reboot();
  54. wdt_enable(WDTO_15MS);
  55. while(1);
  56. }
  57. /*---------------------------------------------------------*/
  58. /* 100Hz timer interrupt generated by OC1A */
  59. /*---------------------------------------------------------*/
  60. ISR(TIMER1_COMPA_vect)
  61. {
  62. static WORD ivt_sync;
  63. // static BYTE led;
  64. static unsigned int power_sw;
  65. unsigned int *volatile ctimer;
  66. unsigned char i;
  67. unsigned char k;
  68. static unsigned char oldk;
  69. for(i=0; i<sizeof(System.timers)/sizeof(unsigned int); i++){ // decrement every variable from timers struct unless it's already zero
  70. ctimer = ((unsigned int *)&System.timers) + i;
  71. if(*ctimer)
  72. (*ctimer)--;
  73. }
  74. /* Sync interval */
  75. if (IVT_SYNC && ++ivt_sync >= IVT_SYNC * 100) {
  76. ivt_sync = 0;
  77. FLAGS |= F_SYNC;
  78. }
  79. /* Green LED drive */
  80. /* if (FLAGS & F_POW) {
  81. if ((FLAGS & F_GPSOK) || (++led & 0x20)) {
  82. LEDG_ON();
  83. } else {
  84. LEDG_OFF();
  85. }
  86. } else {
  87. LEDG_OFF();
  88. }*/
  89. /* MMC/SD timer procedure */
  90. disk_timerproc();
  91. /* Switch off */
  92. if (POWER_SW_PRESSED()) {
  93. if (++power_sw == POWER_SW_TIME){
  94. FLAGS |= F_POWEROFF;
  95. power_sw++;
  96. }
  97. } else {
  98. power_sw = 0;
  99. }
  100. if (uart1_test() && uart1_get() == '0' && uart1_get() == ' '){
  101. LEDB_ON();
  102. start_bootloader();
  103. LEDR_ON();
  104. }
  105. /* keyboard */
  106. k = ((~PIND) >> 4) & 0x0f;
  107. if (POWER_SW_PRESSED())
  108. k |= K_POWER;
  109. if (k && k != oldk) {
  110. System.keypress = k;
  111. oldk = k;
  112. }
  113. if (!k)
  114. oldk = 0;
  115. }
  116. unsigned char getkey(void) {
  117. unsigned char key = System.keypress;
  118. System.keypress = 0;
  119. return key;
  120. }
  121. /* Power supply monitor */
  122. ISR(ADC_vect)
  123. {
  124. float bat_volt;
  125. static unsigned int adc_buf;
  126. static unsigned char adc_cnt;
  127. static BYTE lvt;
  128. adc_buf += ADC;
  129. if(++adc_cnt < 15)
  130. return;
  131. bat_volt = (float)adc_buf/(float)(adc_cnt)/VI_MULT;
  132. adc_buf = 0;
  133. adc_cnt = 0;
  134. System.bat_volt = bat_volt;
  135. if (FLAGS & F_LVD) {
  136. if (bat_volt > VI_LVH) {
  137. FLAGS &= ~F_LVD;
  138. lvt = 0;
  139. }
  140. } else {
  141. if (bat_volt < VI_LVL) {
  142. if (++lvt >= 3)
  143. FLAGS |= F_LVD;
  144. } else {
  145. lvt = 0;
  146. }
  147. }
  148. }
  149. static void sleep(void) {
  150. set_sleep_mode(SLEEP_MODE_IDLE);
  151. sleep_enable();
  152. sleep_cpu();
  153. sleep_disable();
  154. }
  155. /*----------------------------------------------------*/
  156. /* Get a line received from GPS module */
  157. /*----------------------------------------------------*/
  158. UINT get_line ( /* 0:Brownout or timeout, >0: Number of bytes received. */
  159. char *buff,
  160. UINT sz_buf
  161. )
  162. {
  163. char c;
  164. UINT i = 0;
  165. set_timer(recv_timeout, 1000);
  166. for (;;) {
  167. wdt_reset();
  168. if (FLAGS & (F_LVD | F_POWEROFF))
  169. return 0; /* A brownout is detected */
  170. if (timer_expired(recv_timeout))
  171. return 0; /* timeout; continue the main loop */
  172. if (!uart0_test()) {
  173. sleep();
  174. continue;
  175. }
  176. c = (char)uart0_get();
  177. uart1_put(c);
  178. if (i == 0 && c != '$')
  179. continue; /* Find start of line */
  180. buff[i++] = c;
  181. if (c == '\n')
  182. break; /* EOL */
  183. if (i >= sz_buf)
  184. i = 0; /* Buffer overflow (abort this line) */
  185. }
  186. return i;
  187. }
  188. /*--------------------------------------------------------------------------*/
  189. /* Controls */
  190. void beep (UINT len, BYTE cnt)
  191. {
  192. while (cnt--) {
  193. BEEP_ON();
  194. set_timer(beep, len);
  195. while(!timer_expired(beep)) {};
  196. BEEP_OFF();
  197. set_timer(beep, len);
  198. while(!timer_expired(beep)) {};
  199. }
  200. }
  201. /* Compare sentence header string */
  202. BYTE gp_comp (const char *str1, __flash const char *str2)
  203. {
  204. char c;
  205. do {
  206. c = pgm_read_byte(str2++);
  207. } while (c && c == *str1++);
  208. return c;
  209. }
  210. #define FIELD_BUF_LEN 32
  211. /* Get a column item */
  212. static
  213. const char* gp_col ( /* Returns pointer to the item (returns a NULL when not found) */
  214. const char* buf, /* Pointer to the sentence */
  215. BYTE col /* Column number (0 is the 1st item) */
  216. ) {
  217. BYTE c;
  218. static char field_buf[FIELD_BUF_LEN];
  219. unsigned char length = 0;
  220. while (col) {
  221. do {
  222. c = *buf++;
  223. if (c <= ' ') return NULL;
  224. } while (c != ',');
  225. col--;
  226. }
  227. while (*buf && *buf != ',' && length < FIELD_BUF_LEN-1) {
  228. field_buf[length++] = *buf++;
  229. }
  230. field_buf[length] = '\0';
  231. return field_buf;
  232. }
  233. static
  234. BYTE gp_val2 (
  235. const char *db
  236. )
  237. {
  238. BYTE n, m;
  239. n = db[0] - '0';
  240. if (n >= 10)
  241. return 0;
  242. m = db[1] - '0';
  243. if (m >= 10)
  244. return 0;
  245. return n * 10 + m;
  246. }
  247. static
  248. UINT gp_val3 (
  249. const char *db
  250. )
  251. {
  252. BYTE n, m, l;
  253. n = db[0] - '0';
  254. if (n >= 10)
  255. return 0;
  256. m = db[1] - '0';
  257. if (m >= 10)
  258. return 0;
  259. l = db[2] - '0';
  260. if (l >= 10)
  261. return 0;
  262. return n * 100 + m * 10 + l;
  263. }
  264. static time_t gp_rmc_parse(const char *str) {
  265. const char *p;
  266. struct tm tmc;
  267. p = gp_col(str, 1); /* Get h:m:s */
  268. if (!p)
  269. return 0;
  270. tmc.tm_hour = gp_val2(p);
  271. tmc.tm_min = gp_val2(p+2);
  272. tmc.tm_sec = gp_val2(p+4);
  273. p = gp_col(str, 9); /* Get y:m:d */
  274. if (!p)
  275. return 0;
  276. tmc.tm_mday = gp_val2(p);
  277. tmc.tm_mon = gp_val2(p+2) - 1;
  278. tmc.tm_year = gp_val2(p+4) + 100;
  279. utc = mktime(&tmc); /* Check time validity */
  280. if (utc == -1)
  281. return 0;
  282. p = gp_col(str, 2); /* Get status */
  283. if (!p || *p != 'A') {
  284. System.location_valid = LOC_INVALID;
  285. FLAGS &= ~F_GPSOK;
  286. return 0; /* Return 0 even is time is valid (comes from module's internal RTC) */
  287. }
  288. FLAGS |= F_GPSOK;
  289. return utc;
  290. }
  291. static void gp_gga_parse(const char *str) {
  292. const char *p;
  293. double tmp;
  294. /* check validity */
  295. p = gp_col(str, 6);
  296. if (*p == '0') {
  297. System.location_valid = LOC_INVALID;
  298. return;
  299. }
  300. System.location_valid = LOC_VALID_NEW;
  301. /* parse location */
  302. p = gp_col(str, 2); /* latitude */
  303. location.lat = gp_val2(p); /* degrees */
  304. p += 2;
  305. xatof(&p, &tmp); /* minutes */
  306. tmp /= 60; /* convert minutes to degrees */
  307. location.lat += tmp;
  308. p = gp_col(str, 3); /* N/S */
  309. if (*p != 'N')
  310. location.lat = -location.lat;
  311. p = gp_col(str, 4); /* longitude */
  312. location.lon = gp_val3(p); /* degrees */
  313. p += 3;
  314. xatof(&p, &tmp); /* minutes */
  315. tmp /= 60; /* convert minutes to degrees */
  316. location.lon += tmp;
  317. p = gp_col(str, 5); /* E/W */
  318. if (*p != 'E')
  319. location.lon = -location.lon;
  320. p = gp_col(str, 7); /* satellites used */
  321. System.satellites_used = atoi(p);
  322. p = gp_col(str, 9); /* MSL altitude */
  323. xatof(&p, &tmp);
  324. location.alt = tmp;
  325. location.time = utc; /* parsed from RMC */
  326. }
  327. static time_t gps_parse(const char *str) { /* Get all required data from NMEA sentences */
  328. if (!gp_comp(str, PSTR("$GPRMC"))) {
  329. return gp_rmc_parse(str);
  330. }
  331. if (!gp_comp(str, PSTR("$GPGGA"))) {
  332. gp_gga_parse(str);
  333. return 0;
  334. }
  335. return 0;
  336. }
  337. #define LOG_SIZE 300
  338. struct {
  339. char buf[LOG_SIZE+1];
  340. unsigned int len;
  341. } logbuf;
  342. void log_put(char c){
  343. UINT bw;
  344. uart1_put(c);
  345. logbuf.buf[logbuf.len++] = c;
  346. if (logbuf.len >= LOG_SIZE && (FLAGS & F_FILEOPEN)) {
  347. if(!f_write(&system_log, logbuf.buf, logbuf.len, &bw))
  348. logbuf.len = 0;
  349. }
  350. if (logbuf.len > LOG_SIZE) {
  351. logbuf.len--;
  352. }
  353. }
  354. static
  355. void ioinit (void)
  356. {
  357. wdt_enable(WDTO_4S);
  358. MCUSR = 0;
  359. POWER_ON_DDR |= POWER_ON;
  360. PORTA |= POWER_ON;
  361. BUZZER_DDR |= BUZZER;
  362. GPS_DIS_DDR |= GPS_DIS;
  363. LEDR_DDR |= LEDR;
  364. OCR1A = F_CPU/8/100-1; /* Timer1: 100Hz interval (OC1A) */
  365. TCCR1B = _BV(WGM12) | _BV(CS11);
  366. TIMSK1 = _BV(OCIE1A); /* Enable TC1.oca interrupt */
  367. /* ADC */
  368. // ADMUX = 0;
  369. ADMUX = 1; // FIXME only testing battery voltage
  370. ADCSRA = _BV(ADEN)|_BV(ADATE)|_BV(ADIE)|_BV(ADPS2)|_BV(ADPS1)|_BV(ADPS0);
  371. /* uart1 (debug) */
  372. uart1_init();
  373. I2C_init();
  374. expander_init(0, 0x00, 0x00); /* all as outputs */
  375. LCD_Initialize();
  376. LCD_Clear();
  377. sei();
  378. ADCSRA |= _BV(ADSC);
  379. /* unused pins */
  380. DDRA |= _BV(PA2) | _BV(PA4) | _BV(PA5);
  381. PRR0 |= _BV(PRTIM2) | _BV(PRTIM0);
  382. ACSR = _BV(ACD); /* Disable analog comp */
  383. }
  384. void close_files(unsigned char flush_logs) {
  385. UINT bw;
  386. if (FLAGS & F_FILEOPEN) {
  387. if (f_close(&gps_log))
  388. System.status = STATUS_FILE_CLOSE_ERROR;
  389. if (gpx_close(&gpx_file))
  390. System.status = STATUS_FILE_CLOSE_ERROR;
  391. if (flush_logs && logbuf.len && !f_write(&system_log, logbuf.buf, logbuf.len, &bw)) {
  392. logbuf.len = 0;
  393. }
  394. if (f_close(&system_log))
  395. System.status = STATUS_FILE_CLOSE_ERROR;
  396. xputs_P(PSTR("File closed\r\n"));
  397. display_state(DISPLAY_STATE_FILE_CLOSED);
  398. }
  399. FLAGS &= ~F_FILEOPEN;
  400. disk_ioctl(0, CTRL_POWER, 0);
  401. }
  402. __flash const char __open_msg[] = "Open %s\r\n";
  403. /*-----------------------------------------------------------------------*/
  404. /* Main */
  405. /*-----------------------------------------------------------------------*/
  406. int main (void)
  407. {
  408. UINT bw, len;
  409. static struct tm ct;
  410. time_t tmp_utc, localtime;
  411. FRESULT res;
  412. unsigned char prev_status;
  413. ioinit();
  414. xdev_out(log_put);
  415. xputs_P(PSTR("STARTUP\r\n"));
  416. display_state(DISPLAY_STATE_STARTUP);
  417. for (;;) {
  418. wdt_reset();
  419. if (FLAGS & (F_POWEROFF | F_LVD)) {
  420. xputs_P(PSTR("POWEROFF\r\n"));
  421. display_state(DISPLAY_STATE_POWEROFF);
  422. if (FLAGS & F_LVD) {
  423. display_state(DISPLAY_STATE_POWEROFF_LOWBAT);
  424. _delay_ms(500);
  425. }
  426. POWEROFF();
  427. while (POWER_SW_PRESSED());
  428. _delay_ms(2000); /* wait for switch off */
  429. FLAGS &= ~F_POWEROFF; /* restart if power is not lost */
  430. POWERON();
  431. xputs_P(PSTR("RESTART\r\n"));
  432. }
  433. display_state(DISPLAY_STATE_START_MESSAGE);
  434. xprintf(PSTR("LOOP err=%u\r\n"), (unsigned int)System.status);
  435. utc = 0;
  436. localtime = 0;
  437. prev_status = System.status;
  438. System.status = STATUS_NO_POWER;
  439. beep(250, prev_status); /* Error beep */
  440. /* Wait for supply voltage stabled */
  441. _delay_ms(500);
  442. if (FLAGS & F_LVD)
  443. continue;
  444. /* report error here ( prev_status) */
  445. if (disk_status(0) & STA_NODISK) {
  446. System.status = STATUS_NO_DISK;
  447. continue;
  448. }
  449. res = f_mount(&Fatfs, "", 1);
  450. if (res != FR_OK) {
  451. xprintf(PSTR("FS error %u\r\n"), res);
  452. System.status = STATUS_DISK_ERROR;
  453. continue;
  454. }
  455. System.status = STATUS_NO_GPS;
  456. xputs(PSTR("FS Ok\r\n"));
  457. display_state(DISPLAY_STATE_CARD_OK);
  458. beep(50, 1); /* 1 beep */
  459. /* Initialize GPS receiver */
  460. GPS_ON(); /* GPS power on */
  461. FLAGS |= F_POW;
  462. _delay_ms(300); /* Delay */
  463. uart0_init(); /* Enable UART */
  464. // xfprintf(uart0_put, PSTR("$PSRF106,21*0F\r\n")); /* Send initialization command (depends on the receiver) */
  465. for (;;) { /* main loop */
  466. wdt_reset();
  467. display_refresh(DISPLAY_STATE_NO_CHANGE);
  468. gettemp();
  469. key_process();
  470. if (!(FLAGS & F_GPSOK))
  471. xputs_P(PSTR("Waiting for GPS\r\n"));
  472. len = get_line(Line, sizeof Line); /* Receive a line from GPS receiver */
  473. if (!len){
  474. if (FLAGS & (F_LVD | F_POWEROFF))
  475. break; /* brownout */
  476. continue;
  477. }
  478. tmp_utc = gps_parse(Line);
  479. if (tmp_utc) {
  480. localtime = tmp_utc + local_time_diff(tmp_utc) * 3600L; /* Local time */
  481. ct = *gmtime(&localtime);
  482. if (timer_expired(system_log)) {
  483. set_timer(system_log, 5000);
  484. xprintf(PSTR("Time: %u.%02u.%04u %u:%02u:%02u\r\n"), ct.tm_mday, ct.tm_mon + 1, ct.tm_year+1900, ct.tm_hour, ct.tm_min, ct.tm_sec);
  485. xprintf(PSTR("Bat volt: %.3f\r\n"), System.bat_volt);
  486. if (System.temperature_ok)
  487. xprintf(PSTR("Temp: %.2f\r\n"), System.temperature);
  488. else
  489. xputs_P(PSTR("Temperature unknown\r\n"));
  490. }
  491. LEDG_ON();
  492. _delay_ms(2);
  493. LEDG_OFF();
  494. }
  495. if (FLAGS & F_FILEOPEN) {
  496. f_write(&gps_log, Line, len, &bw);
  497. if (bw != len) {
  498. System.status = STATUS_FILE_WRITE_ERROR;
  499. break;
  500. }
  501. if (System.location_valid == LOC_VALID_NEW) /* a new point */
  502. gpx_process_point(&location, &gpx_file);
  503. wdt_reset();
  504. if (FLAGS & F_SYNC) {
  505. if (f_sync(&gps_log)) {
  506. System.status = STATUS_FILE_SYNC_ERROR;
  507. break;
  508. }
  509. FLAGS &= ~F_SYNC;
  510. }
  511. }
  512. if (System.location_valid == LOC_VALID_NEW) {
  513. System.location_valid = LOC_VALID;
  514. }
  515. if (localtime && !(FLAGS & F_FILEOPEN)) {
  516. char *time = get_iso_time(utc, 1);
  517. char *ptr = time;
  518. while (*ptr) {
  519. switch (*ptr) {
  520. case ':': *ptr = '-'; break;
  521. case '+': *ptr = 'p'; break;
  522. }
  523. ptr++;
  524. }
  525. xsprintf(Line, PSTR("%s-NMEA.LOG"), time);
  526. xprintf(__open_msg, Line);
  527. if (f_open(&gps_log, Line, FA_WRITE | FA_OPEN_ALWAYS) /* Open log file */
  528. || f_lseek(&gps_log, f_size(&gps_log)) /* Append mode */
  529. || f_write(&gps_log, "\r\n", 2, &bw)) /* Put a blank line as start marker */
  530. {
  531. System.status = STATUS_FILE_OPEN_ERROR;
  532. break; /* Failed to start logging */
  533. }
  534. wdt_reset();
  535. xsprintf(Line, PSTR("%s.GPX"), time);
  536. xprintf(__open_msg, Line);
  537. if (f_open(&gpx_file, Line, FA_WRITE | FA_OPEN_ALWAYS) /* Open log file */
  538. || f_lseek(&gpx_file, f_size(&gpx_file)) /* Append mode */
  539. || gpx_init(&gpx_file)) /* Put a blank line as start marker */
  540. {
  541. f_close(&gpx_file);
  542. System.status = STATUS_FILE_OPEN_ERROR;
  543. break; /* Failed to start logging */
  544. }
  545. wdt_reset();
  546. xsprintf(Line, PSTR("%s-SYSTEM.LOG"), time);
  547. xprintf(__open_msg, Line);
  548. if (f_open(&system_log, Line, FA_WRITE | FA_OPEN_ALWAYS) /* Open log file */
  549. || f_lseek(&system_log, f_size(&system_log)) /* Append mode */
  550. || f_write(&system_log, "\r\n", 2, &bw)) /* Put a blank line as start marker */
  551. {
  552. f_close(&gpx_file);
  553. f_close(&gps_log);
  554. System.status = STATUS_FILE_OPEN_ERROR;
  555. break; /* Failed to start logging */
  556. }
  557. wdt_reset();
  558. FLAGS |= F_FILEOPEN;
  559. System.status = STATUS_OK;
  560. beep(50, 2); /* Two beeps. Start logging. */
  561. display_state(DISPLAY_STATE_FILE_OPEN);
  562. continue;
  563. }
  564. }
  565. /* Stop GPS receiver */
  566. uart0_deinit();
  567. GPS_OFF();
  568. FLAGS &= ~F_POW;
  569. /* Close file */
  570. close_files(1);
  571. if (System.status != STATUS_FILE_CLOSE_ERROR)
  572. beep(500, 1); /* Long beep on file close succeeded */
  573. }
  574. }