main.c 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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 <string.h>
  11. #include "main.h"
  12. #include "ff.h"
  13. #include "diskio.h"
  14. #include "uart0.h"
  15. #include "uart1.h"
  16. #include "xprintf.h"
  17. #include "stime.h"
  18. #include "ds18b20.h"
  19. #include "I2C.h"
  20. #include "expander.h"
  21. #include "HD44780-I2C.h"
  22. #include "gpx.h"
  23. /*FUSES = {0xFF, 0x11, 0xFE};*/ /* ATmega644PA fuses: Low, High, Extended.
  24. This is the fuse settings for this project. The fuse bits will be included
  25. in the output hex file with program code. However some old flash programmers
  26. cannot load the fuse bits from hex file. If it is the case, remove this line
  27. and use these values to program the fuse bits. */
  28. volatile struct system_s System;
  29. FATFS Fatfs; /* File system object for each logical drive */
  30. FIL gps_log; /* File object */
  31. FIL system_log; /* System log file */
  32. char Line[100]; /* Line buffer */
  33. time_t utc; /* current time */
  34. struct location_s location;
  35. /*---------------------------------------------------------*/
  36. /* 100Hz timer interrupt generated by OC1A */
  37. /*---------------------------------------------------------*/
  38. ISR(TIMER1_COMPA_vect)
  39. {
  40. static WORD ivt_sync;
  41. // static BYTE led;
  42. static unsigned int power_sw;
  43. unsigned int *volatile ctimer;
  44. unsigned char i;
  45. for(i=0; i<sizeof(System.timers)/sizeof(unsigned int); i++){ // decrement every variable from timers struct unless it's already zero
  46. ctimer = ((unsigned int *)&System.timers) + i;
  47. if(*ctimer)
  48. (*ctimer)--;
  49. }
  50. /* Sync interval */
  51. if (IVT_SYNC && ++ivt_sync >= IVT_SYNC * 100) {
  52. ivt_sync = 0;
  53. FLAGS |= F_SYNC;
  54. }
  55. /* Green LED drive */
  56. /* if (FLAGS & F_POW) {
  57. if ((FLAGS & F_GPSOK) || (++led & 0x20)) {
  58. LEDG_ON();
  59. } else {
  60. LEDG_OFF();
  61. }
  62. } else {
  63. LEDG_OFF();
  64. }*/
  65. /* MMC/SD timer procedure */
  66. disk_timerproc();
  67. /* Switch off */
  68. if (POWER_SW_PRESSED()) {
  69. if (++power_sw == POWER_SW_TIME){
  70. FLAGS |= F_POWEROFF;
  71. power_sw++;
  72. }
  73. } else {
  74. power_sw = 0;
  75. }
  76. }
  77. /* Power supply monitor */
  78. ISR(ADC_vect)
  79. {
  80. WORD ad;
  81. static BYTE lvt;
  82. ad = ADC * 16;
  83. if (FLAGS & F_LVD) {
  84. if (ad > (WORD)(VI_LVH * VI_MULT) * 16) {
  85. FLAGS &= ~F_LVD;
  86. lvt = 0;
  87. }
  88. } else {
  89. if (ad < (WORD)(VI_LVL * VI_MULT) * 16) {
  90. if (++lvt >= 10)
  91. FLAGS |= F_LVD;
  92. } else {
  93. lvt = 0;
  94. }
  95. }
  96. }
  97. /*---------------------------------------------------------*/
  98. /* User Provided Timer Function for FatFs module */
  99. /*---------------------------------------------------------*/
  100. DWORD get_fattime (void)
  101. {
  102. struct tm *stm;
  103. time_t localtime = utc + LOCALDIFF;
  104. stm = gmtime(&localtime);
  105. return (DWORD)(stm->tm_year - 80) << 25 |
  106. (DWORD)(stm->tm_mon + 1) << 21 |
  107. (DWORD)stm->tm_mday << 16 |
  108. (DWORD)stm->tm_hour << 11 |
  109. (DWORD)stm->tm_min << 5 |
  110. (DWORD)stm->tm_sec >> 1;
  111. }
  112. /*----------------------------------------------------*/
  113. /* Get a line received from GPS module */
  114. /*----------------------------------------------------*/
  115. UINT get_line ( /* 0:Brownout or timeout, >0: Number of bytes received. */
  116. char *buff,
  117. UINT sz_buf
  118. )
  119. {
  120. char c;
  121. UINT i = 0;
  122. set_timer(recv_timeout, 1000);
  123. for (;;) {
  124. if (FLAGS & (F_LVD | F_POWEROFF))
  125. return 0; /* A brownout is detected */
  126. if (timer_expired(recv_timeout))
  127. return 0; /* timeout; continue the main loop */
  128. if (!uart0_test())
  129. continue;
  130. c = (char)uart0_get();
  131. uart1_put(c);
  132. if (i == 0 && c != '$')
  133. continue; /* Find start of line */
  134. buff[i++] = c;
  135. if (c == '\n')
  136. break; /* EOL */
  137. if (i >= sz_buf)
  138. i = 0; /* Buffer overflow (abort this line) */
  139. }
  140. return i;
  141. }
  142. /*--------------------------------------------------------------------------*/
  143. /* Controls */
  144. void beep (UINT len, BYTE cnt)
  145. {
  146. while (cnt--) {
  147. BEEP_ON();
  148. set_timer(beep, len);
  149. while(!timer_expired(beep)) {};
  150. BEEP_OFF();
  151. set_timer(beep, len);
  152. while(!timer_expired(beep)) {};
  153. }
  154. }
  155. /* Make ISO time string */
  156. const char *get_iso_time(time_t time) {
  157. static char output[32];
  158. struct tm *ct = gmtime(&time);
  159. xsprintf(output, PSTR("%4u-%02u-%02uT%02u:%02u:%02u.000Z"), ct->tm_year+1900, ct->tm_mon+1, ct->tm_mday, ct->tm_hour, ct->tm_min, ct->tm_sec);
  160. return output;
  161. }
  162. /* Compare sentence header string */
  163. BYTE gp_comp (const char *str1, __flash const char *str2)
  164. {
  165. char c;
  166. do {
  167. c = pgm_read_byte(str2++);
  168. } while (c && c == *str1++);
  169. return c;
  170. }
  171. #define FIELD_BUF_LEN 32
  172. /* Get a column item */
  173. static
  174. const char* gp_col ( /* Returns pointer to the item (returns a NULL when not found) */
  175. const char* buf, /* Pointer to the sentence */
  176. BYTE col /* Column number (0 is the 1st item) */
  177. ) {
  178. BYTE c;
  179. static char field_buf[FIELD_BUF_LEN];
  180. unsigned char length = 0;
  181. while (col) {
  182. do {
  183. c = *buf++;
  184. if (c <= ' ') return NULL;
  185. } while (c != ',');
  186. col--;
  187. }
  188. while (*buf && *buf != ',' && length < FIELD_BUF_LEN-1) {
  189. field_buf[length++] = *buf++;
  190. }
  191. field_buf[length] = '\0';
  192. return field_buf;
  193. }
  194. static
  195. BYTE gp_val2 (
  196. const char *db
  197. )
  198. {
  199. BYTE n, m;
  200. n = db[0] - '0';
  201. if (n >= 10)
  202. return 0;
  203. m = db[1] - '0';
  204. if (m >= 10)
  205. return 0;
  206. return n * 10 + m;
  207. }
  208. static
  209. UINT gp_val3 (
  210. const char *db
  211. )
  212. {
  213. BYTE n, m, l;
  214. n = db[0] - '0';
  215. if (n >= 10)
  216. return 0;
  217. m = db[1] - '0';
  218. if (m >= 10)
  219. return 0;
  220. l = db[2] - '0';
  221. if (l >= 10)
  222. return 0;
  223. return n * 100 + m * 10 + l;
  224. }
  225. static
  226. time_t gp_rmctime ( /* Get GPS status from RMC sentence */
  227. const char *str
  228. )
  229. {
  230. const char *p;
  231. struct tm tmc;
  232. double tmp;
  233. if (gp_comp(str, PSTR("$GPRMC")))
  234. return 0; /* Not the RMC */
  235. p = gp_col(str, 1); /* Get h:m:s */
  236. if (!p)
  237. return 0;
  238. tmc.tm_hour = gp_val2(p);
  239. tmc.tm_min = gp_val2(p+2);
  240. tmc.tm_sec = gp_val2(p+4);
  241. p = gp_col(str, 9); /* Get y:m:d */
  242. if (!p)
  243. return 0;
  244. tmc.tm_mday = gp_val2(p);
  245. tmc.tm_mon = gp_val2(p+2) - 1;
  246. tmc.tm_year = gp_val2(p+4) + 100;
  247. utc = mktime(&tmc); /* Check time validity */
  248. if (utc == -1)
  249. return 0;
  250. p = gp_col(str, 2); /* Get status */
  251. if (!p || *p != 'A') {
  252. FLAGS &= ~F_GPSOK;
  253. return 0; /* Return 0 even is time is valid (comes from module's internal RTC) */
  254. }
  255. FLAGS |= F_GPSOK;
  256. /* parse location */
  257. p = gp_col(str, 3); /* latitude */
  258. location.lat = gp_val2(p); /* degrees */
  259. p += 2;
  260. xatof(&p, &tmp); /* minutes */
  261. tmp /= 60; /* convert minutes to degrees */
  262. location.lat += tmp;
  263. p = gp_col(str, 4); /* N/S */
  264. if (*p != 'N')
  265. location.lat = -location.lat;
  266. p = gp_col(str, 5); /* longitude */
  267. location.lon = gp_val3(p); /* degrees */
  268. p += 3;
  269. xatof(&p, &tmp); /* minutes */
  270. tmp /= 60; /* convert minutes to degrees */
  271. location.lon += tmp;
  272. p = gp_col(str, 6); /* E/W */
  273. if (*p != 'E')
  274. location.lon = -location.lon;
  275. location.time = utc;
  276. return utc;
  277. }
  278. #define LOG_SIZE 300
  279. struct {
  280. char buf[LOG_SIZE+1];
  281. unsigned int len;
  282. } logbuf;
  283. void log_put(char c){
  284. UINT bw;
  285. uart1_put(c);
  286. logbuf.buf[logbuf.len++] = c;
  287. if (logbuf.len >= LOG_SIZE && (FLAGS & F_FILEOPEN)) {
  288. if(!f_write(&system_log, logbuf.buf, logbuf.len, &bw))
  289. logbuf.len = 0;
  290. }
  291. if (logbuf.len > LOG_SIZE) {
  292. logbuf.len--;
  293. }
  294. }
  295. static
  296. void ioinit (void)
  297. {
  298. POWER_ON_DDR |= POWER_ON;
  299. PORTA |= POWER_ON;
  300. BUZZER_DDR |= BUZZER;
  301. GPS_DIS_DDR |= GPS_DIS;
  302. LEDR_DDR |= LEDR;
  303. OCR1A = F_CPU/8/100-1; /* Timer1: 100Hz interval (OC1A) */
  304. TCCR1B = _BV(WGM12) | _BV(CS11);
  305. TIMSK1 = _BV(OCIE1A); /* Enable TC1.oca interrupt */
  306. ACSR = _BV(ACD); /* Disable analog comp */
  307. /* ADC */
  308. // ADMUX = 0;
  309. ADMUX = 1; // FIXME only testing battery voltage
  310. ADCSRA = _BV(ADEN)|_BV(ADATE)|_BV(ADIE)|_BV(ADPS2)|_BV(ADPS1)|_BV(ADPS0);
  311. /* uart1 (debug) */
  312. uart1_init();
  313. I2C_init();
  314. expander_init(0, 0x00, 0x00); /* all as outputs */
  315. LCD_Initialize();
  316. LCD_Clear();
  317. LCD_WriteTextP(PSTR("TEST"));
  318. sei();
  319. ADCSRA |= _BV(ADSC);
  320. }
  321. __flash const char __open_msg[] = "Open %s\r\n";
  322. /*-----------------------------------------------------------------------*/
  323. /* Main */
  324. /*-----------------------------------------------------------------------*/
  325. int main (void)
  326. {
  327. UINT bw, len;
  328. struct tm *ct;
  329. time_t tmp_utc, localtime;
  330. FRESULT res;
  331. unsigned char prev_status;
  332. ioinit();
  333. xdev_out(log_put);
  334. xputs_P(PSTR("STARTUP\r\n"));
  335. for (;;) {
  336. if (FLAGS & F_POWEROFF) {
  337. xputs_P(PSTR("POWEROFF\r\n"));
  338. POWEROFF();
  339. while (POWER_SW_PRESSED());
  340. _delay_ms(2000); /* wait for switch off */
  341. FLAGS &= ~F_POWEROFF; /* restart if power is not lost */
  342. POWERON();
  343. xputs_P(PSTR("RESTART\r\n"));
  344. }
  345. xprintf(PSTR("LOOP err=%u\r\n"), (unsigned int)System.status);
  346. utc = 0;
  347. localtime = 0;
  348. prev_status = System.status;
  349. System.status = STATUS_NO_POWER;
  350. beep(250, prev_status); /* Error beep */
  351. /* Wait for supply voltage stabled */
  352. while (FLAGS & F_LVD) {};
  353. _delay_ms(500);
  354. if (FLAGS & F_LVD)
  355. continue;
  356. /* report error here ( prev_status) */
  357. if (disk_status(0) & STA_NODISK) {
  358. System.status = STATUS_NO_DISK;
  359. continue;
  360. }
  361. res = f_mount(&Fatfs, "", 1);
  362. if (res != FR_OK) {
  363. xprintf(PSTR("FS error %u\r\n"), res);
  364. System.status = STATUS_DISK_ERROR;
  365. continue;
  366. }
  367. System.status = STATUS_NO_GPS;
  368. xputs(PSTR("FS Ok\r\n"));
  369. beep(50, 1); /* 1 beep */
  370. /* Initialize GPS receiver */
  371. GPS_ON(); /* GPS power on */
  372. FLAGS |= F_POW;
  373. _delay_ms(300); /* Delay */
  374. uart0_init(); /* Enable UART */
  375. // xfprintf(uart0_put, PSTR("$PSRF106,21*0F\r\n")); /* Send initialization command (depends on the receiver) */
  376. for (;;) { /* main loop */
  377. gettemp();
  378. if (!(FLAGS & F_GPSOK))
  379. xputs_P(PSTR("Waiting for GPS\r\n"));
  380. len = get_line(Line, sizeof Line); /* Receive a line from GPS receiver */
  381. if (!len){
  382. if (FLAGS & (F_LVD | F_POWEROFF))
  383. break; /* brownout */
  384. continue;
  385. }
  386. tmp_utc = gp_rmctime(Line);
  387. if (tmp_utc) {
  388. localtime = tmp_utc + LOCALDIFF * 3600L; /* Local time */
  389. LEDG_ON();
  390. _delay_ms(2);
  391. LEDG_OFF();
  392. }
  393. if (localtime && !(FLAGS & F_FILEOPEN)) {
  394. ct = gmtime(&localtime);
  395. xsprintf(Line, PSTR("%04u-%02u-%02u_%02u-%02u.LOG"), ct->tm_year+1900, ct->tm_mon + 1, ct->tm_mday, ct->tm_hour, ct->tm_min);
  396. xprintf(__open_msg, Line);
  397. if (f_open(&gps_log, Line, FA_WRITE | FA_OPEN_ALWAYS) /* Open log file */
  398. || f_lseek(&gps_log, f_size(&gps_log)) /* Append mode */
  399. || f_write(&gps_log, "\r\n", 2, &bw)) /* Put a blank line as start marker */
  400. {
  401. System.status = STATUS_FILE_OPEN_ERROR;
  402. break; /* Failed to start logging */
  403. }
  404. xsprintf(Line, PSTR("%04u-%02u-%02u_%02u-%02u-%02u.GPX"), ct->tm_year+1900, ct->tm_mon + 1, ct->tm_mday, ct->tm_hour, ct->tm_min, ct->tm_sec);
  405. xprintf(__open_msg, Line);
  406. if (f_open(&gpx_file, Line, FA_WRITE | FA_OPEN_ALWAYS) /* Open log file */
  407. || f_lseek(&gpx_file, f_size(&gpx_file)) /* Append mode */
  408. || gpx_init(&gpx_file)) /* Put a blank line as start marker */
  409. {
  410. f_close(&gpx_file);
  411. System.status = STATUS_FILE_OPEN_ERROR;
  412. break; /* Failed to start logging */
  413. }
  414. xsprintf(Line, PSTR("%04u-%02u-%02u_%02u-%02u-SYSTEM.LOG"), ct->tm_year+1900, ct->tm_mon + 1, ct->tm_mday, ct->tm_hour, ct->tm_min);
  415. xprintf(__open_msg, Line);
  416. if (f_open(&system_log, Line, FA_WRITE | FA_OPEN_ALWAYS) /* Open log file */
  417. || f_lseek(&system_log, f_size(&system_log)) /* Append mode */
  418. || f_write(&system_log, "\r\n", 2, &bw)) /* Put a blank line as start marker */
  419. {
  420. f_close(&gpx_file);
  421. f_close(&gps_log);
  422. System.status = STATUS_FILE_OPEN_ERROR;
  423. break; /* Failed to start logging */
  424. }
  425. FLAGS |= F_FILEOPEN;
  426. System.status = STATUS_OK;
  427. beep(50, 2); /* Two beeps. Start logging. */
  428. continue;
  429. }
  430. if (FLAGS & F_FILEOPEN) {
  431. f_write(&gps_log, Line, len, &bw);
  432. if (bw != len) {
  433. System.status = STATUS_FILE_WRITE_ERROR;
  434. break;
  435. }
  436. if(tmp_utc) /* a new point */
  437. gpx_process_point(&location, &gpx_file);
  438. if (FLAGS & F_SYNC) {
  439. if (f_sync(&gps_log)) {
  440. System.status = STATUS_FILE_SYNC_ERROR;
  441. break;
  442. }
  443. FLAGS &= ~F_SYNC;
  444. }
  445. }
  446. }
  447. /* Stop GPS receiver */
  448. uart0_deinit();
  449. GPS_OFF();
  450. FLAGS &= ~F_POW;
  451. /* Close file */
  452. if (FLAGS & F_FILEOPEN) {
  453. if (f_close(&gps_log))
  454. System.status = STATUS_FILE_CLOSE_ERROR;
  455. if (gpx_close(&gpx_file))
  456. System.status = STATUS_FILE_CLOSE_ERROR;
  457. if (logbuf.len && !f_write(&system_log, logbuf.buf, logbuf.len, &bw)) {
  458. logbuf.len = 0;
  459. }
  460. if (f_close(&system_log))
  461. System.status = STATUS_FILE_CLOSE_ERROR;
  462. xputs_P(PSTR("File closed\r\n"));
  463. }
  464. FLAGS &= ~F_FILEOPEN;
  465. disk_ioctl(0, CTRL_POWER, 0);
  466. if (System.status != STATUS_FILE_CLOSE_ERROR)
  467. beep(500, 1); /* Long beep on file close succeeded */
  468. }
  469. }