From 254b9379a5843bcd6ffa33ffedf532c75d607b37 Mon Sep 17 00:00:00 2001 From: Boyan Date: Thu, 14 Mar 2024 18:01:57 +0100 Subject: [PATCH] Moving --- Platrix/.gitignore | 168 ++++++++++++++++++ Platrix/LICENSE | 9 + Platrix/README.md | 3 + Platrix/src/arduino/.vscode/arduino.json | 8 + Platrix/src/arduino/text_display.ino | 105 +++++++++++ .../src/arduino/text_display/text_display.ino | 156 ++++++++++++++++ Platrix/src/place/manage.py | 22 +++ Platrix/src/place/place/__init__.py | 0 Platrix/src/place/place/asgi.py | 16 ++ Platrix/src/place/place/settings.py | 124 +++++++++++++ Platrix/src/place/place/urls.py | 26 +++ Platrix/src/place/place/wsgi.py | 16 ++ Platrix/src/place/website/__init__.py | 0 Platrix/src/place/website/admin.py | 5 + Platrix/src/place/website/apps.py | 6 + Platrix/src/place/website/config.py | 1 + Platrix/src/place/website/models.py | 15 ++ Platrix/src/place/website/tests.py | 3 + Platrix/src/place/website/views.py | 164 +++++++++++++++++ README.md | 5 +- led_strip_door/README.md | 1 + led_strip_door/led_strip_door.ino | 41 +++++ 22 files changed, 893 insertions(+), 1 deletion(-) create mode 100644 Platrix/.gitignore create mode 100644 Platrix/LICENSE create mode 100644 Platrix/README.md create mode 100644 Platrix/src/arduino/.vscode/arduino.json create mode 100644 Platrix/src/arduino/text_display.ino create mode 100644 Platrix/src/arduino/text_display/text_display.ino create mode 100755 Platrix/src/place/manage.py create mode 100644 Platrix/src/place/place/__init__.py create mode 100644 Platrix/src/place/place/asgi.py create mode 100644 Platrix/src/place/place/settings.py create mode 100644 Platrix/src/place/place/urls.py create mode 100644 Platrix/src/place/place/wsgi.py create mode 100644 Platrix/src/place/website/__init__.py create mode 100644 Platrix/src/place/website/admin.py create mode 100644 Platrix/src/place/website/apps.py create mode 100644 Platrix/src/place/website/config.py create mode 100644 Platrix/src/place/website/models.py create mode 100644 Platrix/src/place/website/tests.py create mode 100644 Platrix/src/place/website/views.py create mode 100644 led_strip_door/README.md create mode 100644 led_strip_door/led_strip_door.ino diff --git a/Platrix/.gitignore b/Platrix/.gitignore new file mode 100644 index 0000000..4e500d8 --- /dev/null +++ b/Platrix/.gitignore @@ -0,0 +1,168 @@ +# ---> Python +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# Django migrations +migrations/ + +# sqlite3 db +*.sqlite3 + +# C extensions +*.so + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +share/python-wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +*.py,cover +.hypothesis/ +.pytest_cache/ +cover/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +.pybuilder/ +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +# For a library or package, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# .python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# poetry +# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control. +# This is especially recommended for binary packages to ensure reproducibility, and is more +# commonly ignored for libraries. +# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control +#poetry.lock + +# pdm +# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control. +#pdm.lock +# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it +# in version control. +# https://pdm.fming.dev/#use-with-ide +.pdm.toml + +# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm +__pypackages__/ + +# Celery stuff +celerybeat-schedule +celerybeat.pid + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +# Pyre type checker +.pyre/ + +# pytype static type analyzer +.pytype/ + +# Cython debug symbols +cython_debug/ + +# PyCharm +# JetBrains specific template is maintained in a separate JetBrains.gitignore that can +# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore +# and can be added to the global gitignore or merged into this file. For a more nuclear +# option (not recommended) you can uncomment the following to ignore the entire idea folder. +#.idea/ + diff --git a/Platrix/LICENSE b/Platrix/LICENSE new file mode 100644 index 0000000..d25b5c1 --- /dev/null +++ b/Platrix/LICENSE @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2023 boyan_k + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/Platrix/README.md b/Platrix/README.md new file mode 100644 index 0000000..027a07a --- /dev/null +++ b/Platrix/README.md @@ -0,0 +1,3 @@ +# Platrix + +r/place like project designed for LED matrices \ No newline at end of file diff --git a/Platrix/src/arduino/.vscode/arduino.json b/Platrix/src/arduino/.vscode/arduino.json new file mode 100644 index 0000000..f0285df --- /dev/null +++ b/Platrix/src/arduino/.vscode/arduino.json @@ -0,0 +1,8 @@ +{ + "port": "/dev/ttyS0", + "configuration": "PartitionScheme=default,CPUFreq=240,FlashMode=qio,FlashFreq=80,FlashSize=4M,UploadSpeed=921600,LoopCore=1,EventsCore=1,DebugLevel=none,EraseFlash=none", + "board": "esp32:esp32:esp32da", + "programmer": "esptool", + "sketch": "text_display.ino", + "output": "../ArduinoOutput" +} \ No newline at end of file diff --git a/Platrix/src/arduino/text_display.ino b/Platrix/src/arduino/text_display.ino new file mode 100644 index 0000000..785b801 --- /dev/null +++ b/Platrix/src/arduino/text_display.ino @@ -0,0 +1,105 @@ + +// Example sketch which shows how to display some patterns +// on a 64x32 LED matrix +// + +#include + + +#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; + +const char *firstLine = "obicham te"; +const char *secondLine = "mnogo, bebi"; +const char *thirdLine = "bottom text"; + + +uint16_t myBLACK = dma_display->color565(0, 0, 0); +uint16_t myWHITE = dma_display->color565(255, 255, 255); +uint16_t myRED = dma_display->color565(255, 0, 0); +uint16_t myGREEN = dma_display->color565(0, 255, 0); +uint16_t myBLUE = dma_display->color565(0, 0, 255); + + + +// Input a value 0 to 255 to get a color value. +// The colours are a transition r - g - b - back to r. +// From: https://gist.github.com/davidegironi/3144efdc6d67e5df55438cc3cba613c8 +uint16_t colorWheel(uint8_t pos) { + if(pos < 85) { + return dma_display->color565(pos * 3, 255 - pos * 3, 0); + } else if(pos < 170) { + pos -= 85; + return dma_display->color565(255 - pos * 3, 0, pos * 3); + } else { + pos -= 170; + return dma_display->color565(0, pos * 3, 255 - pos * 3); + } +} + +void drawText(int colorWheelOffset) +{ + + // draw text with a rotating colour + dma_display->setTextSize(1); // size 1 == 8 pixels high + dma_display->setTextWrap(false); // Don't wrap at end of line - will do ourselves + + dma_display->setCursor(0, 0); // start at top left + uint8_t w = 0; + for (w=0; wsetTextColor(colorWheel((w*32)+colorWheelOffset)); + dma_display->print(firstLine[w]); + } + + dma_display->println(); + for (w=9; w<20; w++) { + dma_display->setTextColor(colorWheel((w*32)+colorWheelOffset)); + dma_display->print("="); + } + + dma_display->println(); + + dma_display->setTextColor(dma_display->color444(15,15,15)); + dma_display->println(secondLine); // 10 char max + dma_display->println(thirdLine); +} + + +void setup() { + + // 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(); + dma_display->fillScreen(myWHITE); + + // fill the screen with 'black' + dma_display->fillScreen(dma_display->color444(0, 0, 0)); + +} + +uint8_t wheelval = 0; + +void loop() { + + // animate by going through the colour wheel for the first two lines + drawText(wheelval); + wheelval +=1; + + delay(20); + + +} diff --git a/Platrix/src/arduino/text_display/text_display.ino b/Platrix/src/arduino/text_display/text_display.ino new file mode 100644 index 0000000..4f24e9d --- /dev/null +++ b/Platrix/src/arduino/text_display/text_display.ino @@ -0,0 +1,156 @@ + +// Example sketch which shows how to display some patterns +// on a 64x32 LED matrix +// + +#include +#include +#include +#include + +#define REFRESH 10 // Seconds until refresh +#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; + + + +int hexToRGB(String hex) { + + // TODO: Fix the colors not being accurate + // Remove the '#' from the start + hex.remove(0, 1); + + // Extract and convert the red, green, and blue components + uint8_t r = strtol(hex.substring(0, 2).c_str(), NULL, 16); + uint8_t g = strtol(hex.substring(2, 4).c_str(), NULL, 16); + uint8_t b = strtol(hex.substring(4, 6).c_str(), NULL, 16); + + return dma_display->color565(r, g, b); + +} + + +// Pixel putting +void putPixel(int16_t x, int16_t y, int color) { + dma_display->drawPixel(x, y, color); +} + +// Replace with your network credentials +const char* ssid = "SSID"; +const char* password = "PASSWORD"; +String serverName = "https://your-domain.com/board/json/"; + +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()); +} + + + + +void setup() { + Serial.begin(9600); + 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 + String payload = "null"; + 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); + payload = http.getString(); + } + else { + Serial.print("Error code: "); + Serial.println(httpResponseCode); + } + // Free resources + http.end(); + } + else { + Serial.println("WiFi Disconnected, trying to reconnect"); + WiFi.reconnect(); + } + lastTime = millis(); + + if (payload != "null") { + JSONVar board = JSON.parse(payload); + if (JSON.typeof(board) == "undefined") { + Serial.println("Parsing failed!"); + return; + } + // Parse JSON + for (int y = 0; y < PANEL_RES_Y; y++) { + for (int x = 0; x < PANEL_RES_X; x++) { + String color = board[String(y)][x]; + + int colorize; + if (color.length() < 1) { + colorize = dma_display->color444(0, 0, 0); + } + else { + colorize = hexToRGB(color); + } + putPixel(x, y, colorize); + } + } + } + + + } + + delay(REFRESH * 100); +} diff --git a/Platrix/src/place/manage.py b/Platrix/src/place/manage.py new file mode 100755 index 0000000..7276861 --- /dev/null +++ b/Platrix/src/place/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +"""Django's command-line utility for administrative tasks.""" +import os +import sys + + +def main(): + """Run administrative tasks.""" + os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'place.settings') + try: + from django.core.management import execute_from_command_line + except ImportError as exc: + raise ImportError( + "Couldn't import Django. Are you sure it's installed and " + "available on your PYTHONPATH environment variable? Did you " + "forget to activate a virtual environment?" + ) from exc + execute_from_command_line(sys.argv) + + +if __name__ == '__main__': + main() diff --git a/Platrix/src/place/place/__init__.py b/Platrix/src/place/place/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Platrix/src/place/place/asgi.py b/Platrix/src/place/place/asgi.py new file mode 100644 index 0000000..9ceb452 --- /dev/null +++ b/Platrix/src/place/place/asgi.py @@ -0,0 +1,16 @@ +""" +ASGI config for place project. + +It exposes the ASGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/asgi/ +""" + +import os + +from django.core.asgi import get_asgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'place.settings') + +application = get_asgi_application() diff --git a/Platrix/src/place/place/settings.py b/Platrix/src/place/place/settings.py new file mode 100644 index 0000000..37179b9 --- /dev/null +++ b/Platrix/src/place/place/settings.py @@ -0,0 +1,124 @@ +""" +Django settings for place project. + +Generated by 'django-admin startproject' using Django 4.2.1. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/4.2/ref/settings/ +""" + +from pathlib import Path + +# Build paths inside the project like this: BASE_DIR / 'subdir'. +BASE_DIR = Path(__file__).resolve().parent.parent + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/4.2/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'django-insecure-)1r%_dlx4^+o8sg#z8vm-mq+8oslg=v2*(2zpc6-y+$_ntm4%!' + +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True + +ALLOWED_HOSTS = ["*"] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + "website", +] + +MIDDLEWARE = [ + 'django.middleware.security.SecurityMiddleware', + 'django.contrib.sessions.middleware.SessionMiddleware', + 'django.middleware.common.CommonMiddleware', + 'django.middleware.csrf.CsrfViewMiddleware', + 'django.contrib.auth.middleware.AuthenticationMiddleware', + 'django.contrib.messages.middleware.MessageMiddleware', + 'django.middleware.clickjacking.XFrameOptionsMiddleware', +] + +ROOT_URLCONF = 'place.urls' + +TEMPLATES = [ + { + 'BACKEND': 'django.template.backends.django.DjangoTemplates', + 'DIRS': [], + 'APP_DIRS': True, + 'OPTIONS': { + 'context_processors': [ + 'django.template.context_processors.debug', + 'django.template.context_processors.request', + 'django.contrib.auth.context_processors.auth', + 'django.contrib.messages.context_processors.messages', + ], + }, + }, +] + +WSGI_APPLICATION = 'place.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/4.2/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': BASE_DIR / 'db.sqlite3', + } +} + + +# Password validation +# https://docs.djangoproject.com/en/4.2/ref/settings/#auth-password-validators + +AUTH_PASSWORD_VALIDATORS = [ + { + 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + }, + { + 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + }, +] + + +# Internationalization +# https://docs.djangoproject.com/en/4.2/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/4.2/howto/static-files/ + +STATIC_URL = 'static/' + +# Default primary key field type +# https://docs.djangoproject.com/en/4.2/ref/settings/#default-auto-field + +DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' diff --git a/Platrix/src/place/place/urls.py b/Platrix/src/place/place/urls.py new file mode 100644 index 0000000..1f18e5c --- /dev/null +++ b/Platrix/src/place/place/urls.py @@ -0,0 +1,26 @@ +""" +URL configuration for place project. + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/4.2/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: path('', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.urls import include, path + 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) +""" +from django.contrib import admin +from django.urls import path +from website import views + +urlpatterns = [ + path('admin/', admin.site.urls), + path('board/', views.current_config), + path('board/json/', views.json_board), + path('board///', views.update_board), +] diff --git a/Platrix/src/place/place/wsgi.py b/Platrix/src/place/place/wsgi.py new file mode 100644 index 0000000..b953d0c --- /dev/null +++ b/Platrix/src/place/place/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for place project. + +It exposes the WSGI callable as a module-level variable named ``application``. + +For more information on this file, see +https://docs.djangoproject.com/en/4.2/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'place.settings') + +application = get_wsgi_application() diff --git a/Platrix/src/place/website/__init__.py b/Platrix/src/place/website/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Platrix/src/place/website/admin.py b/Platrix/src/place/website/admin.py new file mode 100644 index 0000000..4e638fc --- /dev/null +++ b/Platrix/src/place/website/admin.py @@ -0,0 +1,5 @@ +from django.contrib import admin +from .models import Board, RestrictedIP +# Register your models here. +admin.site.register(Board) +admin.site.register(RestrictedIP) \ No newline at end of file diff --git a/Platrix/src/place/website/apps.py b/Platrix/src/place/website/apps.py new file mode 100644 index 0000000..2b099b1 --- /dev/null +++ b/Platrix/src/place/website/apps.py @@ -0,0 +1,6 @@ +from django.apps import AppConfig + + +class WebsiteConfig(AppConfig): + default_auto_field = 'django.db.models.BigAutoField' + name = 'website' diff --git a/Platrix/src/place/website/config.py b/Platrix/src/place/website/config.py new file mode 100644 index 0000000..3514e70 --- /dev/null +++ b/Platrix/src/place/website/config.py @@ -0,0 +1 @@ +URL = "http://127.0.0.1:8000/board/" diff --git a/Platrix/src/place/website/models.py b/Platrix/src/place/website/models.py new file mode 100644 index 0000000..1df0cc3 --- /dev/null +++ b/Platrix/src/place/website/models.py @@ -0,0 +1,15 @@ +from django.db import models + +class Board(models.Model): + update_time = models.DateTimeField(unique=True, primary_key=True) + configuration = models.JSONField() + + def __str__(self) -> str: + return f"{self.update_time}" + +class RestrictedIP(models.Model): + ip = models.GenericIPAddressField(unique=True, primary_key=True) + time_added = models.DateTimeField() + + def __str__(self) -> str: + return f"{self.ip}" \ No newline at end of file diff --git a/Platrix/src/place/website/tests.py b/Platrix/src/place/website/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/Platrix/src/place/website/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/Platrix/src/place/website/views.py b/Platrix/src/place/website/views.py new file mode 100644 index 0000000..701f477 --- /dev/null +++ b/Platrix/src/place/website/views.py @@ -0,0 +1,164 @@ +from django.shortcuts import render +from .models import Board, RestrictedIP +from datetime import datetime +from django.http import HttpResponse, JsonResponse +from django.core.exceptions import ObjectDoesNotExist +from colour import Color +from pytz import UTC +from .config import URL + +# Change these for your board +BOARD_X = 64 +BOARD_Y = 32 + +# Options for implementation of board update: +# 1) Serve at a special url which is a OTC generated by the server and the client (Hard-ish) +# 2) Serve at all times and have the client decide when it has changed(Easy) + + + +# Internal validation +def validateBoard(x:int, y:int, board:dict, ip) -> bool: + + key_counter = 0 # Not using len for optimization purposes + + for row in board: + # Check if datatype is list + if not isinstance(board[row], list): + return "WRONG Y" + + # If length of list is not equal to given width of matrix, it is incorrect + length = len(board[row]) + if length != x: + return "WRONG LENGTH" + + key_counter += 1 + + # Check if the keys are the same number as y + if key_counter != y: + return "WRONG X" + return "SUCCESS" + +def restrict_or_unrestrict(ip): + try: + ip = RestrictedIP.objects.get(ip=ip) + timedelta = datetime.utcnow().replace(tzinfo=UTC) - ip.time_added + # if banned for more than 1 minute, unban + if timedelta.seconds > 60: + ip.delete() + return "SUCESS" + return "STILL RESTRICTED" + except ObjectDoesNotExist: + instance = RestrictedIP(ip=ip, time_added=datetime.now()) + instance.save() + return "SUCCESS" + +# Internal board class +class localBoard: + def __init__(self) -> None: + try: + self.board = Board.objects.latest("update_time") + except ObjectDoesNotExist: + # Create a blank board + blank_config = {int(i): [-1 for _ in range(64)] for i in range(32)} + + # Time in YYYY-MM-DD HH:MM[:ss[.uuuuuu]][TZ] format + time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + instance = Board(update_time=time, configuration=blank_config) + instance.save() + self.board = Board.objects.latest("update_time") + + def getBoard(self) -> dict: + return dict(self.board.configuration) + + def setBoard(self, new_configuration:dict, ip) -> bool: + # Validate the board + if err := validateBoard(x=BOARD_X, y=BOARD_Y, board=new_configuration, ip=ip) != "SUCCESS": + return err + + # Save the board + instance = Board(update_time=datetime.now(), configuration=new_configuration) + instance.save() + self.board = Board.objects.latest("update_time") + return "SUCCESS" + + def HTML(self) -> str: + board = self.getBoard() + style = """ + + """ + + selected_pixel = f""" + + """ + reload_page = """ + + """ + html = f"Ballin{reload_page}{style}{selected_pixel}" + for row in board: + html += "" + x = 0 + for col in board[row]: + html += f"" + x += 1 + html += "" + html += "

<------ pick ur color

" + return html + +# Publicly visible functions +def update_board(request, x, y, color): + board = localBoard().getBoard() + try: + color = Color(color).hex + except Exception as e: + return HttpResponse(e) + board[str(y)][int(x)] = color + + ip = restrict_or_unrestrict(request.META["REMOTE_ADDR"]) + if ip != "SUCCESS": + return HttpResponse("RESTRICTED") + res = localBoard().setBoard(board, request.META["REMOTE_ADDR"]) + return HttpResponse(f"board: {str(res)}, ip: {ip}") + +def current_config(request): + html = localBoard().HTML() + return HttpResponse(html) + +def json_board(request): + board = localBoard().getBoard() + return JsonResponse(board) diff --git a/README.md b/README.md index 9dc4fc2..147f13e 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,6 @@ # hardware_projects -random electronincs projects repo \ No newline at end of file +random electronincs projects repo + +## ESP WROOM pinout +![Pinout](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fesp32io.com%2Fimages%2Ftutorial%2FESP-WROOM-32-Dev-Module-pinout.jpg&f=1&nofb=1&ipt=80e11059e9681730d3fdc8fa8c313ecf0d6305604c8b2e324392e15b1b0cce86&ipo=images) \ No newline at end of file diff --git a/led_strip_door/README.md b/led_strip_door/README.md new file mode 100644 index 0000000..c820818 --- /dev/null +++ b/led_strip_door/README.md @@ -0,0 +1 @@ +![WIRE](https://cdn.sparkfun.com/assets/learn_tutorials/7/9/0/Non_Addressable_LED_Strip_Simple_bb_Fritzing.png) \ No newline at end of file diff --git a/led_strip_door/led_strip_door.ino b/led_strip_door/led_strip_door.ino new file mode 100644 index 0000000..f7ea4b3 --- /dev/null +++ b/led_strip_door/led_strip_door.ino @@ -0,0 +1,41 @@ + +// Define the pins for the LED strip +#define RED 23 +#define GREEN 33 +#define BLUE 26 + + +void setup() { + // Set the pins as outputs + pinMode(RED, OUTPUT); + pinMode(GREEN, OUTPUT); + pinMode(BLUE, OUTPUT); + Serial.begin(9600); +} + +// Function that sets the color of the LED strip +void setColor(int red, int green, int blue) { + Serial.println("Setting color to: " + String(red) + ", " + String(green) + ", " + String(blue)); + +} + + + +void loop() { + // Set the color to red + setColor(255, 0, 0); + delay(1000); + // Set the color to green + setColor(0, 255, 0); + delay(1000); + // Set the color to blue + setColor(0, 0, 255); + delay(1000); + // Set the color to white + setColor(255, 255, 255); + delay(1000); + // Set the color to off + setColor(0, 0, 0); + delay(1000); +} + \ No newline at end of file