Smart Traffic

Dependencies:   MQTT_G_SENSOR

Revision:
0:f0ae089c9363
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/WISEAgent.cpp	Wed Aug 12 02:44:16 2015 +0000
@@ -0,0 +1,83 @@
+#include "WISEAgent.h"
+
+void messageCbf(MQTT::MessageData& md)
+{
+    MQTT::Message &message = md.message;
+    printf("Message arrived: qos %d, retained %d, dup %d, packetid %d\n", message.qos, message.retained, message.dup, message.id);
+    printf("Payload %.*s\n", message.payloadlen, (char*)message.payload);
+}
+
+MQTT::Client<MQTTEthernet, Countdown> *pMQTTClient;
+
+void Init(MQTTEthernet ipstack)
+{
+    if( !pMQTTClient )
+        pMQTTClient = new MQTT::Client<MQTTEthernet, Countdown>(ipstack);    
+}
+
+int WISEAgentConnect(const char *ip, char *uid)
+{
+    int rc = 0;
+    MQTT::Message message;
+        
+    // Register
+    char topic[128]={0};
+    char buf[256]={0};
+        
+    //snprintf(buf,sizeof(topic),RegistJson,uid, uid, uid, 0, uid, 1436160081000);
+        
+    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;       
+    data.MQTTVersion = 3;   
+    data.clientID.cstring= uid;//mac;
+    data.username.cstring = "ral";
+    data.password.cstring = "123";
+    // willmessage
+    data.will.topicName.cstring = DEF_WILLMSG_TOPIC;
+    data.will.message.cstring = buf;
+    
+    memset(topic, 0, sizeof(topic));
+    memset(buf, 0, sizeof(buf)); 
+        
+    if ((rc = pMQTTClient->connect(data)) != 0) {
+       printf("rc from MQTT connect is %d\n", rc);
+       return rc;
+    }
+           
+    snprintf(topic,sizeof(topic),WA_PUB_CONNECT_TOPIC,uid);
+    //snprintf(buf,sizeof(topic),RegistJson,uid, uid, uid, 1, uid, 1436160081020);
+    
+    message.qos = MQTT::QOS0;
+    message.retained = false;
+    message.dup = false;
+    message.payload = (void*)buf;
+    message.payloadlen = strlen(buf)+1;
+            
+    if( rc = pMQTTClient->publish(topic, message) != 0 ) {
+       printf("rc from MQTT publish topic=%s rc= %d\n", topic, rc);
+       return rc;        
+    }
+    
+    memset(topic, 0, sizeof(topic));
+    memset(buf, 0, sizeof(buf)); 
+
+    snprintf(topic,sizeof(topic),WA_PUB_ACTION_TOPIC,uid);
+    //snprintf(buf,sizeof(topic),OSInfoJson,ip, uid, 1436160081030);   
+
+    message.payloadlen = strlen(buf)+1;
+            
+    if( rc = pMQTTClient->publish(topic, message) != 0 ) {
+       printf("rc from MQTT publish topic=%s rc= %d\n", topic, rc);
+       return rc;        
+    }        
+    
+    memset(topic, 0, sizeof(topic));
+    memset(buf, 0, sizeof(buf));     
+    snprintf(topic,sizeof(topic),WA_SUB_CBK_TOPIC,uid);    
+
+    if ((rc = pMQTTClient->subscribe(topic, MQTT::QOS1, messageCbf)) != 0) {
+        printf("rc from MQTT subscribe is %d\n", rc);     
+        return rc;
+    }
+    
+    return rc;
+}
\ No newline at end of file