scooter correction for mbed_os V5.2

Dependencies:   bloc_io html_mbed_os

Fork of scooter_mbed by ERS3 2015-2016

Revision:
1:e3cb81b3cbea
Parent:
0:8871b0c9af3b
Child:
3:ac3990c4a479
--- a/main.cpp	Tue Aug 11 15:01:10 2015 +0000
+++ b/main.cpp	Wed Aug 12 15:54:13 2015 +0000
@@ -1,9 +1,10 @@
 
 
-#include "EthernetInterface.h"
+//#include "EthernetInterface.h"
 #include <stdlib.h>
 #include <string.h>
 #include "mbed.h"
+#include "rtos.h" // need for main thread sleep
 #include "html.h" // need for html patch working with web server
 #include "bloc_io.h"
 #define RADIUS  0.2F // wheel size
@@ -35,23 +36,27 @@
     
     
 /********************* web server section **********************************/
-char * ma_chaine3;
+//char * ma_chaine3;
 var_field_t tab_balise[10];  //une balise est présente dans le squelette
 int giCounter=0;// acces counting
 
 
+/*********************** can bus section  ************/
+#define GAZ_CAN_ID 1000 // determine message ID used to send Gaz ref over can bus
+#define _CAN_DEBUG // used to debug can bus activity
+#define USE_CAN_REF // uncomment to receive gaz ref over can_bus
+CANMessage msg_receive,msg_send;
+DigitalOut led1(LED1); //initialisation des Leds présentes sur le micro-controleur Mbed*/
+DigitalOut led2(LED2);
+DigitalOut led3(LED3); // blink when can message is sent
+DigitalOut led4(LED4); // blink when can message is received 
+CAN can_port (p30, p29); // initialisation du Bus CAN sur les broches 30 (rd) et 29(td) for lpc1768 + mbed shield
+int iGaz_Can=0;
+bool bCan_Active=false;
+ 
 
  
-EthernetInterface eth; // ethernet layer management object
-TCPSocketServer svr; //
-bool serverIsListened = false;// flag to indicate server is listening
- 
-#define PORT   80 // tcp port for socket listeningt 
-TCPSocketConnection client;// socket to identify client side
-bool clientIsConnected = false;// flag that indicate if a web client is avalaible
- 
 //************ prototypes *******************
-int Init_Web_Server(void);
 
 
 
@@ -61,7 +66,7 @@
  //***********
 //* functions
 
-
+/**************** Read persistent data from text file located on local file system ****************/
 int Read_File_Data(char * pcFileName)
 {
 float fRayon;
@@ -76,13 +81,17 @@
  {fscanf (DataFile,"rayon:%f ",&fRayon);// insert ' ' after %format mode to separe numeric data
  fscanf (DataFile,"poles:%d ",&iPoles);
  fscanf (DataFile,"vit_max:%d ",&iVit_Max);
- printf("valeurs lues: rayon:%f poles:%d  vit_max:%d \n\r",fRayon,iPoles,iVit_Max);
+ fscanf (DataFile,"fgaz_max:%f ",&fGAZ_MAX);
+  fscanf (DataFile,"fgaz_min:%f ",&fGAZ_MIN);
+ printf("valeurs lues: rayon:%f poles:%d vit_max:%d gaz_max:%f gaz_min:%f \n\r",fRayon,iPoles,iVit_Max,fGAZ_MAX,fGAZ_MIN);
   fclose(DataFile);
   return 0; 
   } 
     
 }
 
+
+/**************** write persitant  data to text file located on local file system ****************/
 int Write_File_Data(char * pcFileName)
 {
 float fRayon=0.45;
@@ -97,9 +106,9 @@
     return(NULL);
    }
  else
- { fprintf (DataFile, "rayon:%f poles:%d vit_max:%d ",fRayon,iPoles,iVit_Max);
+ { fprintf (DataFile, "rayon:%f poles:%d vit_max:%d gaz_max:%f gaz_min:%f \n\r",fRayon,iPoles,iVit_Max,fGAZ_MAX,fGAZ_MIN);
     
- printf("valeurs ecrites: rayon:%f poles:%d  vit_max:%d \n\r",fRayon,iPoles,iVit_Max);
+ printf("valeurs ecrites: rayon:%f poles:%d vit_max:%d gaz_max:%f gaz_min:%f \n\r",fRayon,iPoles,iVit_Max,fGAZ_MAX,fGAZ_MIN);
   fclose(DataFile);
   return 0; 
   } 
@@ -107,135 +116,11 @@
 }
 
 
-int Init_Web_Server(void)
-  {
- 
-    //setup ethernet interface
-    eth.init(); //Use DHCP
-    eth.connect();
-    pc.printf("IP Address is %s\n\r", eth.getIPAddress());// display server ip address
- 
-     // Set the callbacks for Listening
-  //srv.setOnEvent(&onListeningTCPSocketEvent);  // create a call back fonction associated with listning socket
-    //setup srv tcp socket
-    if(svr.bind(PORT)< 0) {
-        printf("tcp server bind failed.\n\r");
-        return -1;
-    } else {
-        printf("tcp server bind successed.\n\r");
-        serverIsListened = true;
-    }
- 
-    if(svr.listen(1) < 0) {
-        printf("tcp server listen failed.\n\r");
-        return -1;
-    } else {
-        printf("tcp server is listening...\n\r");
-       
-
-    }
-    return 0;
- }
-   
 
 
 
- 
-  
-          
- 
 
-
-/***************** thread section **************/
-#include "rtos.h"
- 
-void Web_Server_Thread(void const *args) 
-{
-    while ( serverIsListened) {
-        //blocking mode(never timeout)
-        if(svr.accept(client)<0) {
-            pc.printf("failed to accept connection.\n\r");
-        } else {
-            pc.printf("connection success!\n\rIP: %s\n\r",client.get_address());
-            clientIsConnected = true;
-             // Setup the new socket events
-       // client.setOnEvent(&onConnectedTCPSocketEvent);
-        // We can find out from where the connection is coming by looking at the
-        // Host parameter of the accept() method
-            
-            while(clientIsConnected) {
-                char buffer[1024] = {};
-                char ma_chaine4[20]={};// needed to form html response
-                switch(client.receive(buffer, 1023)) {
-                    case 0:
-                        pc.printf("recieved buffer is empty.\n\r");
-                        clientIsConnected = false;
-                        break;
-                    case -1:
-                        pc.printf("failed to read data from client.\n\r");
-                        clientIsConnected = false;
-                        break;
-                    default:
-                        pc.printf("Recieved Data: %d\n\r\n\r%.*s\n\r",strlen(buffer),strlen(buffer),buffer);
-                        if(buffer[0] == 'G' && buffer[1] == 'E' && buffer[2] == 'T' ) {
-                            pc.printf("GET request incomming.\n\r");
-                            //setup http response header & data
-                            /************* patch all dynamic data in html response page ************/
-                            giCounter++;
-                            sprintf (ma_chaine4,"%d",(int)fSpeed);// convert speed as ascii string
-                            Html_Patch (tab_balise,0,ma_chaine4);// patch first label with dyn.string
-                            
-                            sprintf (ma_chaine4,"%d",(int)(fGaz_Brute*100)/255);// convert count as ascii string
-                            Html_Patch (tab_balise,1,ma_chaine4);// patch first label with dyn.string
-                            
-                             sprintf (ma_chaine4,"%d",(int)fBat);// convert count as ascii string
-                            Html_Patch (tab_balise,2,ma_chaine4);// patch first label with dyn.string
-                            
-                             sprintf (ma_chaine4,"%d",(int)fIdc);// convert count as ascii string
-                            Html_Patch (tab_balise,3,ma_chaine4);// patch first label with dyn.string
-                           
-                             sprintf (ma_chaine4,"%d",(int)fTemp);// convert count as ascii string
-                            Html_Patch (tab_balise,4,ma_chaine4);// patch first label with dyn.string
-                            
-                            char echoHeader[256] = {};
-                            sprintf(echoHeader,"HTTP/1.1 200 OK\n\rContent-Length: %d\n\rContent-Type: text\n\rConnection: Close\n\r",strlen(ma_chaine3));
-                            client.send(echoHeader,strlen(echoHeader));
-                             pc.printf("%s",echoHeader);// debut http header sent
-                                                      
-                            //client.send(buffer,strlen(buffer));// realise echo request to client 
-                             
-                                  
-                            client.send(ma_chaine3,strlen(ma_chaine3));// realise echo request to client 
-                           
-                            pc.printf("%s",ma_chaine3);
-                           
-                            
-                            clientIsConnected = false;// close connection with this client at end of http response
-                            pc.printf("web page sent.\n\r");
-                        }
-                        break;
-                }// end case
-           //Thread::wait(10);// sleep for 10 ms
-            }// end while Client is Connected
-           
-            pc.printf("close connection.\n\rtcp server is listening...\n\r");
-            client.close();
-           
-       
-        }
-    Thread::wait(10);// sleep for 10 ms
-   } // end while ServerIs listening
-}
- 
-
-
-
-    
-    
-    
-    
-    
-// needed to record min_gaz and max_gaz value to persistent text file
+//************** needed to record min_gaz and max_gaz value to persistent text file  ******************
 void Calibrate_Gaz(void)
 { char cJunk;     
 
@@ -253,16 +138,17 @@
     fTabVal[1]=Gaz.read()*100;// read max gaz value
       fGAZ_MAX=fTabVal[1];// update local GAZ_MIN constante
     pc.printf("calibration terminee: gaz_min=%f    gaz_max=%f \n",fTabVal[0],fTabVal[1]); 
+    Write_File_Data("/local/persist.txt"); // write persistent data to text file
 
 }
 
-// top hall counting interre
+// ************top hall counting interupt needed for speed measurement
 void SpeedCount(void)
 {uiCptImpuls++;// top hall encoured increment speed counter
     }
 
 
-// timer interrupt for speed measurement each 100ms
+//********************** timer interrupt for speed measurement each 100ms  *************************
 void MyITSpeed(void)
 {unsigned int uiCptSpeed;
 
@@ -275,7 +161,7 @@
     
 
 
-//Timer Interrupt for gaz ref management each 10ms
+//********************* Timer Interrupt for gaz ref management each 10ms   ********************
 void MyITGaz (void) 
 {unsigned char byRefPWM=0;
 
@@ -283,7 +169,13 @@
  fBat=Bat.read()*100;// read actual Bat voltage
  fIdc=Idc.read()*100;// read actual Idc current
  fTemp=Temp.read()*100;// readf actual Temp
- fGaz_Brute= (float)255/(fGAZ_MAX-fGAZ_MIN)* (fGaz-fGAZ_MIN);
+ 
+ #ifndef USE_CAN_REF
+ fGaz_Brute= (float)255/(fGAZ_MAX-fGAZ_MIN)* (fGaz-fGAZ_MIN);/ use local ref
+ #else
+ fGaz_Brute= iGaz_Can;// use can bus gaz ref
+ #endif
+ 
  if (fGaz_Brute>255) fGaz_Brute=255;
  if (fGaz_Brute<0) fGaz_Brute=0;
  byRefPWM=(unsigned char) fGaz_Brute;
@@ -291,23 +183,82 @@
 }
 
 
+/********* main cgi function used to patch data to the web server thread **********************************/
+void CGI_Function(void) // cgi function that patch web data to empty web page
+{  char ma_chaine4[20]={};// needed to form html response  
+                         sprintf (ma_chaine4,"%d",(int)fSpeed);// convert speed as ascii string
+                            Html_Patch (tab_balise,0,ma_chaine4);// patch first label with dyn.string
+                            
+                            sprintf (ma_chaine4,"%d",(int)(fGaz_Brute*100)/255);// convert count as ascii string
+                            Html_Patch (tab_balise,1,ma_chaine4);// patch first label with dyn.string
+                            
+                             sprintf (ma_chaine4,"%d",(int)fBat);// convert count as ascii string
+                            Html_Patch (tab_balise,2,ma_chaine4);// patch first label with dyn.string
+                            
+                             sprintf (ma_chaine4,"%d",(int)fIdc);// convert count as ascii string
+                            Html_Patch (tab_balise,3,ma_chaine4);// patch first label with dyn.string
+                           
+                             sprintf (ma_chaine4,"%d",(int)fTemp);// convert count as ascii string
+                            Html_Patch (tab_balise,4,ma_chaine4);// patch first label with dyn.string
+                            
+    
+    
+    }
+    
+    
+  /*********************** CAN BUS SECTION  **********************/
+    
+
+
+void CAN_REC_THREAD(void const *args)
+{ int iCount,iError;
+
+ while (bCan_Active)
+ {Thread::wait(100);// wait 100ms  
+    //printf("CAN_REC_Thread\n\r");
+    if(can_port.read(msg_receive)) //si on lit un message reçu */
+    //can_port.read(msg_receive);
+    {iError=0; 
+    #ifdef _CAN_DEBUG
+    printf("CAN Message received : %s\n id=%d\n\r", msg_receive.data,msg_receive.id);
+  # endif
+    switch (msg_receive.id) {
+      case GAZ_CAN_ID: // received Gaz from can
+       sscanf((char *)msg_receive.data,"%03d",&iGaz_Can);// read and convert gaz ref from can bus
+       led4=!led4;
+        #ifdef _CAN_DEBUG
+      for (iCount=0; iCount<=5;iCount++)
+            {led4=!led4;
+           Thread::wait(100);
+            }
+         #endif  
+       break;
+    
+    }
+    }
+    }
+    
+}
+       
+    
+  
+
 int main() {
     
     char cChoix=0;
-int iIndex,iVal,iRefPWM;
+int iVal,iRefPWM;
 
 
 Read_File_Data("/local/persist.txt"); // read persistent data from text file
- Write_File_Data("/local/persist.txt"); // write persistent data to text file
-//***************************************** web section ********************************************
+ //Write_File_Data("/local/persist.txt"); // write persistent data to text file
+//***************************************** web section ********************************************/
+Init_Web_Server(&CGI_Function); // create and initialize tcp server socket and pass function pointer to local CGI function
+Thread WebThread(Web_Server_Thread);// create and launch web server thread
+//******************************************* end web section  ************************************* / 
 
 
-Init_Web_Server(); // create and initialize tcp server socket
-Thread WebThread(Web_Server_Thread);// create and launch web server thread
-//******************************************* end web section  *************************************  
-
-
-  ma_chaine3 = Gen_HtmlCode_From_File("/local/pagecgi2.htm",tab_balise,5);// read and localise ^VARDEF[X] tag
+//ma_chaine3 = Gen_HtmlCode_From_File("/local/pagecgi2.htm",tab_balise,5);// read and localise ^VARDEF[X] tag
+Gen_HtmlCode_From_File("/local/pagecgi2.htm",tab_balise,5);// read and localise ^VARDEF[X] tag in empty html file
 
 IT_Timer_Gaz.attach_us(&MyITGaz, 10000);// install timer it each 10ms
 IT_Speed.attach_us(&MyITSpeed, 100000);// install timer it each 10ms
@@ -317,6 +268,12 @@
 MyPLD.write(0);// set initial PWM ref=0
 ValidPWM.write(1);// enable pwm generator
 
+can_port.frequency(125000); //on impose une fréquence commune pour etre s’incroniser
+//can_port.attach(&CAN_REC_IRQ); // install CAN BUS IRQ on data received 
+bCan_Active=true;
+Thread CanThread(CAN_REC_THREAD);// create and launch can receiver  thread
+
+
 while(cChoix!='q' and cChoix!='Q')
 {pc.printf(" veuillez saisir un choix parmi la liste proposee: \n");
  pc.printf(" a:saisie consigne pwm \n");
@@ -325,9 +282,10 @@
 pc.printf(" d:calibration poignee Gaz \n");
 pc.printf(" e:affichage vitesse  \n");
  pc.printf(" q:quitter \n");
- 
- while (pc.readable()==0)// determine if char available)
+ /************* multithreading : main thread need to sleep in order to allow web response */
+ while (pc.readable()==0) // determine if char availabler
  {Thread::wait(10);} // wait 10 until char available on serial input
+ /************* end of main thread sleep  ****************/ 
  pc.scanf(" %c",&cChoix);
  switch (cChoix){
      case 'a': pc.printf(" veuillez saisir une consigne pwm entre 0 et 255 \n");
@@ -351,6 +309,7 @@
        fBat=Bat.read()*100;
        fIdc=Idc.read()*100;
        pc.printf("valeur gaz:%3f  Temperature:%3f   Vbat:%3f   Idc:%3f \n",fGaz,fTemp,fBat,fIdc);
+       pc.printf("valeur temp:%3f \n\r",fTemp*5.1282-53.53);
        break;
        
        case 'd': // calibration poignée gaz
@@ -374,5 +333,8 @@
     IT_Speed.detach();// uninstall timer interrupt
     MyPLD.write(0);// stop motor before exiting
     ValidPWM.write(0);// disable pwm generator
+     DeInit_Web_Server();
+     bCan_Active=false;
+     CanThread=false;// close can received thread
     pc.printf(" fin programme scooter mbed \n");
 }