Remade the ESP32 code. Fixed some bugs in the website.

This commit is contained in:
Boyan 2023-09-09 19:35:41 +02:00
parent 837a3f09de
commit 1c361820c7
4 changed files with 147 additions and 20 deletions

View File

@ -0,0 +1,116 @@
// Example sketch which shows how to display some patterns
// on a 64x32 LED matrix
//
#include <ESP32-HUB75-MatrixPanel-I2S-DMA.h>
#include <WiFi.h>
#include <HTTPClient.h>
#define PANEL_RES_X 64 // Number of pixels wide of each INDIVIDUAL panel module.
#define PANEL_RES_Y 32 // Number of pixels tall of each INDIVIDUAL panel module.
#define PANEL_CHAIN 1 // Total number of panels chained one to another
//MatrixPanel_I2S_DMA dma_display;
MatrixPanel_I2S_DMA *dma_display = nullptr;
void putPixel(int16_t x, int16_t y, uint16_t color) {
dma_display->drawPixel(x, y, color);
}
// Replace with your network credentials
const char* ssid = "ssid";
const char* password = "password";
void initWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
Serial.print("Connecting to WiFi ..");
while (WiFi.status() != WL_CONNECTED) {
Serial.print('.');
delay(1000);
}
Serial.println(WiFi.localIP());
}
String serverName = "https://changethis.com/board/json/";
void setup() {
initWiFi();
// Module configuration
HUB75_I2S_CFG mxconfig(
PANEL_RES_X, // module width
PANEL_RES_Y, // module height
PANEL_CHAIN // Chain length
);
// Display Setup
dma_display = new MatrixPanel_I2S_DMA(mxconfig);
dma_display->begin();
dma_display->setBrightness8(90); //0-255
dma_display->clearScreen();
// fill the screen with 'black'
dma_display->fillScreen(dma_display->color444(0, 0, 0));
}
// the following variables are unsigned longs because the time, measured in
// milliseconds, will quickly become a bigger number than can be stored in an int.
unsigned long lastTime = 0;
// Timer set to 10 minutes (600000)
//unsigned long timerDelay = 600000;
// Set timer to 5 seconds (5000)
unsigned long timerDelay = 5000;
void loop() {
if ((millis() - lastTime) > timerDelay) {
//Check WiFi connection status
if(WiFi.status()== WL_CONNECTED){
HTTPClient http;
String serverPath = serverName;
// Your Domain name with URL path or IP address with path
http.begin(serverPath.c_str());
// If you need Node-RED/server authentication, insert user and password below
//http.setAuthorization("REPLACE_WITH_SERVER_USERNAME", "REPLACE_WITH_SERVER_PASSWORD");
// Send HTTP GET request
int httpResponseCode = http.GET();
if (httpResponseCode>0) {
Serial.print("HTTP Response code: ");
Serial.println(httpResponseCode);
String payload = http.getString();
Serial.println(payload);
}
else {
Serial.print("Error code: ");
Serial.println(httpResponseCode);
}
// Free resources
http.end();
}
else {
Serial.println("WiFi Disconnected, trying to reconnect");
WiFi.reconnect();
}
lastTime = millis();
}
}
// animate by going through the colour wheel for the first two lines
drawText(wheelval);
wheelval +=1;
delay(20);
}

View File

@ -21,5 +21,6 @@ from website import views
urlpatterns = [ urlpatterns = [
path('admin/', admin.site.urls), path('admin/', admin.site.urls),
path('board/', views.current_config), path('board/', views.current_config),
path('board/json/', views.current_board),
path('board/<int:x>/<int:y>/<str:color>', views.update_board), path('board/<int:x>/<int:y>/<str:color>', views.update_board),
] ]

View File

@ -0,0 +1 @@
URL = "http://127.0.0.1:8000/board/"

View File

@ -5,6 +5,8 @@ from django.http import HttpResponse
from django.core.exceptions import ObjectDoesNotExist from django.core.exceptions import ObjectDoesNotExist
from colour import Color from colour import Color
from pytz import UTC from pytz import UTC
from .config import URL
# Change these for your board # Change these for your board
BOARD_X = 64 BOARD_X = 64
BOARD_Y = 32 BOARD_Y = 32
@ -17,11 +19,7 @@ BOARD_Y = 32
# Internal validation # Internal validation
def validateBoard(x:int, y:int, board:dict, ip) -> bool: def validateBoard(x:int, y:int, board:dict, ip) -> bool:
try:
ip = RestrictedIP.objects.get(ip=ip)
return "RESTRICTED"
except ObjectDoesNotExist:
pass
key_counter = 0 # Not using len for optimization purposes key_counter = 0 # Not using len for optimization purposes
for row in board: for row in board:
@ -48,12 +46,12 @@ def restrict_or_unrestrict(ip):
# if banned for more than 1 minute, unban # if banned for more than 1 minute, unban
if timedelta.seconds > 60: if timedelta.seconds > 60:
ip.delete() ip.delete()
return "ALLOWED" return "SUCESS"
return "STILL RESTRICTED" return "STILL RESTRICTED"
except ObjectDoesNotExist: except ObjectDoesNotExist:
instance = RestrictedIP(ip=ip, time_added=datetime.now()) instance = RestrictedIP(ip=ip, time_added=datetime.now())
instance.save() instance.save()
return "RESTRICTION" return "SUCCESS"
# Internal board class # Internal board class
class localBoard: class localBoard:
@ -83,7 +81,7 @@ class localBoard:
instance.save() instance.save()
self.board = Board.objects.latest("update_time") self.board = Board.objects.latest("update_time")
return "SUCCESS" return "SUCCESS"
def HTML(self) -> str: def HTML(self) -> str:
board = self.getBoard() board = self.getBoard()
style = """ style = """
@ -100,30 +98,38 @@ class localBoard:
</style> </style>
""" """
selected_pixel = """ selected_pixel = f"""
<script> <script>
async function selected_pixel(element) { async function selected_pixel(element) {{
var color = document.getElementById("color_picker").value; var color = document.getElementById("color_picker").value;
var arr = element.id.split("x")[1].split("y"); var arr = element.id.split("x")[1].split("y");
var x = arr[0]; var x = arr[0];
var y = arr[1]; var y = arr[1];
var url = "http://127.0.0.1:8000/board/" + x + "/" + y + "/" + color.replace("#", "%23"); var url = "{URL}" + x + "/" + y + "/" + color.replace("#", "%23");
let response = await fetch(url); let response = await fetch(url);
let result = await response.text(); let result = await response.text();
console.log(result); console.log(result);
if (result != "RESTRICTED") { if (result != "RESTRICTED") {{
element.style.backgroundColor = color; element.style.backgroundColor = color;
} }}
else { else {{
alert("You have placed your pixel. Please wait."); alert("You have placed your pixel. Please wait.");
} }}
} }}
</script> </script>
""" """
reload_page = """
html = f"<html><head><title>Ballin</title></head>{style}<body>{selected_pixel}<table><form>" <script>
function reload_page() {
location.reload();
}
setTimeout(reload_page, 10000);
</script>
"""
html = f"<html><head><title>Ballin</title>{reload_page}</head>{style}<body>{selected_pixel}<table><form>"
for row in board: for row in board:
html += "<tr>" html += "<tr>"
x = 0 x = 0
@ -132,7 +138,7 @@ class localBoard:
x += 1 x += 1
html += "</tr>" html += "</tr>"
html += "</table><div class='color'><input type='color' id='color_picker'><p color='white' ><------ pick ur color</p></div></body></html>" html += "</table><div class='color'><input type='color' id='color_picker'><p color='white' ><------ pick ur color</p></div></body></html>"
return html return html
# Publicly visible functions # Publicly visible functions
def update_board(request, x, y, color): def update_board(request, x, y, color):
@ -144,7 +150,7 @@ def update_board(request, x, y, color):
board[str(y)][int(x)] = color board[str(y)][int(x)] = color
ip = restrict_or_unrestrict(request.META["REMOTE_ADDR"]) ip = restrict_or_unrestrict(request.META["REMOTE_ADDR"])
if ip == "STILL RESTRICTED": if ip != "SUCCESS":
return HttpResponse("RESTRICTED") return HttpResponse("RESTRICTED")
res = localBoard().setBoard(board, request.META["REMOTE_ADDR"]) res = localBoard().setBoard(board, request.META["REMOTE_ADDR"])
return HttpResponse(f"board: {str(res)}, ip: {ip}") return HttpResponse(f"board: {str(res)}, ip: {ip}")
@ -153,3 +159,6 @@ def current_config(request):
html = localBoard().HTML() html = localBoard().HTML()
return HttpResponse(html) return HttpResponse(html)
def json_board(request):
board = localBoard().getBoard()
return HttpResponse(board)