main.c 15 KB

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