Esempio n. 1
0
void MQclient::reconn(PubSubClient& client) {
  Serial.print("Attempting remo MQTT connection...");
  if (client.connect(cdevid)) {
    Serial.println("connected");
    for (int i=0;i<la.numcmds;i++){
      char topic[25];
      strcpy(topic, cdevid);
      strcat(topic,"/"); 
      strcat(topic,la.scribedTo[i]);
      client.subscribe(topic);
      //Serial.println(topic);     
    }
    // delay(5000);
    char* dd = "the time is being requesrd";
    Serial.println(dd);
    char time[20];
    strcpy(time,cdevid);
    strcat(time,"/time");  
    client.publish(time, dd, true);    
    return;
  } else {
    Serial.print("failed, rc=");
    Serial.print(client.state());
    delay(5000);
    Serial.println(" try again in 5 seconds");
  }
}
Esempio n. 2
0
extern "C" void loop() {
	Actor::eventLoop();
	if (WiFi.status() != WL_CONNECTED) {
		Serial.print("Connecting to ");
		Serial.print(WIFI_SSID);
		Serial.println("...");
		WiFi.begin(WIFI_SSID, WIFI_PSWD);

		if (WiFi.waitForConnectResult() != WL_CONNECTED) {
			LOGF(" still connecting ");
			return;
		}
		LOGF("WiFi connected");
	}

	if (WiFi.status() == WL_CONNECTED) {
//	if (wifi.connected()) {
		if (!client.connected()) {
			mdns.onWifiConnected(Header(INIT));
			IPAddress server = mdns.query("mqtt");
			client.set_server(server,1883);
			if (client.connect("wibo1", prefix + "system/alive", 1, 0,
					"false")) {
				client.publish(prefix + "system/alive", "true");
				client.set_callback(callback);
				client.subscribe(subscribe_topic);
				Log.setOutput(udpLog);
				LOGF(" mqtt client connected ");
			} else {
				LOGF(" mqtt connect failed ")
			}
		}
		if (client.connected())
			client.loop();
	}
Esempio n. 3
0
void loop() {
  ArduinoOTA.handle();

  // -- MQTT connect
    if (!client.connected()) {
      error_path += thisDevicePath;
      error_path += "/";
      error_path += "errors/";
      error_path += thisDeviceName;
      if (client.connect(MQTT::Connect(thisDeviceName).set_will(error_path, "disconnected"))) {
        Serial.println("MQTT connected");
        client.set_callback(callback);
        client.subscribe(MQTT::Subscribe()
          .add_topic("/deviceInfo/#")
          .add_topic("/global/#")
          .add_topic(subscribe_path)
                 );
        // notify persistence of device IP
          String persistence_ip_path = "/persistence/control/";
          persistence_ip_path += thisDeviceName;
          persistence_ip_path += "/ip";
          client.publish(MQTT::Publish(persistence_ip_path, local_ip_str).set_qos(2));

        // ask persistence/control/device_name/chipID "request states" --  do you have any states with my device_name or chipID
          String persistence_path = "/persistence/control/";
          persistence_path += thisDeviceName;
          persistence_path += "/";
          persistence_path += chip_id;
          client.publish(MQTT::Publish(persistence_path, "request states").set_qos(2));
          Serial.println("request states sent");
      }
    }

    if (client.connected()) {
      client.loop();
    }


  // -- NeoPixel continuous update
    for(int i=0; i<PixelCount; i++) {
      strip.SetPixelColor(i, RgbColor (redValue, greenValue, blueValue));
    }
    strip.Show();


  yield();
}
Esempio n. 4
0
mqtt_result PubSub::publish(const char *message) {
  if(_publishChannel != NULL && _publishChannel != "") {
    if(client.publish(_publishChannel, message)) {
      return E_MQTT_OK;
    } else {
      return E_MQTT_PUBLISH;
    }
  } else {
    return E_MQTT_NO_PUBLISH_CHANNEL;
  }
}
Esempio n. 5
0
void gpioPublish(int pin, PubSubClient &client, const String& topic)
{
  static int currentState = 0;
  int p = digitalRead(pin) == HIGH ? 1 : 0;
  if (p != currentState)
  {
    String publish = String(p);
    client.publish(topic.c_str(), publish.c_str());
    currentState = p;
  }
}
Esempio n. 6
0
void callback(const MQTT::Publish& pub) {
	if (pub.topic().endsWith("request")) {
		String sRequest = pub.payload_string();
		StaticJsonBuffer<1000> request;
		JsonObject& req = request.parseObject(sRequest);
		StaticJsonBuffer<1000> reply;
		JsonObject& repl = reply.createObject();
		handle(repl, req);
		if (!req.success()) {
			LOGF(" UDP message JSON parsing fails");
			client.publish("system/log", " UDP message JSON parsing fails");
			return;
		} else {
			handle(repl, req);
			String str;
			repl.printTo(str);
			client.publish(prefix + "bootloader/reply", str);
		}
	} else {
		LOGF(" unknown request %s", pub.payload_string().c_str());
	}
}
Esempio n. 7
0
void udpLog(char* str, uint32_t length) {
	if (client.connected()) {
		str[length] = '\0';
		String message(str);
		client.publish(prefix + "system/log", message);
	}
	/*	if (udp.isConnected()) {
	 WiFiUDP Udp;
	 Udp.beginPacket(UdpServer::_lastAddress, UdpServer::_lastPort);
	 Udp.write(str, length);
	 Udp.write("\n");
	 Udp.endPacket();
	 }*/
}
Esempio n. 8
0
void loop() {
  ArduinoOTA.handle();

  // -- MQTT connect
    if (!client.connected()) {
      error_path += thisDevicePath;
      error_path += "/";
      error_path += "errors/";
      error_path += thisDeviceName;
      if (client.connect(MQTT::Connect(thisDeviceName).set_will(error_path, "disconnected"))) {
        Serial.println("MQTT connected");
        client.set_callback(callback);
        client.subscribe(MQTT::Subscribe()
          .add_topic("/deviceInfo/#")
          .add_topic("/global/#")
          .add_topic(subscribe_path)
                 );
        // notify persistence of device IP
          String persistence_ip_path = "/persistence/control/";
          persistence_ip_path += thisDeviceName;
          persistence_ip_path += "/ip";
          client.publish(MQTT::Publish(persistence_ip_path, local_ip_str).set_qos(2));

        // ask persistence/control/device_name/chipID "request states" --  do you have any states with my device_name or chipID
          String persistence_path = "/persistence/control/";
          persistence_path += thisDeviceName;
          persistence_path += "/";
          persistence_path += chip_id;
          client.publish(MQTT::Publish(persistence_path, "request states").set_qos(2));
          Serial.println("request states sent");
      }
    }

    if (client.connected()) {
      client.loop();
    }

  /*
  // -- Device Request Response
    if (sendJSON) {
      buildDeviceJson(); // flag set to false inside function
    }
  */

  /*
  // -- Confirm Messages
    if (sendConfirm) {
      client.publish(MQTT::Publish(confirmPath, confirmPayload).set_qos(2));
      sendConfirm = false;
    }
  */

  /*
  // -- NeoPixel updates
    if (neoPixelChange) {
      for(int i=0; i<PixelCount; i++) {
        strip.SetPixelColor(i, RgbColor (redValue, greenValue, blueValue));
      }
      strip.Show();
      neoPixelChange = false;
    }
  */

  // -- NeoPixel continuous update
    for(int i=0; i<PixelCount; i++) {
      strip.SetPixelColor(i, RgbColor (redValue, greenValue, blueValue));
    }
    strip.Show();

  /*
  // -- NeoPixel Sunrise Alarm Code
    if (millis() - lastcheck > alarmcheck)  {
      DateTime now = RTC.now();
      lastcheck = millis();
      if (alarmminute == now.minute() && alarmhour == now.hour()) {
         sunrise(4000);
         sunrise(400);
         sunrise(40);
         sunrise(40);
         sunrise(40);
         sunrise(40);
         sunrise(40);
         sunrise(20);
         sunrise(20);
         black();
      }
    }
  */


  // Do things every NTPLimit seconds
  if ( millis() - tick > NTPlimit) {
    tick = millis();

    /*
    // -- get server and send NTP packet
      //get a random server from the pool
      WiFi.hostByName(ntpServerName, timeServerIP);

      sendNTPpacket(timeServerIP); // send an NTP packet to a time server
      // wait to see if a reply is available
      delay(1000);

      int cb = udp.parsePacket();
      if (!cb) {
        Serial.println("no packet yet");
      }
      else {
        //Serial.print("packet received, length=");
        //Serial.println(cb);
        udp.read(packetBuffer, NTP_PACKET_SIZE); // read the packet into the buffer

        unsigned long highWord = word(packetBuffer[40], packetBuffer[41]);
        unsigned long lowWord = word(packetBuffer[42], packetBuffer[43]);
        // combine the four bytes (two words) into a long integer
        // this is NTP time (seconds since Jan 1 1900):
        unsigned long secsSince1900 = highWord << 16 | lowWord;
        const unsigned long seventyYears = 2208988800UL;
        unsigned long epoch = secsSince1900 - seventyYears;

        int UTChour = (epoch  % 86400L) / 3600;   // (86400 equals secs per day)
        int UTCmin = (epoch  % 3600) / 60;        // (3600 equals secs per minute)
        //Serial.println(UTChour);

        Serial.print(year(epoch));
        Serial.print('-');
        Serial.print(month(epoch));
        Serial.print('-');
        Serial.println(day(epoch));

        Serial.print("The UTC time is ");       // UTC is the time at Greenwich Meridian (GMT)
        Serial.print(UTChour);
        Serial.print(':');
        if ( ((epoch % 3600) / 60) < 10 ) {
          Serial.print('0');
        }
        Serial.print(UTCmin);
        Serial.print(':');
        if ( (epoch % 60) < 10 ) {
          Serial.print('0');
        }
        Serial.println(epoch % 60); // print the second
      }
    */

    /*
    // -- begin neropixel test

      delay(1000);

      Serial.println("Colors R, G, B, W...");

      // set the colors,
      // if they don't match in order, you need to use NeoGrbFeature feature
      strip.SetPixelColor(0, RgbColor (128, 0, 0));
      strip.SetPixelColor(1, green);
      strip.SetPixelColor(2, blue);
      strip.SetPixelColor(3, white);
      // the following line demonstrates rgbw color support
      // if the NeoPixels are rgbw types the following line will compile
      // if the NeoPixels are anything else, the following line will give an error
      //strip.SetPixelColor(3, RgbwColor(colorSaturation));
      strip.Show();


      delay(1000);

      Serial.println("Off ...");

      // turn off the pixels
      strip.SetPixelColor(0, black);
      strip.SetPixelColor(1, black);
      strip.SetPixelColor(2, black);
      strip.SetPixelColor(3, black);
      strip.Show();

      delay(1000);

      Serial.println("HSL Colors R, G, B, W...");

      // set the colors,
      // if they don't match in order, you may need to use NeoGrbFeature feature
      strip.SetPixelColor(0, hslRed);
      strip.SetPixelColor(1, hslGreen);
      strip.SetPixelColor(2, hslBlue);
      strip.SetPixelColor(3, hslWhite);
      strip.Show();


      delay(1000);

      Serial.println("Off again...");

      // turn off the pixels
      strip.SetPixelColor(0, hslBlack);
      strip.SetPixelColor(1, hslBlack);
      strip.SetPixelColor(2, hslBlack);
      strip.SetPixelColor(3, hslBlack);
      strip.Show();
    */

    // -- neopixel sunrise test
      //sunrise(40);
      //offblack();

    /*
    // -- print IP address
      Serial.println(WiFi.localIP());
      //Serial.println("..");
    */
  }


  yield();
}
Esempio n. 9
0
  void callback(const MQTT::Publish& pub) {
    yield();
    if (millis() - MQTTtick > MQTTlimit) {
      MQTTtick = millis();


      int commandLoc;
      String command = "";
      String deviceName = "";
      String endPoint = "";

      topic = pub.topic();
      payload = pub.payload_string();

      // -- topic parser
          // syntax:
          // global: / global / path / command / function
          // device setup: / deviceInfo / command / name
          // normal: path / command / name / endpoint

      // check item 1 in getValue
      String firstItem = getValue(topic, '/', 1);
      if (firstItem == "global") {
        // -- do nothing until I change to $ prefix before command types
      }
      else if (firstItem == "deviceInfo") {
        // get name and command
        deviceName = getValue(topic, '/', 3);
        command = getValue(topic, '/', 2);
        if ((deviceName == thisDeviceName) && (command == "control")) {
          if (payload == "no states") {
            // -- do something to send the default states, but now that this is managed by persistence this shouldn't be necessary
            // -- maybe it just resets all the states to 0 or whatever was originally programmed into the sketch
            //sendJSON = true;
          }
          else if (payload == "blink on") {
            Serial.end();
            pinMode(BUILTIN_LED, OUTPUT);
            ticker.attach(0.6, tick_fnc);
          }
          else if (payload == "blink off") {
            ticker.detach();
            digitalWrite(BUILTIN_LED, HIGH);
            pinMode(BUILTIN_LED, INPUT);
            Serial.begin(115200);
          }
          else {
            // -- persistence will no longer send the default object, if it's an arduino based esp chip, it will just send the control messages to /[device_path]/control/[device_name]/[endpoint_key]
          }






        }

      }
      else {

        int i;
        int maxitems;

        // count number of items
        for (i=1; i<topic.length(); i++) {
          String chunk = getValue(topic, '/', i);
          if (chunk == NULL) {
            break;
          }
        }

        // get topic variables
        maxitems = i;

        for (i=1; i<maxitems; i++) {
          String chunk = getValue(topic, '/', i);
          if (chunk == "control") {
            commandLoc = i;
            command = chunk;
            deviceName = getValue(topic, '/', i + 1);
            endPoint = getValue(topic, '/', i + 2);
            break;
          }
        }

        //Serial.println("device and endpoint incoming...");
        //Serial.println(deviceName);
        //Serial.println(endPoint);

          // send endpoint_key to function stored in namepins.h at compile time
          // function returns static_endpoint_id associated with that endpoint

          String lookup_val = lookup(endPoint);
          //Serial.println("looking value incoming...");
          //Serial.println(lookup_val);

          // sketch acts on that value as it normally would, using the static_endpoint_id to know for sure what it should do (turn output pin on/off, adjust RGB light, etc)
          if (lookup_val == "RGB") {
            // deserialize payload, get valueKey
            // or just look for value or red,green,blue
            String findKey = getValue(payload, '"', 1);
            String findValue = getValue(payload, ':', 1);
            findValue.remove(findValue.length() - 1);

            if (findKey == "red") {
              redValue = findValue.toInt();
            }
            else if (findKey == "green") {
              greenValue = findValue.toInt();
            }
            else if (findKey == "blue") {
              blueValue = findValue.toInt();
            }
            //neoPixelChange = true;
          }
          /*
          else if (lookup_val == "SECOND STATIC ENDPOINT ID") {

          }
          else if (lookup_val == "THIRD STATIC ENDPOINT ID") {

          }
          */


          // sketch confirms the value by sending it back on /[path]/[confirm]/[device_name]/[endpoint_key]

          confirmPath = "";
          confirmPath = thisDevicePath;
          confirmPath += "/confirm/";
          confirmPath += thisDeviceName;
          confirmPath += "/";
          confirmPath += endPoint;
          confirmPayload = payload;

          //sendConfirm = true;
          client.publish(MQTT::Publish(confirmPath, confirmPayload).set_qos(2));

      }
    }




  }
Esempio n. 10
0
void mqttPublish(const char* topic, String message) {
	if (client.connected())
		client.publish(prefix + topic, message);
}