cryarchy

A9G Stalling Code

Jan 9th, 2019
701
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 20.98 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4.  
  5. #include <time.h>
  6. #include <api_os.h>
  7. #include <api_fs.h>
  8. #include <api_event.h>
  9. #include <api_socket.h>
  10. #include <api_network.h>
  11. #include <api_debug.h>
  12. #include <api_hal_uart.h>
  13. #include <api_gps.h>
  14. #include <api_info.h>
  15. #include <api_hal_gpio.h>
  16. #include <api_hal_pm.h>
  17.  
  18. #include "buffer.h"
  19. #include "gps_parse.h"
  20. #include "math.h"
  21. #include "gps.h"
  22.  
  23. #define LOG_FILE_NAME "/t/log.csv"
  24. #define VIOLATIONS_FILE_NAME "/t/vlts.csv"
  25. #define TMP_FILE_NAME "/t/tmp.csv"
  26.  
  27.  #define SERVER_ADDRESS "80.211.88.87"
  28.  #define SERVER_PORT 4000
  29.  
  30. #define RECEIVE_BUFFER_MAX_LENGTH (1 * 1024)
  31. #define FS_BUFFER_MAX_LENGTH 400
  32.  
  33. #define MAIN_TASK_STACK_SIZE (1024 * 2)
  34. #define MAIN_TASK_PRIORITY 0
  35. #define MAIN_TASK_NAME "Main Task"
  36.  
  37. #define UPDATE_TASK_STACK_SIZE (1024 * 2)
  38. #define UPDATE_TASK_PRIORITY 0
  39. #define UPDATE_TASK_NAME "Update Task"
  40.  
  41. #define GPS_TASK_STACK_SIZE (1024 * 4)
  42. #define GPS_TASK_PRIORITY 1
  43. #define GPS_TASK_NAME "Gps Task"
  44.  
  45. #define HTTP_TASK_STACK_SIZE (1024 * 8)
  46. #define HTTP_TASK_PRIORITY 2
  47. #define HTTP_TASK_NAME "Http Task"
  48.  
  49. #define MAX_SPEED 80
  50.  
  51. #define NUMBER_PLATE "KBG 223G"
  52. #define VENDOR "SAFARIWATCH"
  53.  
  54. static HANDLE mainTaskHandle = NULL;
  55. bool networkActiveFlag = false;
  56. static uint8_t preSmsEventsCount = 0;
  57. bool httpFailed = false;
  58.  
  59. char httpBuffer[RECEIVE_BUFFER_MAX_LENGTH], fsBuffer[FS_BUFFER_MAX_LENGTH], imei[16];
  60. int serverSocket = -1;
  61. HANDLE connectionSem = NULL;
  62. HANDLE transmissionSem = NULL;
  63. HANDLE gpsSem = NULL;
  64. int errorCode = 0;
  65. GPIO_LEVEL contactPinState = GPIO_LEVEL_HIGH;
  66. double latVal = 0, lngVal = 0;
  67. int Y, M, D, hr, mn, sc;
  68. int frequency = 0;
  69. float speed;
  70. int printData = 0;
  71.  
  72. GPIO_config_t relayPin, buzzerPin;
  73.  
  74. const char* FILE_HEADER = "Date,Time,IMEI,Vendor,Number Plate,Speed,Latitude,Longitude,Power Disconnect,Speed Disconnect\r\n";
  75. const char* REQUEST = "%d/%d/%d,%d:%d:%d,%s,%s,%s,%.2f,%f%c,%f%c,%d,%d";
  76. const int MAX_LINE_LENGTH = 200;
  77.  
  78. void update_time_variables(void) {
  79.     RTC_Time_t time;
  80.     TIME_GetRtcTIme(&time);
  81.     Y = time.year;
  82.     M = time.month;
  83.     D = time.day;
  84.     hr = time.hour >= 24 ? time.hour - 24 : time.hour;
  85.     mn = time.minute;
  86.     sc = time.second;
  87.     if (time.timeZone > 0)
  88.         hr += time.timeZone;
  89. }
  90.  
  91. void update_imei(void) {
  92.     memset(imei, '\0', sizeof(imei));
  93.     INFO_GetIMEI(imei);
  94. }
  95.  
  96. bool init_file(const char* filePath) {
  97.     Trace(1,"init file");
  98.     int32_t logFptr, result;
  99.     logFptr = API_FS_Open(filePath, FS_O_WRONLY|FS_O_CREAT|FS_O_EXCL, 0);
  100.     if (logFptr == -1) {
  101.         Trace(1, "%s file found!", filePath);
  102.         return true;
  103.     } else if (logFptr < 0) {
  104.         Trace(1,"open file %s error:%d", filePath, logFptr);
  105.         return false;
  106.     } else {
  107.         // write header
  108.         result = API_FS_Write(logFptr, (uint8_t *)FILE_HEADER, strlen(FILE_HEADER));
  109.         if (result < 0) {
  110.             Trace(1,"write file %s error:%d", filePath,result);
  111.         }
  112.         API_FS_Close(logFptr);
  113.         return true;
  114.     }
  115.     return true;
  116. }
  117.  
  118. void save_data(const char* filePath) {
  119.     if (init_file(filePath) == true) {
  120.         Trace(1, "Open file: %s", filePath);
  121.         int logFptr = API_FS_Open(filePath, FS_O_WRONLY|FS_O_CREAT|FS_O_APPEND, 0);
  122.         if (logFptr < 0) {
  123.             Trace(1,"open file %s error:%d", filePath, logFptr);
  124.             return;
  125.         }
  126.         Trace(1, "Clear fs buffer");
  127.         memset(fsBuffer, '\0', sizeof(fsBuffer));
  128.         char latHem = latVal < 0 ? 'W' : 'E';
  129.         char lngHem = lngVal < 0 ? 'S' : 'N';
  130.         Trace(1, "sprintf");
  131.         sprintf(
  132.             // "Date,Time,IMEI,Vendor,Number Plate,Speed,Latitude,Longitude,Power Disconnect,Speed Disconnect\r\n";
  133.             fsBuffer, "%d/%d/%d,%d:%d:%d,%s,%s,%s,%.2f,%f%c,%f%c,%d,%d\r\n",
  134.             Y, M, D,
  135.             hr, mn, sc,
  136.             imei, VENDOR, NUMBER_PLATE,
  137.             speed,
  138.             latVal, latHem, lngVal, lngHem,
  139.             0, 0
  140.         );
  141.         Trace(1, "write");
  142.         int result = API_FS_Write(logFptr, fsBuffer, strlen(fsBuffer));
  143.         if (result < 0) {
  144.             Trace(1,"write file %s error:%d", filePath, result);
  145.         } else {
  146.             Trace(1, "Save %s data: Successful!", filePath);
  147.         }
  148.         Trace(1, "close");
  149.         API_FS_Close(logFptr);
  150.     };
  151. }
  152.  
  153. int32_t time_to_seconds(int h, int m, int s) {
  154.     return (h * 3600) + (m * 60) + s;
  155. }
  156.  
  157. void print_data(void) {
  158.     Trace(1, "Print data.");
  159.     Trace(1, "Open vioations file.");
  160.     int vltsFptr = API_FS_Open(VIOLATIONS_FILE_NAME, FS_O_RDONLY, 0);
  161.     if (vltsFptr < 0) {
  162.         Trace(1, "open file %s error:%d", VIOLATIONS_FILE_NAME, vltsFptr);
  163.         return;
  164.     }
  165.     Trace(1, "Open tmp file.");
  166.     int tmpFptr = API_FS_Open(TMP_FILE_NAME, FS_O_WRONLY|FS_O_CREAT|FS_O_APPEND, 0);
  167.     if (tmpFptr < 0) {
  168.         Trace(1, "open file %s error:%d", TMP_FILE_NAME, tmpFptr);
  169.         return;
  170.     }
  171.     char lineBuffer[MAX_LINE_LENGTH], *sepBuffer = NULL;
  172.     memset(fsBuffer, '\0', sizeof(fsBuffer));
  173.     int result, i = 0, nextLineStart = 0;
  174.     char *token = NULL, *tailPtr = NULL, *newlinePtr = NULL;
  175.     long int dateTime[6];
  176.     long int currentTime = time_to_seconds(hr, mn, sc), logTime;
  177.     Trace(1, "Enter while.");
  178.     while (1) {
  179.         Trace(1, "Read vioations file.");
  180.         result = API_FS_Read(vltsFptr, fsBuffer, FS_BUFFER_MAX_LENGTH);
  181.         Trace(1, "Clear previous memory if any.");
  182.         Trace(1, "Allocate memory for sep buffer");
  183.         sepBuffer = malloc((strlen(fsBuffer) + 1) * sizeof(char));
  184.         Trace(1, "Copy fs buffer to sep buffer");
  185.         strcpy(sepBuffer, fsBuffer);
  186.         if (result < 0) {
  187.             Trace(1, "read file %s error:%d", VIOLATIONS_FILE_NAME, result);
  188.             break;
  189.         } else if (result == 0) {
  190.             Trace(1, "Nothing more to read!");
  191.             break;
  192.         }
  193.         Trace(1, "Search last line.");
  194.         // find the location of the first newline character
  195.         newlinePtr = strrchr(fsBuffer, '\n');
  196.         // if the newline character is at position 1, read from next position
  197.         if (newlinePtr == fsBuffer) {
  198.             newlinePtr += 1;
  199.             break;
  200.         }
  201.         Trace(1, "%d - %d = %d", newlinePtr, fsBuffer, (newlinePtr - fsBuffer));
  202.         Trace(1, "Added: %d", (newlinePtr - fsBuffer));
  203.         // get the start location of the next line
  204.         nextLineStart += (newlinePtr - fsBuffer) / sizeof(char);
  205.         Trace(1, "Next line start: %d", nextLineStart);
  206.         // rewind the file pointer
  207.         Trace(1, "Seeking.");
  208.         result = API_FS_Seek(vltsFptr, nextLineStart, FS_SEEK_SET);
  209.         if (result != 0) {
  210.             Trace(1, "Seek file: %s Result: %d", VIOLATIONS_FILE_NAME, result);
  211.         }
  212.         // seek to file end if seek result is not equal to expected value
  213.         if (result != nextLineStart) {
  214.             result = API_FS_Seek(vltsFptr, 0, FS_SEEK_END);
  215.             Trace(1, "Seek file: %s Result: %d", VIOLATIONS_FILE_NAME, result);
  216.         }
  217.         result = 0;
  218.         Trace(1, "Begin parse lines");
  219.         // parse the read lines
  220.         do {
  221.             // obtain the first 6 tokens which represent the log's date and time
  222.             for (i = 0; i < 6; i++) {
  223.                 // separate using time and date and csv delimiters
  224.                 token = strsep(&sepBuffer, "/:,");
  225.                 // check for separation failure
  226.                 if (token == NULL) {
  227.                     Trace(1, "parsing failed! null token.");
  228.                     result = -1;
  229.                     break;
  230.                 }
  231.                 // parse tokens to integers
  232.                 dateTime[i] = strtol(token, &tailPtr, 10);
  233.                 // check for parsing failures
  234.                 if (*tailPtr != '\0') {
  235.                     Trace(1, "parsing failed! expected null byte but got %c", *tailPtr);
  236.                     result = -1;
  237.                     break;
  238.                 }
  239.             }
  240.             // break if a parsing error occured
  241.             if (result == -1) break;
  242.             Trace(1, "%ld/%ld/%ld,%ld:%ld:%ld", dateTime[0], dateTime[1], dateTime[2], dateTime[3], dateTime[4], dateTime[5]);
  243.             // obtain the rest of the line
  244.             token = strsep(&sepBuffer, "\n");
  245.             // break if '\n' character is not found
  246.             if (token == NULL) {
  247.                 Trace(1, "eol not found! continuing.");
  248.                 break;
  249.             }
  250.             // get the log time in seconds
  251.             logTime = time_to_seconds(dateTime[3], dateTime[4], dateTime[5]);
  252.             // if log time is within the past hour or between 00:00 and 01:00
  253.             if (((currentTime - logTime) < 3600) || (logTime < 3600)) {
  254.                 // discard entries of a different day
  255.                 if (dateTime[2] != D) continue;
  256.                 // construct the new line
  257.                 sprintf(
  258.                     lineBuffer, "ENTRY: %d/%d/%d,%d:%d:%d,%s\n",
  259.                     dateTime[0], dateTime[1], dateTime[2], dateTime[3], dateTime[4], dateTime[5],
  260.                     token
  261.                 );
  262.                 // print the line
  263.                 UART_Write(UART1, lineBuffer, strlen(lineBuffer));
  264.                 // write the file to the file tmp.csv
  265.                 result = API_FS_Write(tmpFptr, lineBuffer, strlen(lineBuffer));
  266.                 if (result < 0) {
  267.                     Trace(1, "write file %s error:%d", TMP_FILE_NAME, result);
  268.                 } else {
  269.                     Trace(1, "Save %s data: Successful!", TMP_FILE_NAME);
  270.                 }
  271.             }
  272.         } while (token != NULL);
  273.         OS_Sleep(10);
  274.     }
  275.     // close files
  276.     API_FS_Close(tmpFptr);
  277.     API_FS_Close(vltsFptr);
  278.     // remove file: vlts.csv
  279.     result = API_FS_Delete(VIOLATIONS_FILE_NAME);
  280.     if (result != 0) {
  281.         Trace(1, "delete file %s error:%d", VIOLATIONS_FILE_NAME, result);
  282.     }
  283.     // rename file: tmp.csv to: vlts.csv
  284.     result = API_FS_Rename(TMP_FILE_NAME, VIOLATIONS_FILE_NAME);
  285.     if (result != 0) {
  286.         Trace(1, "rename file %s error:%d", TMP_FILE_NAME, result);
  287.     }
  288. }
  289.  
  290. void EventDispatch(API_Event_t* pEvent) {
  291.   switch(pEvent->id) {
  292.     case API_EVENT_ID_NO_SIMCARD:
  293.         Trace(10,"!!NO SIM CARD%d!!!!",pEvent->param1);
  294.         break;
  295.  
  296.     case API_EVENT_ID_SYSTEM_READY:
  297.         Trace(1,"system initialize complete");
  298.         preSmsEventsCount |= 1;
  299.         break;
  300.  
  301.     case API_EVENT_ID_NETWORK_REGISTERED_HOME:
  302.     case API_EVENT_ID_NETWORK_REGISTERED_ROAMING:
  303.         Trace(2,"network register success");
  304.         preSmsEventsCount |= 2;
  305.         Network_StartAttach();
  306.         break;
  307.  
  308.     case API_EVENT_ID_NETWORK_ATTACHED:
  309.         Trace(2,"network attach success");
  310.         Network_PDP_Context_t context = {
  311.             .apn        ="internet",
  312.             .userName   = "",
  313.             .userPasswd = ""
  314.         };
  315.         Network_StartActive(context);
  316.         break;
  317.  
  318.     case API_EVENT_ID_GPS_UART_RECEIVED:
  319.         GPS_Update(pEvent->pParam1,pEvent->param1);
  320.         break;
  321.  
  322.     case API_EVENT_ID_NETWORK_ACTIVATED:
  323.         Trace(2,"network activate success");
  324.         connectionSem = 1;
  325.         networkActiveFlag = true;
  326.         break;
  327.  
  328.     case API_EVENT_ID_SOCKET_CONNECTED:
  329.         Trace(2,"event connect");
  330.         connectionSem = 1;
  331.         break;
  332.  
  333.     case API_EVENT_ID_SOCKET_SENT:
  334.         connectionSem = 1;
  335.         break;
  336.  
  337.     case API_EVENT_ID_SOCKET_RECEIVED:
  338.         {
  339.             Trace(1, "Socket received!");
  340.             // int fd = pEvent->param1;
  341.             // int length = pEvent->param2 > RECEIVE_BUFFER_MAX_LENGTH
  342.             //  ? RECEIVE_BUFFER_MAX_LENGTH
  343.             //  : pEvent->param2;
  344.             // memset(httpBuffer, '\0', sizeof(httpBuffer));
  345.             // length = Socket_TcpipRead(fd, httpBuffer, length);
  346.             // Trace(2,"socket %d received %d bytes", fd, length);
  347.             // UART_Write(UART1, "\r\n\r\n", strlen("\r\n\r\n"));
  348.             // UART_Write(UART1, httpBuffer, strlen(httpBuffer));
  349.             // transmissionSem = 0;
  350.             break;
  351.         }
  352.  
  353.     case API_EVENT_ID_SOCKET_CLOSED:
  354.         {
  355.             int fd = pEvent->param1;
  356.             Trace(2,"socket %d closed", fd);
  357.             // serverSocket = -1;
  358.             connectionSem = 1;
  359.             break;
  360.         }
  361.  
  362.     case API_EVENT_ID_SOCKET_ERROR:
  363.         {
  364.             int fd = pEvent->param1;
  365.             Trace(2,"socket %d error occurred,cause:%d",fd,pEvent->param2);
  366.             errorCode = pEvent->param2;
  367.             connectionSem = 1;
  368.             break;
  369.         }
  370.  
  371.     default:
  372.         break;
  373.   }
  374. }
  375.  
  376. void CreateSem(HANDLE* sem_) {
  377.     *sem_ = 0;
  378. }
  379.  
  380. void WaitSem(HANDLE* sem_) {
  381.     while(*sem_ == 0)
  382.         OS_Sleep(1);
  383.     *sem_ = 0;
  384. }
  385.  
  386. bool Connect() {
  387.     // reset httpBuffer
  388.     memset(httpBuffer, 0, sizeof(httpBuffer));
  389.     // resolve server IP address
  390.     if(DNS_GetHostByName2(SERVER_ADDRESS, (char*)httpBuffer) != 0)
  391.         return false;
  392.     // print server domain name and ip address
  393.     Trace(2, "DNS,domain: %s, ip: %s, strlen(ip): %d", SERVER_ADDRESS, httpBuffer,
  394.         strlen(httpBuffer));
  395.     // create a blocked semaphore
  396.     CreateSem(&connectionSem);
  397.     // connect to the server
  398.     serverSocket = Socket_TcpipConnect(UDP, httpBuffer, SERVER_PORT);
  399.     Trace(2, "connect tcp server, socketFd: %d", serverSocket);
  400.     // wait for the connection to complete or fail
  401.     // WaitSem(&connectionSem);
  402.     // print the end of the connection
  403.     Trace(2, "connect end");
  404.     // handle connection fail
  405.     if(errorCode != 0) {
  406.         // reset error code
  407.         errorCode = 0;
  408.         // print error message
  409.         Trace(2, "error ocurred");
  410.         // terminate function
  411.         return false;
  412.     }
  413.     // terminate function
  414.     return true;
  415. }
  416.  
  417. bool Write(uint8_t* data, uint16_t len) {
  418.     // print to signal function start
  419.     Trace(2, "Write");
  420.     // create a blocked semaphore
  421.     CreateSem(&connectionSem);
  422.     // write data to the server socket
  423.     int ret = Socket_TcpipWrite(serverSocket, data, len);
  424.     // handle write fail
  425.     if(ret <= 0) {
  426.         // print to signal write fail
  427.         Trace(2, "socket write fail: %d", ret);
  428.         // terminate function
  429.         return false;
  430.     }
  431.     // print to signal write success
  432.     Trace(2,"### socket %d send %d bytes data to server: %s, ret: %d",
  433.         serverSocket, len, data, ret);
  434.     // wait for response data from the server
  435.     // WaitSem(&connectionSem);
  436.     // print to signal write end
  437.     Trace(2,"### write end");
  438.     // handle write fail
  439.     if(errorCode != 0) {
  440.         // reset error code
  441.         errorCode = 0;
  442.         // print to signal write fail
  443.         Trace(2,"error ocurred");
  444.         // terminate function
  445.         return false;
  446.     }
  447.     // terminate function
  448.     return true;
  449. }
  450.  
  451. bool Close() {
  452.     // create blocked semaphore
  453.     CreateSem(&connectionSem);
  454.     // close the socket
  455.     Socket_TcpipClose(serverSocket);
  456.     // wait for the socket to be closed
  457.     WaitSem(&connectionSem);
  458.     // reset the value of serverSocket to -1
  459.     serverSocket = -1;
  460.     // terminate function
  461.     return true;
  462. }
  463.  
  464. void httpTask(void* param) {
  465.     // -------------- LED & BTN CONFIG -----------------
  466.     GPIO_config_t gpioLedBlue = {
  467.         .mode         = GPIO_MODE_OUTPUT,
  468.         .pin          = GPIO_PIN28,
  469.         .defaultLevel = GPIO_LEVEL_LOW
  470.     };
  471.  
  472.     PM_PowerEnable(POWER_TYPE_VPAD ,true);
  473.  
  474.     GPIO_Init(gpioLedBlue);
  475.     // -------------- END CONFIG -----------------
  476.    
  477.     bool writeSuccess = false;
  478.     // wait for network to be active
  479.     WaitSem(&connectionSem);
  480.     // print semaphore status
  481.     Trace(2, "sem: %d, %p", (int)connectionSem, (void*)connectionSem);
  482.     // infinite loop
  483.     while(1) {
  484.         Trace(1, "Waiting for transmission sem.");
  485.         // wait for previous transmission to complete
  486.         WaitSem(&transmissionSem);
  487.         // turn on the LED
  488.         GPIO_SetLevel(gpioLedBlue, GPIO_LEVEL_HIGH);
  489.         // signal http task running
  490.         Trace(1, "Http task running ...");
  491.         // print to signal connect start
  492.         Trace(1, "start connect now");
  493.         // connect to server if a connection does not already exist
  494.         if (serverSocket == -1) {
  495.             // send coordinates via SMS if connection fails
  496.             if (!Connect()) {
  497.                 // signal transmission over http fail
  498.                 httpFailed = true;
  499.                 continue;
  500.             }
  501.         }
  502.         // create the request string
  503.         char latHem = latVal < 0 ? 'W' : 'E';
  504.         char lngHem = lngVal < 0 ? 'S' : 'N';
  505.         memset(httpBuffer, '\0', sizeof(httpBuffer));
  506.         sprintf(
  507.             httpBuffer, REQUEST,
  508.             Y, M, D,
  509.             hr, mn, sc,
  510.             imei, VENDOR, NUMBER_PLATE,
  511.             speed,
  512.             latVal, latHem, lngVal, lngHem,
  513.             0, 0
  514.         );
  515.         // write data to the server
  516.         writeSuccess = Write(httpBuffer, strlen(httpBuffer));
  517.         // if write attempt fails
  518.         if(!writeSuccess) {
  519.             // signal transmission over http fail
  520.             httpFailed = true;
  521.             // close server socket
  522.             Close();
  523.         }
  524.         // turn off the LED
  525.         GPIO_SetLevel(gpioLedBlue, GPIO_LEVEL_LOW);
  526.     }
  527. }
  528.  
  529. void gpsTask(void *pData) {
  530.     GPS_Info_t* gpsInfo = Gps_GetInfo();
  531.     // Wait for SMS and gprs connections to be active
  532.     while(!networkActiveFlag) {
  533.         Trace(1,"Waiting for GPRS connection to be active");
  534.         OS_Sleep(2000);
  535.     }
  536.     //open GPS hardware(UART2 open either)
  537.     GPS_Init();
  538.     GPS_Open(NULL);
  539.     //wait for gps start up, or gps will not response command
  540.     while(gpsInfo->rmc.latitude.value == 0)
  541.         OS_Sleep(1000);
  542.     // signal GPS initialization okay
  543.     Trace(1," GPS init ok");
  544.     // infinite loop
  545.     while(1) {
  546.         //show fix info
  547.         uint8_t isFixed = gpsInfo->gsa[0].fix_type > gpsInfo->gsa[1].fix_type
  548.             ? gpsInfo->gsa[0].fix_type
  549.             : gpsInfo->gsa[1].fix_type;
  550.         char* isFixedStr;
  551.         if(isFixed == 2)
  552.             isFixedStr = "2D fix";
  553.         else if(isFixed == 3)
  554.         {
  555.             if(gpsInfo->gga.fix_quality == 1)
  556.                 isFixedStr = "3D fix";
  557.             else if(gpsInfo->gga.fix_quality == 2)
  558.                 isFixedStr = "3D/DGPS fix";
  559.         }
  560.         else
  561.             isFixedStr = "no fix";
  562.         //convert unit ddmm.mmmm to degree(°)
  563.         // obtain the current latitude and update the global latitude variable
  564.         int temp = (int)(gpsInfo->rmc.latitude.value/gpsInfo->rmc.latitude.scale/100);
  565.         latVal = temp+(double)(gpsInfo->rmc.latitude.value - temp*gpsInfo->rmc.latitude.scale*100)/gpsInfo->rmc.latitude.scale/60.0;
  566.         // obtain the current longitude and update the global longitude variable
  567.         temp = (int)(gpsInfo->rmc.longitude.value/gpsInfo->rmc.longitude.scale/100);
  568.         lngVal = temp+(double)(gpsInfo->rmc.longitude.value - temp*gpsInfo->rmc.longitude.scale*100)/gpsInfo->rmc.longitude.scale/60.0;
  569.         gpsSem = 1;
  570.         OS_Sleep(1000);
  571.     }
  572. }
  573.  
  574. void updateTask(void* param) {
  575.     while(1) {
  576.         // wait for the gps
  577.         WaitSem(&gpsSem);
  578.         // print data if the print button has been pressed
  579.         if (printData == 1) {
  580.             print_data();
  581.             printData = 0;
  582.         }
  583.         // update the time variables
  584.         update_time_variables();
  585.         // update imei
  586.         update_imei();
  587.         // save the data
  588.         save_data(LOG_FILE_NAME);
  589.         // log entry if it is a vioation
  590.         if (speed > MAX_SPEED) {
  591.             save_data(VIOLATIONS_FILE_NAME);
  592.         }
  593.         // signal transmit data to server
  594.         transmissionSem = 1;
  595.         OS_Sleep(5000);
  596.     }
  597. }
  598.  
  599. void OnPinFalling(GPIO_INT_callback_param_t* param) {
  600.     // Trace(1,"OnPinFalling");
  601.     switch(param->pin)
  602.     {
  603.         case GPIO_PIN3:
  604.             frequency++;
  605.             break;
  606.          case GPIO_PIN2:
  607.             printData = 1;
  608.             break;
  609.         default:
  610.             break;
  611.     }
  612. }
  613.  
  614. void sampleSpeed(void* param) {
  615.     speed = frequency * 1.365;
  616.     Trace(1, "Speed: %f", speed);
  617.     // alert if max speed has been exceeded
  618.     if (speed > MAX_SPEED) {
  619.         GPIO_SetLevel(buzzerPin, GPIO_LEVEL_HIGH);
  620.         GPIO_SetLevel(relayPin, GPIO_LEVEL_HIGH);
  621.     } else {
  622.         GPIO_SetLevel(buzzerPin, GPIO_LEVEL_LOW);
  623.         GPIO_SetLevel(relayPin, GPIO_LEVEL_LOW);
  624.     }
  625.     // reset frequency
  626.     frequency = 0;
  627.     // reschedule the speed sampler for per second
  628.     OS_StartCallbackTimer(mainTaskHandle, 1000, sampleSpeed, NULL);
  629. }
  630.  
  631. void mainTask(void *pData) {
  632.     // set up network time synchronization
  633.     TIME_SetIsAutoUpdateRtcTime(true);
  634.     // create event object
  635.     API_Event_t* event=NULL;
  636.     // configure UART
  637.     UART_Config_t config = {
  638.         .baudRate = UART_BAUD_RATE_9600,
  639.         .dataBits = UART_DATA_BITS_8,
  640.         .stopBits = UART_STOP_BITS_1,
  641.         .parity   = UART_PARITY_NONE,
  642.         .rxCallback = NULL,
  643.         .useEvent   = false
  644.     };
  645.     // initialize UART
  646.     UART_Init(UART1, config);
  647.     // test uart
  648.     UART_Write(UART1, "Hello, world!\r\n", strlen("Hello, world!\r\n"));
  649.     // enable power for used pins
  650.     PM_PowerEnable(POWER_TYPE_VPAD, true);
  651.     PM_PowerEnable(POWER_TYPE_LCD, true);
  652.     // configure speed pin
  653.     GPIO_config_t intPin = {
  654.         .mode               = GPIO_MODE_INPUT_INT,
  655.         .pin                = GPIO_PIN3,
  656.         .defaultLevel       = GPIO_LEVEL_LOW,
  657.         .intConfig.debounce = 0,
  658.         .intConfig.type     = GPIO_INT_TYPE_FALLING_EDGE,
  659.         .intConfig.callback = OnPinFalling
  660.     };
  661.     GPIO_Init(intPin);
  662.     // configure print pin
  663.     intPin.intConfig.debounce = 200;
  664.     intPin.pin = GPIO_PIN2;
  665.     GPIO_Init(intPin);
  666.     // configure buzzer pin
  667.     buzzerPin.mode = GPIO_MODE_OUTPUT;
  668.     buzzerPin.pin = GPIO_PIN26;
  669.     buzzerPin.defaultLevel = GPIO_LEVEL_LOW;
  670.     GPIO_Init(buzzerPin);
  671.     // configure relay pin
  672.     relayPin.mode = GPIO_MODE_OUTPUT;
  673.     relayPin.pin = GPIO_PIN29;
  674.     relayPin.defaultLevel = GPIO_LEVEL_LOW;
  675.     GPIO_Init(relayPin);
  676.     // configure engine pin
  677.     GPIO_config_t enginePin = {
  678.         .mode         = GPIO_MODE_INPUT,
  679.         .pin          = GPIO_PIN30,
  680.         .defaultLevel = GPIO_LEVEL_LOW
  681.     };
  682.     GPIO_Init(enginePin);
  683.     // schedule the speed sampler for per second
  684.     OS_StartCallbackTimer(mainTaskHandle, 1000, sampleSpeed, NULL);
  685.     // create blocked semaphores
  686.     CreateSem(&connectionSem);
  687.     CreateSem(&transmissionSem);
  688.     CreateSem(&gpsSem);
  689.     // create the gpsTask
  690.     OS_CreateTask(gpsTask,
  691.                 NULL, NULL, GPS_TASK_STACK_SIZE, GPS_TASK_PRIORITY, 0, 0, GPS_TASK_NAME);
  692.     // wait for 5 seconds
  693.     OS_Sleep(5000);
  694.     // create the httpTask
  695.     OS_CreateTask(httpTask,
  696.         NULL, NULL, HTTP_TASK_STACK_SIZE, HTTP_TASK_PRIORITY, 0, 0, HTTP_TASK_NAME);
  697.     // create the update task
  698.     OS_CreateTask(updateTask,
  699.                 NULL, NULL, UPDATE_TASK_STACK_SIZE, UPDATE_TASK_PRIORITY, 0, 0, UPDATE_TASK_NAME);
  700.     // infinite loop
  701.     while(1) {
  702.         // if an event is received
  703.         if(OS_WaitEvent(mainTaskHandle, (void**)&event, OS_TIME_OUT_WAIT_FOREVER)) {
  704.             // signal the event
  705.             EventDispatch(event);
  706.             // clean up
  707.             OS_Free(event->pParam1);
  708.             OS_Free(event->pParam2);
  709.             OS_Free(event);
  710.         }
  711.     }
  712. }
  713.  
  714. void speed_governor_5_Main(void) {
  715.     // create the main task
  716.     mainTaskHandle = OS_CreateTask(mainTask,
  717.         NULL, NULL, MAIN_TASK_STACK_SIZE, MAIN_TASK_PRIORITY, 0, 0, MAIN_TASK_NAME);
  718.     // set up the main task to receive messages
  719.     OS_SetUserMainHandle(&mainTaskHandle);
  720. }
Advertisement
Add Comment
Please, Sign In to add comment