Skip to content

Instantly share code, notes, and snippets.

@JonasDoesThings
Last active May 1, 2019 16:20
Show Gist options
  • Save JonasDoesThings/cc3aa12d9bf97628cd46d875e005af80 to your computer and use it in GitHub Desktop.
Save JonasDoesThings/cc3aa12d9bf97628cd46d875e005af80 to your computer and use it in GitHub Desktop.
Arduino LED Matrix Messageboard Code
#include "Queue.h"
#include <ESP8266WiFi.h>
#include <WiFiManager.h>
#include <DNSServer.h>
#include <MD_Parola.h>
#include <MD_MAX72xx.h>
#include <SPI.h>
#include <PubSubClient.h>
#define HARDWARE_TYPE MD_MAX72XX::FC16_HW
#define MAX_DEVICES 4
#define CLK_PIN D5
#define DATA_PIN D7
#define CS_PIN D8
#define SCREENSAVER_DELAY 2*60*1000
#define SLEEP_DELAY 4*60*1000
MD_Parola matrix = MD_Parola(HARDWARE_TYPE, CS_PIN, MAX_DEVICES);
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
Queue<String> queue = Queue<String>(20);
char buffer[255];
unsigned long lastMessage = millis();
void mqttCallback(char* topic, byte* payload, unsigned int length) {
String s;
for (int i=0;i<length;i++) {
s += (char)payload[i];
}
Serial.print("Received ");
Serial.print(topic);
Serial.print(" - ");
Serial.println(s);
if(String(topic).equals("workspace/messageboard/message")) {
queue.push(s);
}
}
void mqttConnect() {
Serial.println("Connecting to MQTT!");
while(!mqttClient.connected()) {
// Attempt to connect
String clientID = "MessageBoard";
if(mqttClient.connect(clientID.c_str(), "MQTTUSER ", "MQTTPASSWORD")) {
Serial.println("Connected to MQTT!");
mqttClient.subscribe("workspace/messageboard/message");
} else {
Serial.print("failed, rc=");
Serial.print(mqttClient.state());
delay(5000);
}
}
}
void setup() {
Serial.begin(115200);
matrix.begin();
matrix.displayClear();
matrix.displaySuspend(false);
queue.push("Connecting...");
WiFiManager wifiManager;
wifiManager.autoConnect();
Serial.println("Connected to WiFi!");
Serial.println(WiFi.localIP());
mqttClient.setServer("192.168.0.20", 1883);
mqttClient.setCallback(mqttCallback);
}
void loop() {
if(!mqttClient.connected()) {
mqttConnect();
}
mqttClient.loop();
if(matrix.displayAnimate()) {
String message = queue.pop();
if(message != "") {
Serial.println("[V] Current Message: " + message);
lastMessage = millis();
message.toCharArray(buffer, 255);
matrix.displayScroll(buffer, PA_LEFT, PA_SCROLL_LEFT, 40);
} else {
if(millis() - lastMessage > SLEEP_DELAY) {
delay(500);
} else if(millis() - lastMessage > SCREENSAVER_DELAY) {
matrix.displayScroll("Insert Coin...", PA_LEFT, PA_SCROLL_LEFT, 50);
} else {
matrix.displayScroll(buffer, PA_LEFT, PA_SCROLL_LEFT, 40);
}
}
}
}
from __future__ import print_function
import sys
import irc.bot
import paho.mqtt.client as mqtt
import asyncio
import argparse
import time
import urllib
class TwitchBot(irc.bot.SingleServerIRCBot):
def __init__(self, username, token, mqttusername, mqttpassword):
self.token = token
self.channel = '#' + username
# Create IRC bot connection
server = 'irc.chat.twitch.tv'
port = 6667
print('Connecting to ' + server + ' on port ' + str(port) + '...')
irc.bot.SingleServerIRCBot.__init__(self, [(server, port, token)], username, username)
self.client = mqtt.Client(client_id="messageboard-twitch", clean_session=False)
self.client.username_pw_set(mqttusername, mqttpassword)
self.client.on_disconnect = self.on_disconnect
self.client.on_connect = self.on_connect
self.mqttconnected = None
self.mqtt_connect()
self.client.loop_start()
def mqtt_connect(self):
self.client.connect("192.168.0.20", 1883, 20)
def on_connect(self, client, userdata, flags, rc):
print("Connected to MQTT Broker (rc=" + rc + ")")
self.mqttconnected = True
def on_disconnect(self, client, userdata, rc):
print("Disconnected from MQTT Broker (rc=" + rc + ")")
self.mqtt_connect()
self.mqttconnected = False
def on_welcome(self, connection, event):
print('Joining ' + self.channel)
# You must request specific capabilities before you can use them
connection.cap('REQ', ':twitch.tv/membership')
connection.cap('REQ', ':twitch.tv/tags')
connection.cap('REQ', ':twitch.tv/commands')
connection.join(self.channel)
def on_pubmsg(self, connection, event):
# If a chat message starts with an exclamation point, try to run it as a command
if event.arguments[0][:1] == '!':
cmd = event.arguments[0].split(' ')[0][1:]
print('Received command: ' + cmd)
self.do_command(event, cmd)
return
def do_command(self, event, cmd):
c = self.connection
print(event.arguments)
if cmd == "message":
message_parts = event.arguments[0].split(' ')
message_parts.pop(0)
if len(message_parts) < 1:
c.privmsg(self.channel, "Usage: !message <Your Message>")
args = ""
for arg in message_parts:
args += arg + " "
if self.mqttconnected == False:
self.mqtt_connect()
self.client.publish("workspace/messageboard/message", args.encode('cp437', errors="ignore"), qos=1, retain=True)
elif cmd == "discord":
c.privmsg(self.channel, "https://discord.gg/discord.gg/qPXMdJm")
def main():
parser = argparse.ArgumentParser(description=__doc__)
required = parser.add_argument_group('required arguments')
required.add_argument('-u', '--username', required=True)
required.add_argument('-t', '--token', required=True)
required.add_argument('-mu', required=True)
required.add_argument('-mp', required=True)
args = parser.parse_args()
bot = TwitchBot(args.username.lower(), args.token, args.mu, args.mp)
bot.start()
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment