Exemple #1
0
int8_t Adafruit_MQTT::connect() {
  // Connect to the server.
  if (!connectServer())
    return -1;

  // Construct and send connect packet.
  uint8_t len = connectPacket(buffer);
  if (!sendPacket(buffer, len))
    return -1;

  // Read connect response packet and verify it
  len = readPacket(buffer, 4, CONNECT_TIMEOUT_MS);
  if (len != 4)
    return -1;
  if ((buffer[0] != (MQTT_CTRL_CONNECTACK << 4)) || (buffer[1] != 2))
    return -1;
  if (buffer[3] != 0)
    return buffer[3];

  // Setup subscriptions once connected.
  for (uint8_t i=0; i<MAXSUBSCRIPTIONS; i++) {
    // Ignore subscriptions that aren't defined.
    if (subscriptions[i] == 0) continue;

    // Construct and send subscription packet.
    uint8_t len = subscribePacket(buffer, subscriptions[i]->topic, subscriptions[i]->qos);
    if (!sendPacket(buffer, len))
      return -1;

    // Check for SUBACK if using MQTT 3.1.1 or higher
    // TODO: The Server is permitted to start sending PUBLISH packets matching the
    // Subscription before the Server sends the SUBACK Packet.
    // if(MQTT_PROTOCOL_LEVEL > 3) {
    //   len = readPacket(buffer, 5, CONNECT_TIMEOUT_MS);
    //   DEBUG_PRINT(F("SUBACK:\t"));
    //   DEBUG_PRINTBUFFER(buffer, len);
    //   if ((len != 5) || (buffer[0] != (MQTT_CTRL_SUBACK << 4))) {
    //     return 6;  // failure to subscribe
    //   }
    // }

  }

  return 0;
}
int8_t Adafruit_MQTT::connect() {
  // Connect to the server.
  if (!connectServer())
    return -1;

  // Construct and send connect packet.
  uint8_t len = connectPacket(buffer);
  if (!sendPacket(buffer, len))
    return -1;

  // Read connect response packet and verify it
  len = readPacket(buffer, 4, CONNECT_TIMEOUT_MS);
  if (len != 4)
    return -1;
  if ((buffer[0] != (MQTT_CTRL_CONNECTACK << 4)))
    return -1;
  if (buffer[3] != 0)
    return buffer[3];

  // Setup subscriptions once connected.
  for (uint8_t i=0; i<MAXSUBSCRIPTIONS; i++) {
    // Ignore subscriptions that aren't defined.
    if (subscriptions[i] == 0) continue;

    // Construct and send subscription packet.
    uint8_t len = subscribePacket(buffer, subscriptions[i]->topic, subscriptions[i]->qos);
    if (!sendPacket(buffer, len))
      return -1;

    // Get SUBACK
    len = readPacket(buffer, 5, CONNECT_TIMEOUT_MS);
    // DEBUG_PRINT(F("SUBACK:\t"));
    // DEBUG_PRINTBUFFER(buffer, len);
    // if (false) {
    //   return 6;  // failure to subscribe
    // }
  }

  return 0;
}