use Dussolved_oxygen_sensor_on_wifi

Dependencies:   watersenor_and_temp_code MQTT NetworkSocketAPI X_NUCLEO_IDW01M1v2 mbed

Fork of DS1820_IDW01M1 by CHANG rozen

main.cpp

Committer:
e58136782000
Date:
2017-11-08
Revision:
7:8eaef8890eee
Parent:
5:42113ea1b319

File content as of revision 7:8eaef8890eee:

#include "mbed.h"
#include "BME280.hpp"
#include "SpwfInterface.h"
#include "TCPSocket.h"
#include "MQTTClient.h"
#include "MQTTWiFi.h"
#include "DS1820.h"

// MQTT use
#define MQTT_MAX_PACKET_SIZE 250
#define MQTT_MAX_PAYLOAD_SIZE 300
//Configuration value needed to connect Red-node
#define BROKER_URL "192.168.20.116";
#define MQTT_PORT 1883
//MQTT use Topic 
#define TOPIC "6"
#define SUB_TOPIC "LED"


//Wifi network
#define SSID "tnta"
#define PASSW "tnta2355818"
Serial serial(USBTX, USBRX);
DigitalOut myled(LED1);
//BME280 bmpSensor;
int connack_rc = 0;    // MQTT connack return code
const char * ip_addr = "";
char *host_addr = "";
bool netConnecting = false;
int connectTimeout = 1000;
bool mqttConnecting = false;
bool netConnected = false;
bool connected = false;
int retryAttempt = 0;
char subscription_url[MQTT_MAX_PAYLOAD_SIZE];

MQTT::Message message;
MQTTString TopicName={TOPIC};
MQTT::MessageData MsgData1(TopicName, message);

BME280 BME280;

void subscribe_LED(char* msg){
	int value = atoi(msg);
	//printf("value = %d\n", value);
	if(value ==1){
		myled = !myled;
	}
	
}


void subscribe_cb(MQTT::MessageData & msgMQTT) {
    char msg[MQTT_MAX_PAYLOAD_SIZE];
    msg[0]='\0';
    strncat (msg, (char*)msgMQTT.message.payload, msgMQTT.message.payloadlen);
    printf ("--->>> subscribe_cb msg: %s\n\r", msg);
    subscribe_LED(msg);
}
int subscribe(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
{
    char* pubTopic = SUB_TOPIC;    
    return client->subscribe(pubTopic, MQTT::QOS1, subscribe_cb);
}


int connect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack){
    const char* host = BROKER_URL;

    char hostname[strlen(host) + 1];
    sprintf(hostname,"%s", host);

    SpwfSAInterface& WiFi = ipstack->getWiFi();

    //Network Debug statements
    LOG("=====================================\n\r");
    LOG("Connecting WiFi.\n\r");
    LOG("Nucleo IP ADDRESS: %s\n\r", WiFi.get_ip_address());
    LOG("Nucleo MAC ADDRESS: %s\n\r", WiFi.get_mac_address());
    LOG("Server Hostname: %s port: %d\n\r", hostname, MQTT_PORT);
    LOG("Topic1: %s\n\r", TOPIC);
    //need subscrie
    LOG("=====================================\n\r");
    netConnecting = true;
    ipstack->open(&ipstack->getWiFi());
    int rc = ipstack->connect(hostname,MQTT_PORT,connectTimeout);
     if (rc != 0)
    {
        WARN("IP Stack connect returned: %d\n", rc);    
        return rc;
    }
    printf ("--->TCP Connected\n\r");
    netConnected = true;
    netConnecting = false;

    //MQTT Connect
    mqttConnecting = true;
    MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
    data.MQTTVersion = 4;
    data.struct_version =0;

    if((rc = client->connect(data)) == 0){
    	connected = true;
    	printf("--->MQTT Connected\n\r");
//#ifdef SUBSCRIBE
        if (!subscribe(client, ipstack)) printf ("--->>>MQTT subscribed to: %s\n\r",SUB_TOPIC);
//#endif 
    }else {
        WARN("MQTT connect returned %d\n", rc);        
    }
    if (rc >= 0)
        connack_rc = rc;
        mqttConnecting = false;
        return rc;
   
}
int getConnTimeout(int attemptNumber)
{  // First 10 attempts try within 3 seconds, next 10 attempts retry after every 1 minute
   // after 20 attempts, retry every 10 minutes
    return (attemptNumber < 10) ? 3 : (attemptNumber < 20) ? 60 : 600;
}
void attemptConnect(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client, MQTTWiFi* ipstack)
{
    connected = false;
           
    while (connect(client, ipstack) != MQTT_CONNECTION_ACCEPTED) 
    {    
        /*if (connack_rc == MQTT_NOT_AUTHORIZED || connack_rc == MQTT_BAD_USERNAME_OR_PASSWORD) {
            printf ("File: %s, Line: %d Error: %d\n\r",__FILE__,__LINE__, connack_rc);        
            return; // don't reattempt to connect if credentials are wrong
        } */
        int timeout = getConnTimeout(++retryAttempt);
        WARN("Retry attempt number %d waiting %d\n", retryAttempt, timeout);
        
        // if ipstack and client were on the heap we could deconstruct and goto a label where they are constructed
        //  or maybe just add the proper members to do this disconnect and call attemptConnect(...)        
        // this works - reset the system when the retry count gets to a threshold
        if (retryAttempt == 5)
            NVIC_SystemReset();
        else
            wait(timeout);
    }
}
int publish(MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE>* client,MQTTWiFi* ipstack,int data){
	
    
	MQTT::Message message;
	char *pubTopic = TOPIC;
	char buf[MQTT_MAX_PAYLOAD_SIZE];
	printf("Dissolved oxygen = %d\n", data);
	sprintf(buf,"%d",data);
	message.qos = MQTT::QOS0;
	message.retained = false;
    message.dup = false;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf);

    printf("Publishing %s\n\r", buf);
    return client->publish(pubTopic, message);
}

int ASCIIChangeInteger(int datain)
{
	int databuffer1;
	if(datain >= 0x30)
	{
		if(datain >= 0x3A)
		{
			serial.printf("ASCIIChangeInteger datain too big \n");			
		}
		else
		{
			databuffer1 = datain - 0x30;			
		}
	}
	else
	{
			serial.printf("ASCIIChangeInteger datain too small \n");		
	}
	serial.printf("ASCIIChangeInteger databuffer1 : %d \n", databuffer1);
	return databuffer1;
}

int Conversionfunction(int TxRxdata1, int TxRxdata2, int TxRxdata3, int TxRxdata4, int TxRxdata5)
{
	int databuffer;
	serial.printf("dataTensdigit: %d\n",TxRxdata1);
	serial.printf("Digits: %d\n",TxRxdata2);
	if(TxRxdata2 == 0x2E)
	{
		databuffer = ASCIIChangeInteger(TxRxdata1);	
		return databuffer;	
	}
	else
	{	
		if(TxRxdata3 == 0x2E)
		{
			databuffer = ASCIIChangeInteger(TxRxdata1)*10 + ASCIIChangeInteger(TxRxdata2);
			return databuffer;			
		}
		else
		{
			if(TxRxdata5 == 13)
			{
				databuffer = ASCIIChangeInteger(TxRxdata1)*1000 + ASCIIChangeInteger(TxRxdata2)*100 + ASCIIChangeInteger(TxRxdata3)*10 + ASCIIChangeInteger(TxRxdata4);
				return databuffer;
			}
			else
			{
				databuffer = ASCIIChangeInteger(TxRxdata1)*100 + ASCIIChangeInteger(TxRxdata2)*10 + ASCIIChangeInteger(TxRxdata3);
				serial.printf("datanumber1: %d\n",databuffer);
				return databuffer;	
			}	
		}
	}
}
int main()
{
	myled =0;
    
	
	const char *ssid = SSID;
	const char *seckey = PASSW;
	//use SpwfSAInterface connect AP
	SpwfSAInterface spwf(D8,D2, false);
	printf("\r\nX-NUCLEO-IDW01M1 mbed \n");
	printf("\r\nconnecting to AP\n");
	//connect to Wifi
	MQTTWiFi ipstack(spwf, ssid, seckey, NSAPI_SECURITY_WPA2);
	//check wifi has got ip_address
	if(ipstack.getWiFi().get_ip_address() == 0){
		printf("Connect WiFi is failed!\nPlease check your ssid and passwd is correct");
		return 0;
	}
	printf("ip: %s\n",ipstack.getWiFi().get_ip_address() );

	MQTT::Client<MQTTWiFi, Countdown, MQTT_MAX_PACKET_SIZE> client(ipstack);
	attemptConnect(&client, &ipstack); 
	sensor.format(8,Serial::None,1);
   int count = 0;  
   int databuffer3 = 0;  
//    tyeld.start();    
    while (true){
    	BME280.receive();
    	serial.printf("data 1 : %d\n",BME280.datareadfuiction(0));
        serial.printf("data 2 : %d\n",BME280.datareadfuiction(1));
        serial.printf("data 3 : %d\n",BME280.datareadfuiction(2));
        serial.printf("data 4 : %d\n",BME280.datareadfuiction(3));
        serial.printf("data 5 : %d\n",BME280.datareadfuiction(4));
        serial.printf("data 6 : %d\n",BME280.datareadfuiction(5));

        wait(10);
        if(BME280.datareadfuiction(0) == 13)
        {
        	databuffer3 = Conversionfunction(BME280.datareadfuiction(1),BME280.datareadfuiction(2),BME280.datareadfuiction(3),BME280.datareadfuiction(4),BME280.datareadfuiction(0));
        }
        else
        {
			databuffer3 = Conversionfunction(BME280.datareadfuiction(3),BME280.datareadfuiction(4),BME280.datareadfuiction(5),BME280.datareadfuiction(0),BME280.datareadfuiction(1));        	
        }
    	if (++count == 3)
    	{               // Publish a message every second
    		if (publish(&client, &ipstack,databuffer3) != 0) 
    		{ 
	     	   	attemptConnect(&client, &ipstack);   // if we have lost the connection                
	     	}
        count = 0;
    	}
    	else
    	{
    		serial.printf("count: %d \n",count);
    	}      
//  	int start = tyeld.read_ms();
    	//client.yield(10);  // allow the MQTT client to receive messages
//  	printf ("tyeld: %d\n\r",tyeld.read_ms()-start);
    	}
}