thunic 2 years ago
commit f222776476

2
.gitignore vendored

@ -2,3 +2,5 @@ SQLHandler/config.json
.vscode/arduino.json .vscode/arduino.json
.gitignore .gitignore
.vscode/c_cpp_properties.json .vscode/c_cpp_properties.json
venv/
**/__pycache__/

@ -0,0 +1,7 @@
from django.contrib import admin
from api.models import *
admin.site.register(Client)
admin.site.register(Temperature)
admin.site.register(Moisture)
admin.site.register(WaterLevel)

@ -0,0 +1,6 @@
from django.apps import AppConfig
class ApiConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'api'

@ -0,0 +1,51 @@
# Generated by Django 5.0.3 on 2024-03-28 20:45
import django.db.models.deletion
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Clients',
fields=[
('id', models.AutoField(auto_created=True, editable=False, primary_key=True, serialize=False)),
('hostname', models.CharField(max_length=100, unique=True)),
('created_at', models.DateTimeField(auto_now_add=True)),
],
),
migrations.CreateModel(
name='Moisture',
fields=[
('id', models.AutoField(auto_created=True, editable=False, primary_key=True, serialize=False)),
('moisture', models.IntegerField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.clients')),
],
),
migrations.CreateModel(
name='Temperature',
fields=[
('id', models.AutoField(auto_created=True, editable=False, primary_key=True, serialize=False)),
('temperature', models.FloatField()),
('humidity', models.FloatField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.clients')),
],
),
migrations.CreateModel(
name='WaterLevel',
fields=[
('id', models.AutoField(auto_created=True, editable=False, primary_key=True, serialize=False)),
('waterlevel', models.IntegerField()),
('created_at', models.DateTimeField(auto_now_add=True)),
('created_by', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.clients')),
],
),
]

@ -0,0 +1,49 @@
from django.db import models
class Client(models.Model):
id = models.AutoField(primary_key=True, auto_created=True, editable=False)
hostname = models.CharField(unique=True, max_length=100)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['id']
def __str__(self):
return f'{self.id}: {self.hostname} - {self.created_at}'
class Temperature(models.Model):
id = models.AutoField(primary_key=True, auto_created=True, editable=False)
temperature = models.FloatField()
humidity = models.FloatField()
created_by = models.ForeignKey(Client, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['id']
def __str__(self):
return f'{self.id}: {self.temperature}°C and {self.humidity}% - {self.created_at}'
class Moisture(models.Model):
id = models.AutoField(primary_key=True, auto_created=True, editable=False)
moisture = models.IntegerField()
created_by = models.ForeignKey(Client, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['id']
def __str__(self):
return f'{self.id}: {self.moisture} - {self.created_at}'
class WaterLevel(models.Model):
id = models.AutoField(primary_key=True, auto_created=True, editable=False)
waterlevel = models.IntegerField()
created_by = models.ForeignKey(Client, on_delete=models.CASCADE)
created_at = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['id']
def __str__(self):
return f'{self.id}: {self.waterlevel} - {self.created_at}'

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,9 @@
from django.urls import path
from api import views
urlpatterns = [
path('client/', views.client, name='api-client'),
path('temperature/', views.temperature, name='api-temperature'),
path('moisture/', views.moisture, name='api-moisture'),
path('waterlevel/', views.waterlevel, name='api-waterlevel'),
]

@ -0,0 +1,52 @@
from django.shortcuts import render
from rest_framework import status
from rest_framework.response import Response
from rest_framework.decorators import api_view
from api.models import *
# ----------------------------------------------------------------------------------------------- #
@api_view(['POST'])
def client(request):
try:
Client.objects.get(hostname=request.data['hostname'])
except Client.DoesNotExist:
temp = Client(
hostname=request.data['hostname']
)
temp.save()
return Response(status=status.HTTP_201_CREATED)
return Response(status=status.HTTP_200_OK)
# ----------------------------------------------------------------------------------------------- #
@api_view(['POST'])
def temperature(request):
client = Client.objects.get(hostname=request.data['hostname'])
temp = Temperature(
temperature=request.data["temperature"],
humidity=request.data["humidity"],
created_by=client
)
temp.save()
return Response(status=status.HTTP_201_CREATED)
# ----------------------------------------------------------------------------------------------- #
@api_view(['POST'])
def moisture(request):
client = Client.objects.get(hostname=request.data['hostname'])
temp = Moisture(
moisture=request.data['moistrue'],
created_by=client
)
temp.save()
return Response(status=status.HTTP_201_CREATED)
# ----------------------------------------------------------------------------------------------- #
@api_view(['POST'])
def waterlevel(request):
client = Client.objects.get(hostname=request.data['hostname'])
temp = WaterLevel(
waterlevel=request.data['waterlevel'],
created_by=client
)
temp.save()
return Response(status=status.HTTP_201_CREATED)

@ -0,0 +1,16 @@
"""
ASGI config for core 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/5.0/howto/deployment/asgi/
"""
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_asgi_application()

@ -0,0 +1,130 @@
"""
Django settings for core project.
Generated by 'django-admin startproject' using Django 5.0.3.
For more information on this file, see
https://docs.djangoproject.com/en/5.0/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/5.0/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/5.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-(6h_gl6)e$xf3^^ds6-iyjxa^kbgr51%tu79urm1lrl31ov%65'
# 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',
'rest_framework',
'api',
'userinterface',
]
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 = 'core.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 = 'core.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',
}
}
# Password validation
# https://docs.djangoproject.com/en/5.0/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/5.0/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/5.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/5.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

@ -0,0 +1,24 @@
"""
URL configuration for core project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/5.0/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, include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include('api.urls')),
path('', include('userinterface.urls')),
]

@ -0,0 +1,16 @@
"""
WSGI config for core 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/5.0/howto/deployment/wsgi/
"""
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'core.settings')
application = get_wsgi_application()

Binary file not shown.

@ -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', 'core.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()

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

@ -0,0 +1,6 @@
from django.apps import AppConfig
class UserinterfaceConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'userinterface'

@ -0,0 +1,3 @@
from django.db import models
# Create your models here.

@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.

@ -0,0 +1,6 @@
from django.urls import path
from userinterface import views
urlpatterns = [
path('', views.home, name='home'),
]

@ -0,0 +1,5 @@
from django.shortcuts import render
from django.http import HttpResponse
def home(request):
return HttpResponse('Hello World!')

Binary file not shown.
Loading…
Cancel
Save