Announcement

Collapse
No announcement yet.

Project weekend: Using MQTT with HS3

Collapse
X
 
  • Filter
  • Time
  • Show
Clear All
new posts

    #16
    Here's the Arduino Yun sketch I am using for the driveway sensors connected to the Dakota Wireless unit:

    Note I have not yet added the web server like I did above, but wouldn't be too hard to modify.

    Code:
    /***************************************************
      Adafruit MQTT Library Arduino Yun Example
    
      Make sure your Arduino Yun is connected to a WiFi access point which
      has internet access.  Also note this sketch uses the Console class
      for debug output so make sure to connect to the Yun over WiFi and
      open the serial monitor to see the console output.
    
      Works great with the Arduino Yun:
      ----> https://www.adafruit.com/products/1498
    
      Adafruit invests time and resources providing this open source code,
      please support Adafruit and open-source hardware by purchasing
      products from Adafruit!
    
      Written by Tony DiCola for Adafruit Industries.
      MIT license, all text above must be included in any redistribution
     ****************************************************/
    #include <Bridge.h>
    #include <Console.h>
    #include <YunClient.h>
    #include "Adafruit_MQTT.h"
    #include "Adafruit_MQTT_Client.h"
    
    
    /************************* Adafruit.io Setup *********************************/
    
    #define AIO_SERVER      "MQTT_SERVER_REPLACE"
    #define AIO_SERVERPORT  1883
    #define AIO_USERNAME    "optional_username_replace"
    #define AIO_KEY         "optional_password_replace"
    #define AIO_FEEDNAME    "/raw/arduino01/driveway"
    
    /************ Global State (you don't need to change this!) ******************/
    
    // Create a YunClient instance to communicate using the Yun's brighe & Linux OS.
    YunClient client;
    
    // Store the MQTT server, username, and password in flash memory.
    // This is required for using the Adafruit MQTT library.
    const char MQTT_SERVER[] PROGMEM    = AIO_SERVER;
    const char MQTT_USERNAME[] PROGMEM  = AIO_USERNAME;
    const char MQTT_PASSWORD[] PROGMEM  = AIO_KEY;
    const char MQTT_FEEDNAME[] PROGMEM  = AIO_FEEDNAME;
    
    
    // Setup the MQTT client class by passing in the WiFi client and MQTT server and login details.
    Adafruit_MQTT_Client mqtt(&client, MQTT_SERVER, AIO_SERVERPORT, MQTT_USERNAME, MQTT_PASSWORD);
    
    /****************************** Feeds ***************************************/
    
    const char VEHICLESENSOR_FEED[] PROGMEM = AIO_FEEDNAME "/vehicle";
    const char MOTIONSENSOR_FEED[] PROGMEM = AIO_FEEDNAME "/motion";
    const char MAILBOXSENSOR_FEED[] PROGMEM = AIO_FEEDNAME "/mailbox";
    
    // Adafruit_MQTT_Publish photocell = Adafruit_MQTT_Publish(&mqtt, PHOTOCELL_FEED);
    
    Adafruit_MQTT_Publish vehicleSensor = Adafruit_MQTT_Publish(&mqtt, VEHICLESENSOR_FEED);
    Adafruit_MQTT_Publish motionSensor = Adafruit_MQTT_Publish(&mqtt, MOTIONSENSOR_FEED);
    Adafruit_MQTT_Publish mailboxSensor = Adafruit_MQTT_Publish(&mqtt, MAILBOXSENSOR_FEED);
    
    
    // Setup a feed called 'onoff' for subscribing to changes.
    // const char ONOFF_FEED[] PROGMEM = AIO_USERNAME "/feeds/onoff";
    
    // Adafruit_MQTT_Subscribe onoffbutton = Adafruit_MQTT_Subscribe(&mqtt, ONOFF_FEED);
    
    /*************************** Digital Input Pins *****************************/
    int VehicleSensor_Pin = 8;
    int MotionSensor_Pin = 9;
    int MailboxSensor_Pin = 10;
    
    /*************************** Sketch Code ************************************/
    
    void setup() {
      Bridge.begin();
      Console.begin();
      Console.println(F("MQTT Server"));
    
      pinMode(VehicleSensor_Pin, INPUT);
      pinMode(MotionSensor_Pin, INPUT);
      pinMode(MailboxSensor_Pin, INPUT);
    
      digitalWrite(VehicleSensor_Pin, LOW);   
      digitalWrite(MotionSensor_Pin, LOW);   
      digitalWrite(MailboxSensor_Pin, LOW);   
      // Setup MQTT subscription for onoff feed.
      // mqtt.subscribe(&onoffbutton);
    }
    
    // uint32_t x=0;
    
    uint32_t vehicleSensorSet = 0;
    uint32_t motionSensorSet = 0;
    uint32_t mailboxSensorSet = 0;
    
    void loop() {
      // Ensure the connection to the MQTT server is alive (this will make the first
      // connection and automatically reconnect when disconnected).  See the MQTT_connect
      // function definition further below.
      MQTT_connect();
    
     if (digitalRead(VehicleSensor_Pin) == HIGH && vehicleSensorSet == 0) 
     {
       Serial.println ("Vehicle Sensor Trigged");
       vehicleSensorSet = 1;
      if (! vehicleSensor.publish("1")) 
      {
        Console.println(F("Failed"));
      } else 
      {
        Console.println(F("OK!"));
      }
     }
     
    if (digitalRead(VehicleSensor_Pin) == LOW && vehicleSensorSet == 1) 
     {
      vehicleSensorSet = 0;
      if (! vehicleSensor.publish("0")) 
      {
        Console.println(F("Failed"));
      } else 
      {
        Console.println(F("OK!"));
      }
     }
     
     
     if (digitalRead(MotionSensor_Pin) == HIGH && motionSensorSet == 0) 
     {
       Serial.println ("Motion Sensor Trigged");
       motionSensorSet = 1;
      if (! motionSensor.publish("1")) 
      {
        Console.println(F("Failed"));
      } else 
      {
        Console.println(F("OK!"));
      }
     }
    
     if (digitalRead(MotionSensor_Pin) == LOW && motionSensorSet == 1) 
     {
       motionSensorSet = 0;
      if (! motionSensor.publish("0")) 
      {
        Console.println(F("Failed"));
      } else 
      {
        Console.println(F("OK!"));
      }
     }
    
    
     
      if (digitalRead(MailboxSensor_Pin) == HIGH && mailboxSensorSet == 0) 
     {
       Serial.println ("Mailbox Sensor Trigged");
       mailboxSensorSet = 1;
      if (! mailboxSensor.publish("1")) 
      {
        Console.println(F("Failed"));
      } else 
      {
        Console.println(F("OK!"));
      }
     }
     
     if (digitalRead(MailboxSensor_Pin) == LOW && mailboxSensorSet == 1) 
     {
      mailboxSensorSet = 0;
      if (! mailboxSensor.publish("0")) 
      {
        Console.println(F("Failed"));
      } else 
      {
        Console.println(F("OK!"));
      }
     }
    
    
      // ping the server to keep the mqtt connection alive
      if(! mqtt.ping()) {
        Console.println(F("MQTT Ping failed."));
      }
    
      delay(200);
    
    }
    
    // Function to connect and reconnect as necessary to the MQTT server.
    // Should be called in the loop function and it will take care if connecting.
    void MQTT_connect() {
      int8_t ret;
    
      // Stop if already connected.
      if (mqtt.connected()) {
        return;
      }
    
      Console.print("Connecting to MQTT server" + String(AIO_SERVER) + " on port " + String(AIO_SERVERPORT) + "... ");
    
      while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
           Console.println(mqtt.connectErrorString(ret));
           Console.println("Retrying MQTT connection in 5 seconds...");
           mqtt.disconnect();
           delay(5000);  // wait 5 seconds
      }
      Console.println("MQTT Connected!");
    
      
    }

    Comment


      #17
      Found an Arduino Yun mount on Thingaverse, and modified ito so it can be mounted in a Leviton SMC enclosure... not the best print, but works:



      Part can be downloaded here: http://www.thingiverse.com/thing:1533513

      Comment


        #18
        So I officially put the Arduino Yun in place and wired up to my driveway sensor in the basement. For some reason the PoE module wasn't happy with the switch in the basement, so running USB powered for now until I debug that. However nice to get this out of the way and mounted:


        Quick test of the driveway sensors and the mailbox and motion sensing inputs are working. Guess I'll find out tomorrow how the vehicle sensor works when I drive out to work

        Comment


          #19
          Nice! How far was the yun from power source using the poe?


          Sent from my iPhone
          Tom
          baby steps...starting again with HS3
          HS3Pro: Z-NET & 80 Z wave Devices,
          HSTouch: 4 Joggler (Android Kitkat), 2 iPhone, 3 iPads
          Whole House Audio: 5 SqueezePlay Jogglers w Bose Speakers
          In The Works: 10 Cameras Geovision, new Adecmo/Envisalink Alarm, Arduinos
          System: XP on Fanless Mini-ITX w/ SSD

          Comment


            #20
            Originally posted by TomTom View Post
            Nice! How far was the yun from power source using the poe?


            Sent from my iPhone
            Not far at all... maybe 12" Was trying a really short cable to see (maybe also part of the problem). TBH I really don't need PoE in the SMC as have a power strip in there. It tested fine upstairs in my office on a different switch and a different PoE injector so a few different variables here.

            Comment


              #21
              That is strange.
              Where did you get that Screw Shield for the Yun. I think I was one for Seedstudio like that.
              Tom
              baby steps...starting again with HS3
              HS3Pro: Z-NET & 80 Z wave Devices,
              HSTouch: 4 Joggler (Android Kitkat), 2 iPhone, 3 iPads
              Whole House Audio: 5 SqueezePlay Jogglers w Bose Speakers
              In The Works: 10 Cameras Geovision, new Adecmo/Envisalink Alarm, Arduinos
              System: XP on Fanless Mini-ITX w/ SSD

              Comment


                #22
                Originally posted by TomTom View Post
                That is strange.
                Where did you get that Screw Shield for the Yun. I think I was one for Seedstudio like that.
                Amazon, they work OK: http://www.amazon.com/Gikfun-Shield-...rch_detailpage

                Comment


                  #23
                  Found out the Yun allows you to bridge commands to the linux side, so can leverage it's clock info for running a web server on the Arduino side:
                  Code:
                  Driveway Sensors
                  
                  Mailbox Sensor: Unknown
                  Vehicle Sensor: Tue May  3 06:56:24 2016
                  Motion Sensor: Tue May  3 06:56:19 2016
                  Resets on a reboot but no big deal as really just for diagnostics.

                  Comment


                    #24
                    Mike,

                    So I started testing with the DHT22 and NodeMCU a yesterday, but I can't get beyond this error. I'm sure it is something basic, but all the reading online hasn't seemed to help.

                    I opened up Adruino IDE

                    Then Tools > Board > Board Manager > Install ESP8266

                    Then Tools > Board > Chose Generic ESP8266 Module

                    Upload Sketch You have below and I get the following error:

                    Sketch uses 234,917 bytes (54%) of program storage space. Maximum is 434,160 bytes.
                    Global variables use 33,176 bytes (40%) of dynamic memory, leaving 48,744 bytes for local variables. Maximum is 81,920 bytes.
                    error: failed reading byte
                    warning: espcomm_send_command: cant receive slip payload data
                    error: failed reading byte
                    warning: espcomm_send_command: cant receive slip payload data
                    error: failed reading byte
                    warning: espcomm_send_command: cant receive slip payload data
                    warning: espcomm_sync failed
                    error: espcomm_open failed
                    error: espcomm_upload_mem failed

                    Any thoughts?






                    Originally posted by mloebl View Post
                    Here's the sample ESP8266/NodeMCU Arduino sketch I am using:

                    Code:
                    /***************************************************
                      Adafruit MQTT Library Arduino Yun Example
                    
                      Make sure your Arduino Yun is connected to a WiFi access point which
                      has internet access.  Also note this sketch uses the Console class
                      for debug output so make sure to connect to the Yun over WiFi and
                      open the serial monitor to see the console output.
                    
                      Works great with the Arduino Yun:
                      ----> https://www.adafruit.com/products/1498
                    
                      Adafruit invests time and resources providing this open source code,
                      please support Adafruit and open-source hardware by purchasing
                      products from Adafruit!
                    
                      Written by Tony DiCola for Adafruit Industries.
                      MIT license, all text above must be included in any redistribution
                    
                     **************************************************
                     
                     Adapted for the ESP8266 Boards
                     
                     This is also using the Adafruit DHT libraries which can be downloaded
                      from GitHub:
                      https://github.com/adafruit/DHT-sensor-library
                    
                     ****************************************************/
                    
                    #include <ESP8266WiFi.h>
                    #include "Adafruit_MQTT.h"
                    #include "Adafruit_MQTT_Client.h"
                    #include "DHT.h"
                    
                    /************************* Adafruit.io Setup *********************************/
                    
                    #define AIO_SERVER      "MQTT_SERVER_REPLACE"
                    #define AIO_SERVERPORT  1883
                    #define AIO_USERNAME    "optional_username_replace"
                    #define AIO_KEY         "optional_password_replace"
                    #define AIO_FEEDNAME    "/raw/nodemcu"  # Change this to what you may want to use
                    
                    /************ Global State (you don't need to change this!) ******************/
                    
                     #define DHTPIN 4     // NodeMCU
                    // #define DHTPIN 2     // ESP8266
                    #define DHTTYPE DHT22   // DHT 22  (AM2302), AM2321
                    
                    DHT dht(DHTPIN, DHTTYPE);
                    ADC_MODE(ADC_VCC);
                    
                    WiFiClient client;
                    WiFiServer server(80);
                    
                    // Store the MQTT server, username, and password in flash memory.
                    // This is required for using the Adafruit MQTT library.
                    const char MQTT_SERVER[] PROGMEM    = AIO_SERVER;
                    const char MQTT_USERNAME[] PROGMEM  = AIO_USERNAME;
                    const char MQTT_PASSWORD[] PROGMEM  = AIO_KEY;
                    const char MQTT_FEEDNAME[] PROGMEM  = AIO_FEEDNAME;
                    
                    const char* ssid     = "ssid_replace";
                    const char* password = "password_replace";
                    Tom
                    baby steps...starting again with HS3
                    HS3Pro: Z-NET & 80 Z wave Devices,
                    HSTouch: 4 Joggler (Android Kitkat), 2 iPhone, 3 iPads
                    Whole House Audio: 5 SqueezePlay Jogglers w Bose Speakers
                    In The Works: 10 Cameras Geovision, new Adecmo/Envisalink Alarm, Arduinos
                    System: XP on Fanless Mini-ITX w/ SSD

                    Comment


                      #25
                      That means it's having issues flashing the board. Trying hitting Upload button inside Arduino IDE, JUST when you see the LED blink when it starts uploading, hold the flash button on the NodeMCU for a moment and let go. May need to try that a couple of times and play with the timing a bit. I just went thru this with some ESP-01 modules as well; I bought one of these to make it a ton easier to program them:
                      http://www.amazon.com/AprilBeacon-Fl.../dp/B01E8O30IC

                      Originally posted by TomTom View Post
                      Mike,

                      So I started testing with the DHT22 and NodeMCU a yesterday, but I can't get beyond this error. I'm sure it is something basic, but all the reading online hasn't seemed to help.

                      Comment


                        #26
                        So that was it. Nice trick!. I had searched about 10 different sites and each one had a different gimmick to try, and none worked. Now I can see the nodemcu on my network as Epress.

                        So my HS3 MQTT plugin shows it is connected. And I went to Suscriptions Page > Manual Add MQTT Suscription > /raw/nodemcu (?)

                        I don't see anydata in HS3?
                        Tom
                        baby steps...starting again with HS3
                        HS3Pro: Z-NET & 80 Z wave Devices,
                        HSTouch: 4 Joggler (Android Kitkat), 2 iPhone, 3 iPads
                        Whole House Audio: 5 SqueezePlay Jogglers w Bose Speakers
                        In The Works: 10 Cameras Geovision, new Adecmo/Envisalink Alarm, Arduinos
                        System: XP on Fanless Mini-ITX w/ SSD

                        Comment


                          #27
                          Originally posted by TomTom View Post
                          So that was it. Nice trick!. I had searched about 10 different sites and each one had a different gimmick to try, and none worked. Now I can see the nodemcu on my network as Epress.

                          So my HS3 MQTT plugin shows it is connected. And I went to Suscriptions Page > Manual Add MQTT Suscription > /raw/nodemcu (?)

                          I don't see anydata in HS3?
                          On your MQTT server, run the following command:
                          Code:
                          mosquitto_sub -t \# -v
                          That will show ALL traffic it can hear. Then you should see a /raw/nodemcu message with the rest of the path you want.

                          Comment


                            #28
                            Ran that command on MQTT server and didn't get anything.
                            I'm wondering if I input everything in the sketch correctly.
                            This is what I have. These are the only ones I changed.

                            #define AIO_SERVER "192.168.1.130"
                            #define AIO_SERVERPORT 1883
                            #define AIO_USERNAME ""
                            #define AIO_KEY ""
                            #define AIO_FEEDNAME "/raw/nodemcu"


                            const char* ssid = "MyWifi";
                            const char* password = "Password";
                            Tom
                            baby steps...starting again with HS3
                            HS3Pro: Z-NET & 80 Z wave Devices,
                            HSTouch: 4 Joggler (Android Kitkat), 2 iPhone, 3 iPads
                            Whole House Audio: 5 SqueezePlay Jogglers w Bose Speakers
                            In The Works: 10 Cameras Geovision, new Adecmo/Envisalink Alarm, Arduinos
                            System: XP on Fanless Mini-ITX w/ SSD

                            Comment


                              #29
                              Try to do this:
                              Code:
                               tail -f /var/log/mosquitto/mosquitto.log
                              Then bounce the nodemcu to see if you see a connection in the log.

                              Also you can connect via USB serial debugging in Arduino ide if you are writing debug serial data in your sketch so you can watch there too.

                              Comment


                                #30
                                Ok, got something. last line say socket error.
                                10.0.1.14 is the NodeMCU

                                -----------------------------------------------
                                1463622929: New client connected from 127.0.0.1 as mosqsub/25117-MQTT (c1, k60).
                                1463622959: Socket error on client mosqsub/25117-MQTT, disconnecting.
                                1463623007: New connection from 127.0.0.1 on port 1883.
                                1463623007: New client connected from 127.0.0.1 as mosqsub/25229-MQTT (c1, k60).
                                1463623815: Socket error on client mosqsub/25229-MQTT, disconnecting.
                                1463623862: New connection from 127.0.0.1 on port 1883.
                                1463623862: New client connected from 127.0.0.1 as mosqsub/25694-MQTT (c1, k60).
                                1463624091: Socket error on client mosqsub/25694-MQTT, disconnecting.
                                1463624175: Saving in-memory database to /var/lib/mosquitto/mosquitto.db.
                                1463624218: New connection from 10.0.1.14 on port 1883.
                                1463624218: New client connected from 10.0.1.14 as bd0c0644-cc84-4546-b5ac-80319935b252 (c1, k300).
                                1463624230: Socket error on client 3f2e2304-c0f0-4485-9d3b-efa8445cf2f6, disconnecting.
                                Tom
                                baby steps...starting again with HS3
                                HS3Pro: Z-NET & 80 Z wave Devices,
                                HSTouch: 4 Joggler (Android Kitkat), 2 iPhone, 3 iPads
                                Whole House Audio: 5 SqueezePlay Jogglers w Bose Speakers
                                In The Works: 10 Cameras Geovision, new Adecmo/Envisalink Alarm, Arduinos
                                System: XP on Fanless Mini-ITX w/ SSD

                                Comment

                                Working...
                                X