eric liang / Mbed 2 deprecated MQTT_G_SENSOR

Dependencies:   EthernetInterface FXOS8700Q HTTPClient HelloMQTT MQTT cantcoap mbed-rtos mbed

Dependents:   SmartTraffic

Fork of HelloMQTT by MQTT

Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers main.cpp Source File

main.cpp

00001 /*******************************************************************************
00002  * Copyright (c) 2014 IBM Corp.
00003  *
00004  * All rights reserved. This program and the accompanying materials
00005  * are made available under the terms of the Eclipse Public License v1.0
00006  * and Eclipse Distribution License v1.0 which accompany this distribution.
00007  *
00008  * The Eclipse Public License is available at
00009  *    http://www.eclipse.org/legal/epl-v10.html
00010  * and the Eclipse Distribution License is available at
00011  *   http://www.eclipse.org/org/documents/edl-v10.php.
00012  *
00013  * Contributors:
00014  *    Ian Craggs - initial API and implementation and/or initial documentation
00015  *******************************************************************************/
00016  
00017  /**
00018   This is a sample program to illustrate the use of the MQTT Client library
00019   on the mbed platform.  The Client class requires two classes which mediate
00020   access to system interfaces for networking and timing.  As long as these two
00021   classes provide the required public programming interfaces, it does not matter
00022   what facilities they use underneath. In this program, they use the mbed
00023   system libraries.
00024  
00025  */
00026 
00027 
00028 #include "MQTTEthernet.h"
00029 #include "MQTTClient.h"
00030 #include "FXOS8700Q.h"
00031 #include "HTTPClient.h"
00032 #include "WISEAgent.h"
00033 
00034 int arrivedcount = 0;
00035 
00036 #define FXOS8700 1
00037 
00038 // FXOS8700
00039 //FXOS8700Q acc( A4, A5, FXOS8700CQ_SLAVE_ADDR0); // Proper Ports and I2C address for Freescale Multi Axis shield
00040 //FXOS8700Q mag( A4, A5, FXOS8700CQ_SLAVE_ADDR0); // Proper Ports and I2C address for Freescale Multi Axis shield
00041 FXOS8700Q_acc acc( PTE25, PTE24, FXOS8700CQ_SLAVE_ADDR1); // Proper Ports and I2C Address for K64F Freedom board
00042 FXOS8700Q_mag mag( PTE25, PTE24, FXOS8700CQ_SLAVE_ADDR1); // Proper Ports and I2C Address for K64F Freedom board
00043 
00044 
00045 #define SampelTime 1 /// 1 sec
00046 #define SampleCount 30
00047 #define MQTT_BROKER_IP "172.22.12.206"
00048 //#define MQTT_BROKER_IP "192.168.1.13"
00049 #define MQTT_CLIENT_ID "Eric"
00050 #define QUARK_THREAD 0.2
00051 #define SMALL_VAR 1
00052 
00053 float X_LOGs[SampleCount];
00054 float Y_LOGs[SampleCount];
00055 float Z_LOGs[SampleCount];
00056 
00057 float stdDevX = 0.0;
00058 float stdDevY = 0.0;
00059 float stdDevZ = 0.0;
00060 
00061 float g_coeff_X = 0.0;
00062 float g_coeff_Y = 0.0;
00063 float g_coeff_Z = 0.0;
00064 
00065 float g_G_Value = 0.0;
00066 
00067 float meanX = 0.0;
00068 float meanY = 0.0;
00069 float meanZ = 0.0;
00070 
00071 int   log_index = 0;
00072 
00073 float X_BASE = 0;
00074 float Y_BASE = 0;
00075 float Z_BASE = 0;
00076 
00077 
00078 #ifdef FXOS8700
00079 Serial pc(USBTX, USBRX);
00080 
00081 MotionSensorDataUnits mag_data;
00082 MotionSensorDataUnits acc_data;
00083 
00084 MotionSensorDataCounts mag_raw;
00085 MotionSensorDataCounts acc_raw;
00086 #endif
00087 
00088 float standard_deviation(float data[], int n, float *mean );
00089 void CalaulateXYZStatisticValue();
00090 
00091 void Get_G_SensorValue(float *praX, float *praY, float *praZ )
00092 {
00093 #ifdef FXOS8700    
00094     acc.getAxis(acc_data);      
00095     *praX = acc_data.x;
00096     *praY = acc_data.y;
00097     *praZ = acc_data.z;
00098 #endif                        
00099 }
00100 
00101 
00102 void messageArrived(MQTT::MessageData& md)
00103 {
00104     MQTT::Message &message = md.message;
00105     printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\n", message.qos, message.retained, message.dup, message.id);
00106     printf("Payload %.*s\n", message.payloadlen, (char*)message.payload);
00107     ++arrivedcount;
00108 }
00109 
00110 
00111 void SaveLogRingBuf( float faX, float faY, float fzZ )
00112 {
00113     X_LOGs[log_index] = faX;
00114     Y_LOGs[log_index] = faY;
00115     Z_LOGs[log_index] = fzZ;
00116     log_index++;
00117     if( log_index >= SampleCount )
00118         log_index = 0;
00119     
00120 }
00121 
00122 
00123 
00124 void CorrectGSensor()
00125 {
00126     float faX=0,faXt=0, faY=0, faYt=0, faZ=0, faZt=0; 
00127 
00128     int count = 0;          
00129     
00130     printf("Start Correct G-Sensor \n");
00131     while(1) {   
00132         count++;
00133         
00134         Get_G_SensorValue(&faX,&faY,&faZ);
00135         SaveLogRingBuf(faX, faY, faZ);
00136         
00137         faXt += faX; 
00138         faYt += faY; 
00139         faZt += faZ; 
00140         if(count >= SampleCount ) {
00141             X_BASE = faXt / count;
00142             Y_BASE = faYt / count;
00143             Z_BASE = faZt / count;
00144             printf("Stop to Correct G-Sensor Base X=%1.4f Y= %1.4f Z=%1.4f\n", X_BASE, Y_BASE, Z_BASE);
00145             break;
00146         }
00147         //wait(SampelTime); 
00148         wait(0.1); 
00149     }          
00150     CalaulateXYZStatisticValue();
00151 }
00152 
00153 void CalaulateXYZStatisticValue()
00154 {
00155     stdDevX = standard_deviation(X_LOGs,SampleCount,&meanX);
00156     g_coeff_X =   stdDevX / meanX;
00157     
00158     stdDevY = standard_deviation(Y_LOGs,SampleCount,&meanY);
00159     g_coeff_Y =   stdDevY / meanY;
00160     
00161     stdDevZ = standard_deviation(Z_LOGs,SampleCount,&meanZ);
00162     g_coeff_Z =   stdDevZ / meanZ;
00163     
00164     printf(" X St=%1.4f Cof=%1.4f\n Y St=%1.4f Cof=%1.4f\n Z St=%1.4f Cof=%1.4f\n",stdDevX,g_coeff_X,stdDevY,g_coeff_Y,stdDevZ,g_coeff_Z);
00165 }
00166 
00167 
00168 void CheckCalibration()
00169 {
00170     int small_coeff = 0;
00171     
00172     if( ( g_coeff_X < 1.0 && g_coeff_X > -1.0) && ( g_coeff_Y < 1.0 && g_coeff_Y > -1.0) && (g_coeff_Z < 1.0 && g_coeff_Z > -1.0) )
00173             small_coeff = 1;
00174 
00175     
00176     if( g_G_Value > 0.2 ) {
00177         if( small_coeff == 1 ) { 
00178             printf("Device's bais be changed in Correct Mode\n");
00179             CorrectGSensor();
00180         }
00181     }
00182 }
00183 
00184 
00185 void ResetLogBuf()
00186 {
00187     int i = 0;
00188     
00189     for(i=0; i<SampleCount; i++) {
00190         X_LOGs[i]=0.0;
00191         Y_LOGs[i]=0.0;
00192         Z_LOGs[i]=0.0;
00193     }    
00194 }
00195 
00196 void ShowCalibrationValue()
00197 {
00198     float faX=0,faX2=0, faY=0, faY2=0, faZ=0, faZ2=0; 
00199     float g1, g2;
00200     int count = 0;
00201     while(1) {     
00202         Get_G_SensorValue(&faX,&faY,&faZ);
00203 
00204         count++;
00205         faZ2 = faZ - Z_BASE;
00206         faX2 = faX - X_BASE;
00207         faY2 = faY - Y_BASE;
00208         g1 = faX2 * faX2 + faY2 * faY2 + faZ2 * faZ2;
00209         g2 = sqrt(g1);
00210         printf(" %1.4f %1.4f %1.4f  %1.4f\n", faX2, faY2, faZ2, g2 );    
00211         wait(SampelTime);  
00212         if( count >= SampleCount )
00213          break;
00214     }
00215 }
00216 
00217 
00218 float standard_deviation(float data[], int n, float *Mean )
00219 {
00220     float mean=0.0;
00221     float sum_deviation=0.0;
00222     int i;
00223     for(i=0; i<n;++i)
00224     {
00225         mean+=data[i];
00226     }
00227     mean=mean/n;
00228     *Mean = mean;
00229     for(i=0; i<n;++i)
00230     sum_deviation+=(data[i]-mean)*(data[i]-mean);
00231     return sqrt(sum_deviation/n);           
00232 }
00233 
00234 
00235 char *RegistJson = "{\"susiCommData\":{\"devID\":\"%s\",\"hostname\":\"mbed\",\"sn\":\"%s\",\"mac\":\"%s\",\"version\":\"3.1.0.440\",\"type\":\"SenHub\",\"product\":\"mbed\",\"manufacture\":\"Adv\",\"status\":%d,\"commCmd\":1,\"requestID\":21,\"agentID\":\"%s\",\"handlerName\":\"general\",\"sendTS\":%d}}\n";
00236                                 
00237 char *OSInfoJson = "{\"susiCommData\":{\"osInfo\":{\"cagentVersion\":\"3.1.0.440\",\"cagentType\":\"IoTGW\",\"osVersion\":\"\",\"biosVersion\":\"1\",\"platformName\":\"\",\"processorName\":\"\",\"osArch\":\"RTOS\",\"totalPhysMemKB\":101240,\"macs\":\"14:DA:E9:96:BE:05\",\"IP\":\"%s\"},\"commCmd\":116,\"requestID\":109,\"agentID\":\"%s\",\"handlerName\":\"general\",\"sendTS\":%d}}\n";
00238 
00239 #if 1
00240 int main(int argc, char* argv[])
00241 {   
00242     float faX=0,faX2=0, faY=0, faY2=0, faZ=0, faZ2=0;
00243     acc.enable();
00244     float g1=0;
00245     g_G_Value = 0.0;
00246     char *mac = MQTT_CLIENT_ID;
00247     char buf[340];
00248     
00249     
00250     MQTTEthernet ipstack = MQTTEthernet();
00251     
00252    //char* topic = "sen/g-sensor";
00253     char topic[128]={0};   
00254           
00255         
00256     MQTT::Client<MQTTEthernet, Countdown> client = MQTT::Client<MQTTEthernet, Countdown>(ipstack);
00257     MQTT::Message message;
00258     
00259     char* hostname = MQTT_BROKER_IP;
00260     int port = 1883;
00261     printf("Connecting to %s:%d\n", hostname, port);
00262     int rc = ipstack.connect(hostname, port);
00263     if (rc != 0)
00264         printf("rc from TCP connect is %d\n", rc);
00265     else
00266         printf("TCP connect %s OK\n", hostname);
00267  
00268  
00269     //snprintf(buf,sizeof(topic),RegistJson,DEV_UNID, DEV_UNID, DEV_UNID, 0, DEV_UNID, 1436160081000);
00270         
00271     printf("%s\n",buf);
00272     
00273     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
00274     data.MQTTVersion = 3;   
00275     data.clientID.cstring= DEV_UNID;//mac;
00276     //data.username.cstring = "ral";
00277     //data.password.cstring = "123";
00278     // willmessage
00279     //data.willFlag = '1';
00280     //data.will.topicName.cstring = DEF_WILLMSG_TOPIC;
00281     //data.will.message.cstring = buf;
00282     
00283        
00284     if ((rc = client.connect(data)) != 0) {
00285        printf("rc from MQTT connect is %d\n", rc);
00286        return rc;
00287     }
00288     
00289     memset(topic, 0, sizeof(topic));
00290     memset(buf, 0, sizeof(buf));     
00291      
00292     snprintf(topic,sizeof(topic),WA_PUB_CONNECT_TOPIC,DEV_UNID);
00293     snprintf(buf,sizeof(buf),RegistJson,DEV_UNID, DEV_UNID, DEV_UNID, 1, DEV_UNID, 1436160081020);
00294     
00295     message.qos = MQTT::QOS0;
00296     message.retained = false;
00297     message.dup = false;
00298     message.payload = (void*)buf;
00299     message.payloadlen = strlen(buf)+1;
00300      
00301 
00302     printf("len=%d\n",message.payloadlen);       
00303     if( rc = client.publish(topic, message) != 0 ) {
00304        printf("rc from MQTT publish topic=%s rc= %d\n", topic, rc);
00305        return rc;        
00306     }else {
00307         printf("rc topic2 ok\n");
00308     }
00309     wait(SampelTime);
00310     
00311     memset(topic, 0, sizeof(topic));
00312     memset(buf, 0, sizeof(buf)); 
00313     
00314     EthernetInterface eth = ipstack.getEth();
00315     
00316     snprintf(topic,sizeof(topic),WA_PUB_ACTION_TOPIC,DEV_UNID);
00317     snprintf(buf,sizeof(buf),OSInfoJson,eth.getIPAddress(), DEV_UNID, 1436160081030);   
00318     
00319     message.payloadlen = strlen(buf)+1;
00320     printf("len=%d\n",message.payloadlen);              
00321     if( rc = client.publish(topic, message) != 0 ) {
00322        printf("rc from MQTT publish topic=%s rc= %d\n", topic, rc);
00323        return rc;        
00324     }else {
00325         printf("rc topic3 ok\n");
00326     }     
00327     //Init(ipstack);
00328     
00329     
00330     //if( WISEAgentConnect( eth.getIPAddress(), DEV_UNID)!= 0 ) { //eth.getMACAddress());
00331 //        printf("Connect to WISECloud Fail\n");
00332 //    }else
00333   //      printf("Connected to WISECloud =%s\n",MQTT_BROKER_IP);
00334         
00335     while(1){
00336          wait(SampelTime); 
00337          printf("111\n");
00338     }    
00339 #if 0     
00340     MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
00341     data.MQTTVersion = 3;   
00342     //mac = eth.getMACAddress();
00343     data.clientID.cstring= DEV_UNID;//mac;
00344     printf("\nMAC =%s IP=%s\n", data.clientID.cstring, eth.getIPAddress() );
00345     //data.username.cstring = "testuser";
00346     //data.password.cstring = "testpassword";
00347     if ((rc = client.connect(data)) != 0)
00348        printf("rc from MQTT connect is %d\n", rc);
00349     
00350     //if ((rc = client.subscribe(topic, MQTT::QOS1, messageArrived)) != 0)
00351       //  printf("rc from MQTT subscribe is %d\n", rc);
00352 
00353     MQTT::Message message;
00354     char buf[100];
00355     while(1) {      
00356         Get_G_SensorValue(&faX,&faY,&faZ);
00357         
00358         SaveLogRingBuf(faX,faY,faZ);
00359         CalaulateXYZStatisticValue();
00360         
00361         faZ2 = faZ - Z_BASE;
00362         faX2 = faX - X_BASE;
00363         faY2 = faY - Y_BASE;
00364         g1 = faX2 * faX2 + faY2 * faY2 + faZ2 * faZ2;
00365         g_G_Value = sqrt(g1);
00366         //printf(" %1.4f %1.4f %1.4f  %1.4f\n", faX2, faY2, faZ2, g_G_Value );   
00367     
00368         sprintf(buf, "%s %1.4f %1.4f %1.4f %1.4f\n", mac, faX2, faY2, faZ2, g_G_Value );
00369         
00370         CheckCalibration();
00371         
00372         message.qos = MQTT::QOS0;
00373         message.retained = false;
00374         message.dup = false;
00375         message.payload = (void*)buf;
00376         message.payloadlen = strlen(buf)+1;
00377         rc = client.publish(topic, message);
00378 
00379         wait(SampelTime); 
00380                   
00381         memset(buf,0,100);        
00382     }
00383 
00384     
00385     if ((rc = client.disconnect()) != 0)
00386        printf("rc from disconnect was %d\n", rc);
00387     
00388 #endif
00389     
00390     ipstack.disconnect();
00391     
00392     //printf("Version %.2f: finish %d msgs\n", version, arrivedcount);
00393     //printf("Finishing with %d messages received\n", arrivedcount);
00394     
00395     return 0;
00396 }
00397 #else // HTTP
00398 
00399 EthernetInterface eth;
00400 HTTPClient http;
00401 char str[512];
00402 char Instr[512];
00403 
00404 void MCB_HTTPPOST(const char *url, const char *data )
00405 {
00406     sprintf(str, "%s", data);
00407     HTTPText outText(str);
00408     HTTPText inText(Instr, 512);
00409 
00410     int ret = http.post(url, outText, &inText);    
00411     if (!ret)
00412     {
00413       printf("Executed PUT successfully - read %d characters\n", strlen(Instr));
00414       printf("Result: %s\n", str);
00415     }
00416     else
00417     {
00418       printf("Error - ret = %d - HTTP return code = %d\n", ret, http.getHTTPResponseCode());
00419     }    
00420 }
00421 
00422 int main(int argc, char* argv[])
00423 {   
00424     float faX=0,faX2=0, faY=0, faY2=0, faZ=0, faZ2=0;
00425     acc.enable();
00426     float g1=0;
00427     g_G_Value = 0.0;
00428     char buf[100];    
00429     
00430     ResetLogBuf();
00431     
00432     CorrectGSensor();    
00433     
00434     
00435     eth.init(); //Use DHCP
00436     
00437 
00438     eth.connect();
00439               
00440 
00441     while(1) {      
00442         Get_G_SensorValue(&faX,&faY,&faZ);
00443         
00444         SaveLogRingBuf(faX,faY,faZ);
00445         CalaulateXYZStatisticValue();
00446         
00447         faZ2 = faZ - Z_BASE;
00448         faX2 = faX - X_BASE;
00449         faY2 = faY - Y_BASE;
00450         g1 = faX2 * faX2 + faY2 * faY2 + faZ2 * faZ2;
00451         g_G_Value = sqrt(g1);
00452         //printf(" %1.4f %1.4f %1.4f  %1.4f\n", faX2, faY2, faZ2, g_G_Value );   
00453     
00454         //sprintf(buf, "%s %1.4f %1.4f %1.4f %1.4f\n", mac, faX, faY, faZ, g_G_Value );
00455         sprintf(buf,"x,,%1.4f",faX2);
00456         MCB_HTTPPOST("http://api.mediatek.com/mcs/v2/devices/DtIA7o7q/datapoints.csv",buf);
00457         memset(buf,0,100);
00458         
00459         
00460         sprintf(buf,"y,,%1.4f",faY2);
00461         MCB_HTTPPOST("http://api.mediatek.com/mcs/v2/devices/DtIA7o7q/datapoints.csv",buf);
00462         
00463         sprintf(buf,"z,,%1.4f",faZ2);
00464         MCB_HTTPPOST("http://api.mediatek.com/mcs/v2/devices/DtIA7o7q/datapoints.csv",buf);                        
00465         
00466         sprintf(buf,"g,,%1.4f",g_G_Value);
00467         MCB_HTTPPOST("http://api.mediatek.com/mcs/v2/devices/DtIA7o7q/datapoints.csv",buf);
00468                 
00469         CheckCalibration();
00470         
00471         // HTTPClient Send
00472 
00473         wait(SampelTime); 
00474                   
00475         memset(buf,0,100);        
00476     }
00477 
00478     eth.disconnect();  
00479     
00480     
00481     return 0;
00482 }
00483 #endif
00484 
00485