aboutsummaryrefslogtreecommitdiff
path: root/src/main.cpp
blob: ad91fa52c98bb3418f64b05c9b6a8e8e45d76e29 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
#include <WiFi.h>
#include <PubSubClient.h>
#include <Arduino.h>
#include "./local.h" // defines ssid and password

WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);

#define BUTTON_PIN 14
#define LED_PIN 2

long lastMsg = 0;
long lastButtonState = LOW; // High/1 by default, Low/0 when pressed

// Reconnect to the wifi / MQTT if required
void reconnect() {
  if (WiFi.status() != WL_CONNECTED) {
    WiFi.begin(ssid, password);
  }
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print("waiting for wifi, status=");
    Serial.println(WiFi.status());
  }

  while (!mqttClient.connected()) {
    Serial.println("attempting mqtt connection...");
    mqttClient.setServer(mqtt_broker, mqtt_port);
    if (!mqttClient.connect("Bark-Button")) {
      Serial.print("failed to connect to mqtt, rc=");
      Serial.println(mqttClient.state());
      delay(2000);
    }
  }
}

// On button press, send a message to the MQTT broker
void buttonPress() {
  char buf[40];
  reconnect();

  sprintf(buf, "barks/%d.mp3", random(n_bark_sounds));
  mqttClient.publish(mqtt_topic, buf);
}

void setup() {
  Serial.begin(9600);
  reconnect();

  pinMode(BUTTON_PIN, INPUT_PULLUP);
  pinMode(LED_PIN, OUTPUT);
}

// Wait for button press
void loop() {
  mqttClient.loop();

  int buttonState = digitalRead(BUTTON_PIN);
  if (buttonState != lastButtonState && buttonState == LOW) {
    digitalWrite(LED_PIN, HIGH);
    buttonPress();
    delay(100);
    digitalWrite(LED_PIN, LOW);
  }
  lastButtonState = buttonState;

}