#include "mraa.hpp" extern "C" { #include "MQTTClient.h" } #include "credentials.h" #include "stdlib.h" #include "stdio.h" #include "math.h" #include using namespace std; MQTTClient client; MQTTClient receiver; // define o topico para efetuar publicações #define MESSAGE_TOPIC "/aula/pub" // define o topico em que o dispositivo efetuara a inscricao // ou seja, sera os dados de tal topico #define TOPIC_SUBSCRIBE "/aula/sub" // protocolo utilizado para conexao com o Broker #define HOST_PROTO "tcp: // url do servidor referente ao Broker #define HOST_SUFFIX "meioseletronicos.pad.lsi.usp.br:" // define o id do cliente - IMPORTANTE: tal id nao pode se repetir em uma mesma conexao com o broker #define client_id "aula7" // porta padrao para o servico de MQTT, utilizada para se conectar com o Broker #define HOST_PORT "1883" // Valor maximo do contador utilizado para exemplo na aplicacao #define DUMMY_MAX_VALUE 100 // Configuracao da qualidade de servico desejada // QoS0 --> A mensagem sera enviada uma ou nenhuma vez // QoS1 --> A mensagem sera enviada no minimo uma vez // QoS2 --> A mensagem sera enviada exatamente uma vez #define MQTT_DEFAULT_QOS 0 /* * This function is called when a message has been successfully published * to the server * Note:This function is not called when messages are * published at QoS0. * @param context A pointer to the context value originally passed to * MQTTClient_setCallbacks(), which contains any application-specific context. * @param dt The ::MQTTClient_deliveryToken associated with * the published message. Applications can check that all messages have been * correctly published by matching the delivery tokens returned from calls to * MQTTClient_publish() and MQTTClient_publishMessage() with the tokens passed * to this callback. */ void delivery_complete(void * context, MQTTClient_deliveryToken dt) { printf("Publishing of message with token %d confirmed\n", dt); } /* * This function will be called when the MQTT client lost the * connection to the server * @param context A pointer to the context value originally passed to * MQTTClient_setCallbacks(), which contains any application-specific context. * @param cause The reason for the disconnection. * Currently, cause is always set to NULL. */ void connection_lost(void * context, char* cause) { printf("Connection lost\n"); exit(MQTTCLIENT_DISCONNECTED); } int autocontrol; int ledstate[3]; double result = 0.0; //Funcao utilizada em parte para efetuar o parse dos dados recebidos pelo MQTT int getInteger(int values[],int size ){ int out = 0; int i; int mult; for(i = 0;i <= size;i++){ mult = pow(10,(size-i)); out =out+ mult*values[i]; } return out; } /* is message is called when the subscribed topic is updated. The received message arrive in a variable of type MQTTClient_message that contains the payload (content) from the message. */ int msgarrvd(void *context, char *topicName, int topicLen, MQTTClient_message *message) { char* payloadptr; //message result format {"autocontrol":"value","ledstate":"value"} - JSON printf("\nMessage arrived\n"); printf(" topic: %s\n", topicName); printf(" message: \n"); payloadptr = (char*)message->payload; printf("%s\n",payloadptr); int i = 0; autocontrol = payloadptr[16]-'0'; char *c = payloadptr+31; while(*c != '"'){ ledstate[i]=*c-'0'; //printf("X%d = %d\n",i,ledstate[i]); c++; i++; } result = (double)getInteger(ledstate,i-1)/255; //printf("PWM level: %f\n",result); MQTTClient_freeMessage(&message); MQTTClient_free(topicName); return 1; } int main() { char host[256]; char clientID[256]; //define o usuario de acesso ao broker volatile const char * username = "aula_psi"; // define a senha de acesso ao broker volatile const char * password = "psi2016"; mraa_pwm_context pino_atuador = NULL; pino_atuador = mraa_pwm_init(11); mraa_pwm_enable(pino_atuador, 1); //concatena os dados de protocolo + servidor + porta para construir a url de conexao com o broker snprintf(host, sizeof host, "%s%s%s", HOST_PROTO, HOST_SUFFIX, HOST_PORT); //constroi a variavel referente ao id do cliente snprintf(clientID, sizeof clientID, "%s",client_id); // create the MQTT client cerr << "Creating client publisher" << endl; int rc = 0; rc = MQTTClient_create(&client, const_cast(host),const_cast(clientID), MQTTCLIENT_PERSISTENCE_NONE, NULL); if (rc != MQTTCLIENT_SUCCESS) { std::cerr << "Failed to create MQTT client, exiting" << std::endl; exit(rc); } cerr << "Setting callback client publisher" << endl; // setup call backs before connecting the client to the server /* The callbacks function is used to represents all responses received from the MQTT server. When it is set the application put the client in a multithread state. All response from the server become completely independent from the client application. */ MQTTClient_setCallbacks(client, NULL,&connection_lost, &msgarrvd, &delivery_complete); MQTTClient_connectOptions data = MQTTClient_connectOptions_initializer; data.username = const_cast(username); data.password = const_cast(password); cerr << "Connecting client publisher" << endl; // connect the client to the server rc = MQTTClient_connect(client, &data); if (rc != MQTTCLIENT_SUCCESS) { std::cerr << "Failed to connect MQTT client, exiting" << std::endl; exit(rc); } /* APOS ANALISAR OS SLIDES DE AULA, IMPLEMENTE AQUI O CODIGO PARA EFETUAR A SUBSCRICAO DO GALILEO NO BROKER */ //subscribe the client in a specified topic rc = MQTTClient_subscribe(client,const_cast(TOPIC_SUBSCRIBE),MQTT_DEFAULT_QOS); if(!rc){ cerr << "Sucessfully subscribed" << endl; } // dummy data used to send to the IBM Bluemix quickstart unsigned short dummyData = 1; // loop forever updating the temperature values every second for (;;) { // send message to IBM Bluemix char payload[80]; //constroi a estrutura da mensagem que sera publicada no broker sprintf(payload, "{ \"counter\": \"%d\" }", dummyData); int message_size = strlen(payload); int retained = 0; MQTTClient_deliveryToken dt; int rc = MQTTClient_publish(client, const_cast(MESSAGE_TOPIC), message_size, const_cast(payload), MQTT_DEFAULT_QOS, retained, &dt); if (rc == MQTTCLIENT_SUCCESS) { printf("Waiting for message to be published...\n"); rc = MQTTClient_waitForCompletion(client, dt, 1000); if (rc == MQTTCLIENT_SUCCESS) { printf("Message published\n"); } else { std::cerr << "Failed to publish message with token " << dt << std::endl; } } else { std::cerr << "Failed to publish message with token " << dt << std::endl; } // reset dummy data if (dummyData == DUMMY_MAX_VALUE) { dummyData = 1; } else { dummyData++; } mraa_pwm_write(pino_atuador,result); sleep(1); } printf("Stopping\n"); int timeout = 100; MQTTClient_disconnect(client, timeout); MQTTClient_destroy(&client); return mraa::SUCCESS; }