From 509b68f43d01cbce44b777747b8d7316e46dd1d6 Mon Sep 17 00:00:00 2001 From: Andrew Aikman Date: Wed, 24 Jan 2024 20:58:24 +0000 Subject: [PATCH] feat: Lint CI checks (#7) --- .github/workflows/lint.yml | 24 ++++++ .pre-commit-config.yaml | 26 +++++++ README.md | 41 +++++++--- insert_data.py | 11 --- manage.py | 6 +- pyproject.toml | 77 +++++++++++++++++++ shed_pi.egg-info/PKG-INFO | 22 +++--- shed_pi.egg-info/SOURCES.txt | 2 +- shed_pi.egg-info/dependency_links.txt | 1 - shedpi_hub_dashboard/apps.py | 4 +- .../migrations/0001_initial.py | 49 ++++++++---- shedpi_hub_dashboard/models.py | 1 + .../shedpi_hub_dashboard/dummy_data.json | 2 +- .../static/shedpi_hub_dashboard/js/index.js | 2 +- shedpi_hub_dashboard/tests.py | 2 - shedpi_hub_dashboard/urls.py | 2 +- shedpi_hub_dashboard/views.py | 2 - shedpi_hub_example_project/asgi.py | 2 +- shedpi_hub_example_project/settings.py | 74 +++++++++--------- shedpi_hub_example_project/urls.py | 14 ++-- shedpi_hub_example_project/wsgi.py | 2 +- temp_logger.py | 33 ++++---- 22 files changed, 276 insertions(+), 123 deletions(-) create mode 100644 .github/workflows/lint.yml create mode 100644 .pre-commit-config.yaml delete mode 100644 insert_data.py diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml new file mode 100644 index 0000000..23acf62 --- /dev/null +++ b/.github/workflows/lint.yml @@ -0,0 +1,24 @@ +name: Lint +on: + push: + branches-ignore: + - "release/**" + +jobs: + lint: + name: Lint code + runs-on: ubuntu-latest + + steps: + - name: Check out repo + uses: actions/checkout@v3 + + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: 3.11 + + - name: Pre-commit checks + run: | + pip install pre-commit==3.6.0 + pre-commit run --all-files diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml new file mode 100644 index 0000000..206db99 --- /dev/null +++ b/.pre-commit-config.yaml @@ -0,0 +1,26 @@ +# See https://pre-commit.com for more information +# See https://pre-commit.com/hooks.html for more hooks +default_language_version: + python: python3.11 + +repos: + - repo: https://github.com/pre-commit/pre-commit-hooks + rev: v4.5.0 + hooks: + - id: check-yaml + - id: check-added-large-files + - id: check-merge-conflict + - id: end-of-file-fixer + - id: detect-private-key + - id: trailing-whitespace + + - repo: https://github.com/astral-sh/ruff-pre-commit + rev: v0.1.14 + hooks: + - id: ruff + args: [--fix] + + - repo: https://github.com/psf/black + rev: 23.12.1 + hooks: + - id: black diff --git a/README.md b/README.md index 8301012..ccb3f1e 100644 --- a/README.md +++ b/README.md @@ -2,7 +2,7 @@ ## Introduction -A package to run a Raspberry Pi in an outbuilding such as a garden shed, for the internet of sheds. +A package to run a Raspberry Pi in an outbuilding such as a garden shed, for the internet of sheds. Automated use cases: - Weather station @@ -11,15 +11,15 @@ Automated use cases: ## TODO: 1. Fix: Bug: The script startup gets an incorrect time (Hasn't yet got the internet time) -2. Instructions on pinout +2. Instructions on pinout ### Wish list: - Poetry (Not started) - ASGI backend server (Daphne) - Native webcomponent FE with Bootstrap - pip install raspberry pi -- modular components that are easy to install from a software and hardware perspective -- Provide systemd script to 3rd parties +- modular components that are easy to install from a software and hardware perspective +- Provide systemd script to 3rd parties - venv is crucial before installing any third party packages! - Pre commit config with ci integration @@ -44,7 +44,7 @@ sudo raspi-config sudo reboot ``` -Sanity check that the 1 Wire data is available: +Sanity check that the 1 Wire data is available: ```shell ls /sys/bus/w1/devices/ @@ -57,30 +57,30 @@ cat /sys/bus/w1/devices/28-000003ebbf13/w1_slave ### Script auto start with systemd -Create a file in systemd +Create a file in systemd ```shell nano /lib/systemd/system/shed-pi.service ```` -With the contents +With the contents ```ini [Unit] Description=Shed-Pi After=multi-user.target StartLimitIntervalSec=0 - + [Service] Type=simple ExecStart=/usr/bin/python3 /home/shed-pi/temp_logger.py StandardInput=tty-force - + [Install] WantedBy=multi-user.target ``` -Enable the service, (CAVEAT: didn't work when manually starting, works on reboot) +Enable the service, (CAVEAT: didn't work when manually starting, works on reboot) ```shell sudo systemctl daemon-reload sudo systemctl enable shed-pi.service @@ -93,6 +93,25 @@ Read the logs tail -f /var/log/shed-pi.log ``` +## Development + +### Precommit + +Install pre-commit: https://pre-commit.com/ + +Configure precommit on your local git for the project by running the following at the root of the project: +```shell +pre-commit install +``` +Pre-commit will then automatically run for your changes at commit time. + + +To run the pre-commit config manually, run: +```shell +pre-commit run --all-files +``` + + ## Release Generate the release @@ -101,4 +120,4 @@ Generate the release pip install -q build python -m build twine upload dist/* -``` \ No newline at end of file +``` diff --git a/insert_data.py b/insert_data.py deleted file mode 100644 index 2a1f8c8..0000000 --- a/insert_data.py +++ /dev/null @@ -1,11 +0,0 @@ - - -import sqlite3 - -if __name__ == "__main__": - db = sqlite3.connect('database/database.db') - cursor = db.cursor() - values = (12.2, 14) - cursor.execute("INSERT INTO device_reading (device_temp, probe_temp) VALUES (:device_temp, :probe_temp)", values) - db.commit() - db.close() diff --git a/manage.py b/manage.py index 03c3dd9..4d2e9c2 100755 --- a/manage.py +++ b/manage.py @@ -6,7 +6,9 @@ def main(): """Run administrative tasks.""" - os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shedpi_hub_example_project.settings') + os.environ.setdefault( + "DJANGO_SETTINGS_MODULE", "shedpi_hub_example_project.settings" + ) try: from django.core.management import execute_from_command_line except ImportError as exc: @@ -18,5 +20,5 @@ def main(): execute_from_command_line(sys.argv) -if __name__ == '__main__': +if __name__ == "__main__": main() diff --git a/pyproject.toml b/pyproject.toml index 6c89601..62dc05d 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -20,3 +20,80 @@ classifiers = [ [project.urls] "Homepage" = "https://github.com/Aiky30/shed-pi" "Bug Tracker" = "https://github.com/Aiky30/shed-pi/issues" + +[tool.black] +exclude = ''' +/( + \.git + | \.hg + | \.mypy_cache + | \.tox + | \.venv + | _build + | build + | dist +)/ +''' + +[tool.ruff] +# Official documentation on ruff rules can be viewed here: https://beta.ruff.rs/docs/rules/ +# Please note that some pydocstyle rules do not work for the PEP257 docstring format this repo uses. Please view the +# official documentation for more information: https://www.pydocstyle.org/en/5.0.1/error_codes.html#default-conventions +select = [ + "F", # pyflakes + "E", # pycodestyle errors + "W", # pycodestyle warnings + "I", # isort + "N", # pep8-naming + #"D101", # pydocstyle: Missing docstring in public class + #"D102", # pydocstyle: Missing docstring in public method + #"D103", # pydocstyle: Missing docstring in public function + "D201", # pydocstyle: No blank lines allowed before function docstring (found {num_lines}) + "D202", # pydocstyle: No blank lines allowed after function docstring (found {num_lines}) + "D204", # pydocstyle: 1 blank line required after class docstring + "D206", # pydocstyle: Docstring should be indented with spaces, not tabs + "D207", # pydocstyle: Docstring is under-indented + "D208", # pydocstyle: Docstring is over-indented + "D209", # pydocstyle: Multi-line docstring closing quotes should be on a separate line + "D300", # pydocstyle: Use triple double quotes """ + "D403", # pydocstyle: First word of the first line should be properly capitalized + #"ANN001", # flake8-annotations: Missing type annotation for function argument {name} + #"ANN002", # flake8-annotations: Missing type annotation for *{name} + #"ANN003", # flake8-annotations: Missing type annotation for **{name} + #"ANN201", # flake8-annotations: Missing return type annotation for public function {name} + #"ANN202", # flake8-annotations: Missing return type annotation for private function {name} + #"ANN204", # flake8-annotations: Missing return type annotation for special method {name} + #"ANN205", # flake8-annotations: Missing return type annotation for staticmethod {name} + #"ANN206", # flake8-annotations: Missing return type annotation for classmethod {name} + "C4", # flake8-comprehensions + "DTZ", # flake8-datetimez + "ISC", # flake8-implicit-str-concat + "ICN", # flake8-import-conventions + "G", # flake8-logging-format + "INP", # flake8-no-pep420 + "PIE", # flake8-pie + #"T20", # flake8-print + "Q", # flake8-quotes + "SLF", # flake8-self + "SIM", # flake8-simplify + "PTH", # flake8-use-pathlib + "ERA", # eradicate + "RUF", # ruff-specific rules +] +ignore = [ + "G004", + "ERA001", + "PTH123", +] +exclude = [ + ".git", + ".pytest_cache", + ".ruff_cache", + ".venv", + ".gitignore", + ".github", + "migrations" +] +force-exclude = true +line-length = 120 +target-version = "py311" diff --git a/shed_pi.egg-info/PKG-INFO b/shed_pi.egg-info/PKG-INFO index 8243b01..0b9023c 100644 --- a/shed_pi.egg-info/PKG-INFO +++ b/shed_pi.egg-info/PKG-INFO @@ -15,7 +15,7 @@ Description-Content-Type: text/markdown ## Introduction -A package to run a Raspberry Pi in an outbuilding such as a garden shed, for the internet of sheds. +A package to run a Raspberry Pi in an outbuilding such as a garden shed, for the internet of sheds. Automated use cases: - Weather station @@ -24,15 +24,15 @@ Automated use cases: ## TODO: 1. Fix: Bug: The script startup gets an incorrect time (Hasn't yet got the internet time) -2. Instructions on pinout +2. Instructions on pinout ### Wish list: - Poetry (Not started) - ASGI backend server (Daphne) - Native webcomponent FE with Bootstrap - pip install raspberry pi -- modular components that are easy to install from a software and hardware perspective -- Provide systemd script to 3rd parties +- modular components that are easy to install from a software and hardware perspective +- Provide systemd script to 3rd parties - venv is crucial before installing any third party packages! - Pre commit config with ci integration @@ -57,7 +57,7 @@ sudo raspi-config sudo reboot ``` -Sanity check that the 1 Wire data is available: +Sanity check that the 1 Wire data is available: ```shell ls /sys/bus/w1/devices/ @@ -70,30 +70,30 @@ cat /sys/bus/w1/devices/28-000003ebbf13/w1_slave ### Script auto start with systemd -Create a file in systemd +Create a file in systemd ```shell nano /lib/systemd/system/shed-pi.service ```` -With the contents +With the contents ```ini [Unit] Description=Shed-Pi After=multi-user.target StartLimitIntervalSec=0 - + [Service] Type=simple ExecStart=/usr/bin/python3 /home/shed-pi/temp_logger.py StandardInput=tty-force - + [Install] WantedBy=multi-user.target ``` -Enable the service, (CAVEAT: didn't work when manually starting, works on reboot) +Enable the service, (CAVEAT: didn't work when manually starting, works on reboot) ```shell sudo systemctl daemon-reload sudo systemctl enable shed-pi.service @@ -105,5 +105,3 @@ Read the logs ```shell tail -f /var/log/shed-pi.log ``` - - diff --git a/shed_pi.egg-info/SOURCES.txt b/shed_pi.egg-info/SOURCES.txt index 338badd..6dae289 100644 --- a/shed_pi.egg-info/SOURCES.txt +++ b/shed_pi.egg-info/SOURCES.txt @@ -6,4 +6,4 @@ temp_logger.py shed_pi.egg-info/PKG-INFO shed_pi.egg-info/SOURCES.txt shed_pi.egg-info/dependency_links.txt -shed_pi.egg-info/top_level.txt \ No newline at end of file +shed_pi.egg-info/top_level.txt diff --git a/shed_pi.egg-info/dependency_links.txt b/shed_pi.egg-info/dependency_links.txt index 8b13789..e69de29 100644 --- a/shed_pi.egg-info/dependency_links.txt +++ b/shed_pi.egg-info/dependency_links.txt @@ -1 +0,0 @@ - diff --git a/shedpi_hub_dashboard/apps.py b/shedpi_hub_dashboard/apps.py index e9c9a69..c2c3e68 100644 --- a/shedpi_hub_dashboard/apps.py +++ b/shedpi_hub_dashboard/apps.py @@ -2,5 +2,5 @@ class ShedpiHubDashboardConfig(AppConfig): - default_auto_field = 'django.db.models.BigAutoField' - name = 'shedpi_hub_dashboard' + default_auto_field = "django.db.models.BigAutoField" + name = "shedpi_hub_dashboard" diff --git a/shedpi_hub_dashboard/migrations/0001_initial.py b/shedpi_hub_dashboard/migrations/0001_initial.py index 45fd30b..9478abe 100644 --- a/shedpi_hub_dashboard/migrations/0001_initial.py +++ b/shedpi_hub_dashboard/migrations/0001_initial.py @@ -6,30 +6,51 @@ class Migration(migrations.Migration): - initial = True - dependencies = [ - ] + dependencies = [] operations = [ migrations.CreateModel( - name='Device', + name="Device", fields=[ - ('id', models.UUIDField(default=uuid.uuid4, editable=False, primary_key=True, serialize=False)), - ('name', models.CharField(max_length=20)), - ('location', models.CharField(max_length=50)), + ( + "id", + models.UUIDField( + default=uuid.uuid4, + editable=False, + primary_key=True, + serialize=False, + ), + ), + ("name", models.CharField(max_length=20)), + ("location", models.CharField(max_length=50)), ], ), migrations.CreateModel( - name='DeviceReading', + name="DeviceReading", fields=[ - ('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), - ('device_temp', models.CharField(max_length=8)), - ('probe_temp', models.CharField(max_length=8)), - ('measurement_type', models.CharField(max_length=10)), - ('datetime', models.DateTimeField()), - ('device', models.ForeignKey(help_text='A device whose readings were collected.', on_delete=django.db.models.deletion.CASCADE, to='shedpi_hub_dashboard.device')), + ( + "id", + models.BigAutoField( + auto_created=True, + primary_key=True, + serialize=False, + verbose_name="ID", + ), + ), + ("device_temp", models.CharField(max_length=8)), + ("probe_temp", models.CharField(max_length=8)), + ("measurement_type", models.CharField(max_length=10)), + ("datetime", models.DateTimeField()), + ( + "device", + models.ForeignKey( + help_text="A device whose readings were collected.", + on_delete=django.db.models.deletion.CASCADE, + to="shedpi_hub_dashboard.device", + ), + ), ], ), ] diff --git a/shedpi_hub_dashboard/models.py b/shedpi_hub_dashboard/models.py index aa6e8e9..fb6bd45 100644 --- a/shedpi_hub_dashboard/models.py +++ b/shedpi_hub_dashboard/models.py @@ -1,4 +1,5 @@ import uuid + from django.db import models diff --git a/shedpi_hub_dashboard/static/shedpi_hub_dashboard/dummy_data.json b/shedpi_hub_dashboard/static/shedpi_hub_dashboard/dummy_data.json index 9b8a1ac..eedab2e 100644 --- a/shedpi_hub_dashboard/static/shedpi_hub_dashboard/dummy_data.json +++ b/shedpi_hub_dashboard/static/shedpi_hub_dashboard/dummy_data.json @@ -7,4 +7,4 @@ "humidity": "12" } ] -} \ No newline at end of file +} diff --git a/shedpi_hub_dashboard/static/shedpi_hub_dashboard/js/index.js b/shedpi_hub_dashboard/static/shedpi_hub_dashboard/js/index.js index 93de40d..df7d187 100644 --- a/shedpi_hub_dashboard/static/shedpi_hub_dashboard/js/index.js +++ b/shedpi_hub_dashboard/static/shedpi_hub_dashboard/js/index.js @@ -46,4 +46,4 @@ response = fetch(myRequest) }) .then((response) => { drawTable(response) - }); \ No newline at end of file + }); diff --git a/shedpi_hub_dashboard/tests.py b/shedpi_hub_dashboard/tests.py index 7ce503c..a39b155 100644 --- a/shedpi_hub_dashboard/tests.py +++ b/shedpi_hub_dashboard/tests.py @@ -1,3 +1 @@ -from django.test import TestCase - # Create your tests here. diff --git a/shedpi_hub_dashboard/urls.py b/shedpi_hub_dashboard/urls.py index 3c98bca..8ace68e 100644 --- a/shedpi_hub_dashboard/urls.py +++ b/shedpi_hub_dashboard/urls.py @@ -4,4 +4,4 @@ urlpatterns = [ path("", views.index), -] \ No newline at end of file +] diff --git a/shedpi_hub_dashboard/views.py b/shedpi_hub_dashboard/views.py index 1c221e3..2514c7f 100644 --- a/shedpi_hub_dashboard/views.py +++ b/shedpi_hub_dashboard/views.py @@ -1,5 +1,3 @@ -from django.shortcuts import render -from django.http import HttpResponse from django.template.response import TemplateResponse diff --git a/shedpi_hub_example_project/asgi.py b/shedpi_hub_example_project/asgi.py index e5f2d3a..c443233 100644 --- a/shedpi_hub_example_project/asgi.py +++ b/shedpi_hub_example_project/asgi.py @@ -11,6 +11,6 @@ from django.core.asgi import get_asgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shedpi_hub_example_project.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shedpi_hub_example_project.settings") application = get_asgi_application() diff --git a/shedpi_hub_example_project/settings.py b/shedpi_hub_example_project/settings.py index d71abf1..a57faf0 100644 --- a/shedpi_hub_example_project/settings.py +++ b/shedpi_hub_example_project/settings.py @@ -20,7 +20,7 @@ # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! -SECRET_KEY = 'django-insecure-np)5s8)r08sz9(-dg#vhlpo%0ixc9u)3rdyo4t9c9t=jiv#ult' +SECRET_KEY = "django-insecure-np)5s8)r08sz9(-dg#vhlpo%0ixc9u)3rdyo4t9c9t=jiv#ult" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True @@ -31,53 +31,53 @@ # Application definition INSTALLED_APPS = [ - 'django.contrib.admin', - 'django.contrib.auth', - 'django.contrib.contenttypes', - 'django.contrib.sessions', - 'django.contrib.messages', - 'django.contrib.staticfiles', - 'shedpi_hub_dashboard.apps.ShedpiHubDashboardConfig', + "django.contrib.admin", + "django.contrib.auth", + "django.contrib.contenttypes", + "django.contrib.sessions", + "django.contrib.messages", + "django.contrib.staticfiles", + "shedpi_hub_dashboard.apps.ShedpiHubDashboardConfig", ] 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', + "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 = 'shedpi_hub_example_project.urls' +ROOT_URLCONF = "shedpi_hub_example_project.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', + "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 = 'shedpi_hub_example_project.wsgi.application' +WSGI_APPLICATION = "shedpi_hub_example_project.wsgi.application" # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.sqlite3', - 'NAME': BASE_DIR / 'db.sqlite3', + "default": { + "ENGINE": "django.db.backends.sqlite3", + "NAME": BASE_DIR / "db.sqlite3", } } @@ -87,16 +87,16 @@ AUTH_PASSWORD_VALIDATORS = [ { - 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', + "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', + "NAME": "django.contrib.auth.password_validation.MinimumLengthValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', + "NAME": "django.contrib.auth.password_validation.CommonPasswordValidator", }, { - 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', + "NAME": "django.contrib.auth.password_validation.NumericPasswordValidator", }, ] @@ -104,9 +104,9 @@ # Internationalization # https://docs.djangoproject.com/en/5.0/topics/i18n/ -LANGUAGE_CODE = 'en-us' +LANGUAGE_CODE = "en-us" -TIME_ZONE = 'UTC' +TIME_ZONE = "UTC" USE_I18N = True @@ -116,7 +116,7 @@ # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/5.0/howto/static-files/ -STATIC_URL = 'static/' +STATIC_URL = "static/" # STATICFILES_DIRS = [ # BASE_DIR / "static", # "/var/www/static/", @@ -125,4 +125,4 @@ # Default primary key field type # https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field -DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' +DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField" diff --git a/shedpi_hub_example_project/urls.py b/shedpi_hub_example_project/urls.py index 0905473..232dc15 100644 --- a/shedpi_hub_example_project/urls.py +++ b/shedpi_hub_example_project/urls.py @@ -1,10 +1,12 @@ -from django.contrib import admin -from django.urls import path, include from django.conf import settings from django.conf.urls.static import static - +from django.contrib import admin +from django.urls import include, path urlpatterns = [ - path('admin/', admin.site.urls), - path("", include("shedpi_hub_dashboard.urls")), -] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) + *[ + path("admin/", admin.site.urls), + path("", include("shedpi_hub_dashboard.urls")), + ], + *static(settings.STATIC_URL, document_root=settings.STATIC_ROOT), +] diff --git a/shedpi_hub_example_project/wsgi.py b/shedpi_hub_example_project/wsgi.py index fca1d84..ddcb5c8 100644 --- a/shedpi_hub_example_project/wsgi.py +++ b/shedpi_hub_example_project/wsgi.py @@ -11,6 +11,6 @@ from django.core.wsgi import get_wsgi_application -os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'shedpi_hub_example_project.settings') +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "shedpi_hub_example_project.settings") application = get_wsgi_application() diff --git a/temp_logger.py b/temp_logger.py index bff7bec..3fa3f5d 100644 --- a/temp_logger.py +++ b/temp_logger.py @@ -1,14 +1,13 @@ +import logging import os -import glob import time -from datetime import datetime -import logging - +from datetime import datetime, timezone +from pathlib import Path logging.basicConfig( - filename='/var/log/shed-pi.log', + filename="/var/log/shed-pi.log", level=logging.INFO, - format='%(asctime)s:%(levelname)s:%(name)s:%(message)s' + format="%(asctime)s:%(levelname)s:%(name)s:%(message)s", ) logger = logging.getLogger("parent") TIME_TO_SLEEP = 60 # time in seconds @@ -16,25 +15,26 @@ class TempProbe: def __init__(self): - base_dir = '/sys/bus/w1/devices/' - device_folder = glob.glob(base_dir + '28*')[0] - self.device_file = device_folder + '/w1_slave' + base_dir = "/sys/bus/w1/devices/" + device_folder = Path.glob(base_dir + "28*")[0] + self.device_file = device_folder + "/w1_slave" def read_temp(self): def read_temp_raw(): - f = open(self.device_file, 'r') - lines = f.readlines() + with open(self.device_file, "r") as f: + lines = f.readlines() + f.close() return lines lines = read_temp_raw() - while lines[0].strip()[-3:] != 'YES': + while lines[0].strip()[-3:] != "YES": time.sleep(0.2) lines = read_temp_raw() - equals_pos = lines[1].find('t=') + equals_pos = lines[1].find("t=") if equals_pos != -1: - temp_string = lines[1][equals_pos + 2:] + temp_string = lines[1][equals_pos + 2 :] temp_c = float(temp_string) / 1000.0 return temp_c @@ -47,17 +47,16 @@ def get_cpu_temp(): cpu_temp = os.popen("vcgencmd measure_temp").readline() # Convert the temp read from the OS to a clean float - return float(cpu_temp.replace("temp=","").replace("'C\n", "")) + return float(cpu_temp.replace("temp=", "").replace("'C\n", "")) def get_time(): - now = datetime.now() + now = datetime.now(timezone.utc) current_time = now.strftime("%H:%M:%S") # 24-Hour:Minute:Second return current_time def main(): - logger.info(f"Shed pi started: {get_time()}, using version: 0.0.1") if not check_os():