

sub 3> mosquitto_sub –h localhost –t edison/hello  pub 3> mosquitto_pub –h localhost –t edison/hello –m "Message#1: Hello World!"  Temperature/Building1/Room1/Location1 Temperature/Building1/Room1/Location2 Temperature/Building2/Room2 Temperature/Outdoor/West Temperature/Outdoor/East Temperature/Average  port 1883 password_file /home/mosquitto/conf/pwdfile.txt log_type debug log_type error log_type warning log_type information log_type notice user root pid_file /home/mosquitto/logs/mosquitto.pid persistence true persistence_location /home/mosquitto/db/ log_dest file /home/mosquitto/logs/mosquitto.log listener 1995 #  1995    TLS-PSK,     #  --psk-identity  --psk psk_file /home/mosquitto/conf/pskfile.txt #   psk_hint,   1995     psk_hint hint listener 1994 #  1994   SSL-,     #  ,   , #   , , ca.crt cafile /home/mosquitto/certs/ca.crt certfile /home/mosquitto/certs/server.crt keyfile /home/mosquitto/certs/server.key  /*    Mosquitto */ user:$6$Su4WZkkQ0LmqeD/X$Q57AYfcu27McE14/MojWgto7fmloRyrZ7BpTtKOkME8UZzJZ5hGXpOea81RlgcXttJbeRFY9s0f+UTY2dO5xdg== /*  PSK- Mosquitto */ user1:deadbeef user2:DEADBEEF0123456789ABCDEF0123456789abcdef0123456789abcdef0123456789abcdef <h1> MQTT   </h1>  // : MQTTClient.h /*  MQTT-,  mosquitto_sub  mosquitto_pub   ,   Mosquitto MQTT   mosquitto_pub/sub      */ #ifndef __MQTTClient_H__ #define __MQTTClient_H__ #include <Arduino.h> #include <stdio.h> enum security_mode {OPEN = 0, SSL = 1, PSK = 2}; class MQTTClient { public:   MQTTClient();   ~MQTTClient();   void    begin(char * broker, int port, security_mode mode,                 char* certificate_file, char *psk_identity, char *psk);   boolean publish(char *topic, char *message);   boolean subscribe(char* topic, void (*callback)(char *topic, char* message));   boolean loop();   boolean available();   void    close(); private:   void           parseDataBuffer();   FILE*          spipe;   char           mqtt_broker[32];   security_mode  mode;   char           topicString[64];   char           certificate_file[64];   char           psk_identity[32];   char           psk_password[32];   int            serverPort;   char           *topic;   char           *message;   boolean         retain_flag;   void           (*callback_function)(char* topic, char* message);   char           dataBuffer[256]; }; #endif  #include <MQTTClient.h> #define SAMPLING_PERIOD   100 #define PUBLISH_INTERVAL  30000 MQTTClient mqttClient; void setup() {  mqttClient.begin("localhost",1833,PSK,NULL,"psk_user","psk_password");  mqttClient.subscribe("edison/#",myCallBack); } void myCallBack(char* topic, char* message) {  //    , ,   } unsigned long publishTime = millis(); void loop() {  mqttClient.loop();        //       if (millis() > publishTime) {      publishTime = millis() + PUBLISH_INTERVAL;      mqttClient.publish("edison/sensor1","sensor1value");      mqttClient.publish("edison/sensor2","sensor2value");  }  delay(SAMPLING_PERIOD); }  // : MQTTClient.cpp #include "MQTTClient.h" #include <fcntl.h> /*====================================================================== / ========================================================================*/ MQTTClient::MQTTClient() { } MQTTClient::~MQTTClient() { close(); } void MQTTClient::close() { if (spipe) {   fclose(spipe); } } /*======================================================================== .             ==========================================================================*/ void MQTTClient::begin(char *broker, int port, security_mode smode,                      char* cafile, char *user, char *psk) { strcpy(mqtt_broker, broker); serverPort = port; mode = smode; if (mode == SSL) {   strcpy(certificate_file, cafile); } else if (mode == PSK) {   strcpy(psk_identity, user);   strcpy(psk_password, psk); } Serial.println("MQTTClient initialized"); Serial.print("Broker: "); Serial.println(mqtt_broker); Serial.print("Port:   "); Serial.println(serverPort); Serial.print("Mode:   "); Serial.println(mode); } /*=======================================================================   , (*callback)  ,   ,    . =========================================================================*/ boolean MQTTClient::subscribe(char* topic,                             void (*callback)(char* topic, char* message)) { char cmdString[256]; if (mqtt_broker == NULL) {   return false; } if (topic == NULL) {   return false; } callback_function = callback; switch(mode) {   case OPEN:     sprintf(cmdString,             "mosquitto_sub -h %s -p %d -t %s -v",             mqtt_broker, serverPort, topic);     break;   case SSL:     sprintf(cmdString,             "mosquitto_sub -h %s -p %d -t %s -v --cafile %s",              mqtt_broker, serverPort, topic, certificate_file);     break;   case PSK:     sprintf(cmdString,             "mosquitto_sub -h %s -p %d -t %s -v --psk-identity %s --psk %s",             mqtt_broker, serverPort, topic, psk_identity, psk_password);     break;   default:     break; } if ((spipe = (FILE*)popen(cmdString, "r")) != NULL) {   //         int fd    = fileno(spipe);   int flags = fcntl(fd, F_GETFL, 0);   flags |= O_NONBLOCK;   fcntl(fd, F_SETFL, flags);   strcpy(topicString, topic);   return true; } else {   return false; } } /*==================================================================== ,     ,  ,         .  ,   . ======================================================================*/ boolean MQTTClient::loop() { if (fgets(dataBuffer, sizeof(dataBuffer), spipe)) {      parseDataBuffer();      callback_function(topic, message); } } /*====================================================================     . ======================================================================*/ boolean MQTTClient::publish(char *topic, char *message) { FILE*   ppipe; char    cmdString[256]; boolean retval = false; if (this->mqtt_broker == NULL) {   return false; } if (topic == NULL) {   return false; } switch (this->mode) {   case OPEN:     sprintf(cmdString,             "mosquitto_pub -h %s -p %d -t %s -m \"%s\" %s",             mqtt_broker, serverPort, topic, message, retain_flag?"-r":"");     break;   case SSL:     sprintf(cmdString,             "mosquitto_pub -h %s -p %d --cafile %s -t %s -m \"%s\" %s",              mqtt_broker, serverPort, certificate_file,              topic, message, retain_flag?"-r":"");     break;   case PSK:     sprintf(cmdString,         "mosquitto_pub -h %s -p %d --psk-identity %s --psk %s -t %s -m \"%s\" %s",             mqtt_broker, serverPort, psk_identity, psk_password,             topic, message, retain_flag?"-r":"");     break; } if (!(ppipe = (FILE *)popen(cmdString, "w"))) {   retval = false; } if (fputs(cmdString, ppipe) != EOF) {   retval = true; } else {   retval = false; } fclose(ppipe); return retval; } /*======================================================================    ,        .    .         , ,         NULL ========================================================================*/ void MQTTClient::parseDataBuffer() { topic   = dataBuffer; message = dataBuffer; while((*message) != 0) {   if ((*message) == 0x20) {     //     NULL     (*message) = 0;     message++;     break;   }   else {     message++;   } } if (strlen(message) == 0) {   topic   = NULL;   message = dataBuffer; } } <h2> </h2> 
 // : MQTT_IoT_Sensor.ino /******************************************************************************       ,    Intel Edison ******************************************************************************/ #include <stdio.h> #include <Arduino.h> #include "sensors.h" #include "MQTTClient.h" //   unsigned long          updateTime = 0; //    volatile unsigned long activityMeasure; volatile unsigned long activityStart; volatile boolean       motionLED = true; unsigned long          resetActivityCounterTime; //   boolean                toggleLED = false; volatile unsigned long previousEdgeTime = 0; volatile unsigned long count = 0; volatile boolean       arm_alarm = false; // MQTT- #define SECURE_MODE     2 MQTTClient              mqttClient; char                    fmtString[256];     //   char                    topicString[64];    //    char                    msgString[64];      //  /*****************************************************************************  ******************************************************************************/ void setup() { Serial.begin(115200); delay(3000); Serial.println("Ready"); pinMode(RED_LED,    OUTPUT); pinMode(GREEN_LED,  OUTPUT); pinMode(BUTTON,     INPUT_PULLUP); pinMode(PIR_SENSOR, INPUT); //  .      attachInterrupt(BUTTON,     buttonISR, RISING);  //   .        attachInterrupt(PIR_SENSOR, pirISR,    CHANGE); digitalWrite(RED_LED,  HIGH); digitalWrite(GREEN_LED,LOW); resetActivityCounterTime = 0; //  MQTTClient #if ( SECURE_MODE == 0 ) Serial.println("No security"); mqttClient.begin("localhost", 1883, OPEN, NULL, NULL, NULL); #elif ( SECURE_MODE == 1 ) Serial.println("SSL security"); mqttClient.begin("localhost", 1994, SSL,                  "/home/mosquitto/certs/ca.crt", NULL, NULL); #elif ( SECURE_MODE == 2 ) Serial.println("TLS-PSK security"); mqttClient.begin("localhost", 1995, PSK, NULL, "user", "deadbeef"); #endif //      edison mqttClient.subscribe("edison/#", mqttCallback); mqttClient.publish("edison/bootMsg","Booted"); digitalWrite(RED_LED, LOW); } /**************************************************************************    MQTT **************************************************************************/ void mqttCallback(char* topic, char* message) { sprintf(fmtString, "mqttCallback(), topic: %s, message: %s",topic,message); Serial.print(fmtString); //   if (strcmp(topic,"edison/LED") == 0) {   //       if (message[0] == 'H') {     digitalWrite(RED_LED, HIGH);     toggleLED = false;   }   else if (message[0] == 'L') {     digitalWrite(RED_LED, LOW);     toggleLED = false;   }   else if (message[0] == 'B') {     toggleLED = true;   } } if (strcmp(topic, "edison/motionLED") == 0) {   //    ,         //   .   //  strncmp  ,       if (strncmp(message, "OFF", 3) == 0) {     digitalWrite(GREEN_LED, LOW);     motionLED = false;   }   else if (strncmp(message, "ON", 2) == 0) {     motionLED = true;   } } } /***********************************************************************   ***********************************************************************/ void loop() {   // ,      mqtt_sub   mqttClient.loop();     if (millis() > resetActivityCounterTime) {     resetActivityCounterTime = millis() + 60000;     //    ,        sprintf(msgString,"%.0f",100.0*activityMeasure/60000.0);     mqttClient.publish("edison/ActivityLevel",msgString);     activityMeasure = 0;   }   if (millis() > updateTime) {     updateTime = millis() + 10000;        //         sprintf(msgString,"%.1f",readTemperature(TEMP_SENSOR));     mqttClient.publish("edison/Temperature",msgString);         //         sprintf(msgString,"%d",readLightSensor(LIGHT_SENSOR));     mqttClient.publish("edison/LightSensor",msgString);         //  arm_alarm     sprintf(msgString,"%s", (arm_alarm == true)? "ARMED"  : "NOTARMED");     mqttClient.publish("edison/alarm_status", msgString);   }     if (toggleLED == true) {     digitalWrite(RED_LED, digitalRead(RED_LED) ^ 1);   }   delay(100); }  // : sensors.h // #define USE_TMP036     0 #define RED_LED       10            //   #define GREEN_LED     11            //   #define BUTTON        13            //       10K #define PIR_SENSOR    12            //    #define LIGHT_SENSOR  A0            //   #define TEMP_SENSOR   A1            //   TMP36  LM35 #define MIN_PULSE_SEPARATION     200   //     #define ADC_STEPSIZE             4.61  //  ,     . #if (USE_TMP036 == 1) #define TEMP_SENSOR_OFFSET_VOLTAGE       750 #define TEMP_SENSOR_OFFSET_TEMPERATURE   25 #else // LM35 temperature sensor #define TEMP_SENSOR_OFFSET_VOLTAGE        0 #define TEMP_SENSOR_OFFSET_TEMPERATURE    0 #endif //   extern unsigned long          updateTime; //    extern volatile unsigned long activityMeasure; extern volatile unsigned long activityStart; extern volatile boolean       motionLED; extern unsigned long          resetActivityCounterTime; //   extern boolean                toggleLED; extern volatile unsigned long previousEdgeTime; extern volatile unsigned long count; extern volatile boolean       arm_alarm; float readTemperature(int analogPin); int   readLightSensor(int analogPin); void  buttonISR(); void  pirISR(); // : sensors.cpp #include <Arduino.h> #include "sensors.h" /***********************************************************************************    ,    ,     HIGH      ,   .   ,     HIGH  2-3 ,     LOW.        HIGH,       .               ************************************************************************************/ void pirISR() { int pirReading; unsigned long timestamp; timestamp = millis(); pirReading = digitalRead(PIR_SENSOR); if (pirReading == 1) {   //      activityStart = timestamp; } else {   int pulseWidth = timestamp-activityStart;   activityMeasure += pulseWidth; } //   ,    if (motionLED == true) {   digitalWrite(GREEN_LED, pirReading); } } /************************************************************************     ************************************************************************/ int readLightSensor(int sensorPin) { return analogRead(sensorPin); } /***********************************************************************        ***********************************************************************/ float readTemperature(int sensorPin) { int   sensorReading; float temperature; sensorReading = analogRead(sensorPin); //    temperature = sensorReading * ADC_STEPSIZE; //   LM35,  TMP036,   : // 10     //    LM35 – 0 ,  TMP036 - 750  //    LM35 – 0  ,  TMP036 – 25 . temperature = (temperature - TEMP_SENSOR_OFFSET_VOLTAGE)/10.0 +                TEMP_SENSOR_OFFSET_TEMPERATURE; //     temperature = temperature * 1.8 + 32.0;        return temperature; } /*************************************************************************     **************************************************************************/ void buttonISR() { //        ,    if ((millis()-previousEdgeTime) >= MIN_PULSE_SEPARATION) {   arm_alarm = !arm_alarm;   Serial.print("Alarm is: ");   if (arm_alarm == true) {     Serial.println("ARMED");   }   else {     Serial.println("NOT ARMED");   }   count++;   Serial.print("Count: "); Serial.println(count); } previousEdgeTime=millis(); }  $> mosquitto_sub –h ipaddr –p 1883 –t edison/# -v  $> mosquitto_pub –h ipaddr –p 1883 –t Edison/LED –m {H, L, B} $> mosquitto_pub –h ipaddr –p 1883 –t Edison/motionLED –m {ON, OFF} Source: https://habr.com/ru/post/283440/
All Articles