Odprta koda 2019. Web aplikacija Sensor.
Samo Penic
2019-04-11 fe4f05bd544255b4874ac8e60d2095a7a0b69dd4
Spremembe narejene na zadnji delavnici.
14 files added
9 files modified
257 ■■■■ changed files
ARDUINO/DigitalReadSerial/DigitalReadSerial.ino 14 ●●●●● patch | view | raw | blame | history
ARDUINO/serial_read.py 9 ●●●●● patch | view | raw | blame | history
Pipfile 2 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/__init__.py patch | view | raw | blame | history
djsenzor/calculator/admin.py 3 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/apps.py 5 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/forms.py 5 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/migrations/__init__.py patch | view | raw | blame | history
djsenzor/calculator/models.py 3 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/templates/calculator/sestej.html 18 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/tests.py 3 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/urls.py 5 ●●●●● patch | view | raw | blame | history
djsenzor/calculator/views.py 24 ●●●●● patch | view | raw | blame | history
djsenzor/db.sqlite3 patch | view | raw | blame | history
djsenzor/djsenzor/settings.py 17 ●●●● patch | view | raw | blame | history
djsenzor/djsenzor/urls.py 3 ●●●● patch | view | raw | blame | history
djsenzor/sensorui/admin.py 8 ●●●●● patch | view | raw | blame | history
djsenzor/sensorui/migrations/0001_initial.py 48 ●●●●● patch | view | raw | blame | history
djsenzor/sensorui/models.py 26 ●●●●● patch | view | raw | blame | history
djsenzor/sensorui/static/sensorui/muca.jpg patch | view | raw | blame | history
djsenzor/sensorui/templates/sensorui/index.html 19 ●●●● patch | view | raw | blame | history
djsenzor/sensorui/urls.py 4 ●●● patch | view | raw | blame | history
djsenzor/sensorui/views.py 41 ●●●●● patch | view | raw | blame | history
ARDUINO/DigitalReadSerial/DigitalReadSerial.ino
New file
@@ -0,0 +1,14 @@
void setup() {
  Serial.begin(9600);
}
long randNo;
// the loop routine runs over and over again forever:
void loop() {
  randNo=random(10,40);
  Serial.println(randNo);
  delay(1000);        // delay in between reads for stability
}
ARDUINO/serial_read.py
New file
@@ -0,0 +1,9 @@
import serial
import io
ser=serial.Serial('/dev/ttyUSB0',9600,timeout=10)
while True:
    ret=ser.readline()
    print(ret.decode('ascii').strip())
ser.close()
Pipfile
@@ -5,6 +5,8 @@
[packages]
django = "*"
djangorestframework = "*"
mysqlclient = "*"
[dev-packages]
djsenzor/calculator/__init__.py
djsenzor/calculator/admin.py
New file
@@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.
djsenzor/calculator/apps.py
New file
@@ -0,0 +1,5 @@
from django.apps import AppConfig
class CalculatorConfig(AppConfig):
    name = 'calculator'
djsenzor/calculator/forms.py
New file
@@ -0,0 +1,5 @@
from django import forms
class Stevila(forms.Form):
    a=forms.FloatField()
    b=forms.FloatField()
djsenzor/calculator/migrations/__init__.py
djsenzor/calculator/models.py
New file
@@ -0,0 +1,3 @@
from django.db import models
# Create your models here.
djsenzor/calculator/templates/calculator/sestej.html
New file
@@ -0,0 +1,18 @@
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sestej stevili</title>
</head>
<body>
<p>Sestej stevili</p>
<form method="POST">
    {{ formular.as_p }}
{% csrf_token %}
    <button type="submit">Poslji</button>
</form>
<hr />
<p>Vsota je: {{ vsota }}</p>
</body>
</html>
djsenzor/calculator/tests.py
New file
@@ -0,0 +1,3 @@
from django.test import TestCase
# Create your tests here.
djsenzor/calculator/urls.py
New file
@@ -0,0 +1,5 @@
from django.urls import path
from . import views
urlpatterns = [
    path('sestej', views.sestej, name='sestej'),
]
djsenzor/calculator/views.py
New file
@@ -0,0 +1,24 @@
from django.shortcuts import render
from django.http import HttpResponse
from .forms import Stevila
# Create your views here.
def sestej(request):
    form=Stevila()
    vsota="NaN"
    if request.method == "POST":
        print(request.POST['a'])
        form=Stevila(request.POST)
        if form.is_valid():
            vsota=float(form.data['a'])+float(form.data['b'])
            print(form.data)
    #form=Stevila()
    return render(request, 'calculator/sestej.html', context={'formular':form, 'vsota':vsota})
djsenzor/db.sqlite3
Binary files differ
djsenzor/djsenzor/settings.py
@@ -25,7 +25,7 @@
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
ALLOWED_HOSTS = ['localhost', 'moja.domena.si']
# Application definition
@@ -37,7 +37,9 @@
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sensorui.apps'
    'sensorui',
    'calculator',
    'rest_framework'
]
MIDDLEWARE = [
@@ -76,8 +78,14 @@
DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
#        'ENGINE': 'django.db.backends.sqlite3',
#        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'samo',
        'USER': 'samo',
        'PASSWORD': 'samo',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}
@@ -119,3 +127,4 @@
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'static/')
djsenzor/djsenzor/urls.py
@@ -18,5 +18,6 @@
urlpatterns = [
    path('admin/', admin.site.urls),
    path('sensorui/', include('sensorui.urls'))
    path('sensorui/', include('sensorui.urls')),
    path('calculator/', include('calculator.urls'))
]
djsenzor/sensorui/admin.py
@@ -1,3 +1,11 @@
from django.contrib import admin
# Register your models here.
from .models import *
admin.site.register(Measurement)
admin.site.register(Sensor)
admin.site.register(SensorType)
djsenzor/sensorui/migrations/0001_initial.py
New file
@@ -0,0 +1,48 @@
# Generated by Django 2.1.7 on 2019-03-25 17:17
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
    initial = True
    dependencies = [
    ]
    operations = [
        migrations.CreateModel(
            name='Measurement',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('value', models.FloatField()),
                ('timestamp', models.DateTimeField(auto_now_add=True)),
            ],
        ),
        migrations.CreateModel(
            name='Sensor',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=30)),
            ],
        ),
        migrations.CreateModel(
            name='SensorType',
            fields=[
                ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
                ('name', models.CharField(max_length=30)),
                ('unit', models.CharField(max_length=10)),
            ],
        ),
        migrations.AddField(
            model_name='sensor',
            name='sensor_type',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='sensorui.SensorType'),
        ),
        migrations.AddField(
            model_name='measurement',
            name='sensor_id',
            field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='sensorui.Sensor'),
        ),
    ]
djsenzor/sensorui/models.py
@@ -1,3 +1,29 @@
from django.db import models
# Create your models here.
class SensorType(models.Model):
    name = models.CharField(max_length=30)
    unit = models.CharField(max_length=10)
    def __str__(self):
        return self.name
class Sensor(models.Model):
    sensor_type = models.ForeignKey(SensorType, on_delete=models.CASCADE)
    name = models.CharField(max_length=30)
    def __str__(self):
        return self.name
class Measurement(models.Model):
    sensor_id = models.ForeignKey(Sensor, on_delete=models.CASCADE)
    value = models.FloatField()
    timestamp = models.DateTimeField(auto_now_add=True)
    def __str__(self):
        return "{} {} {} {}".format(self.sensor_id, self.value, self.sensor_id.sensor_type.unit, self.timestamp)
djsenzor/sensorui/static/sensorui/muca.jpg
djsenzor/sensorui/templates/sensorui/index.html
@@ -1,11 +1,24 @@
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello world stran</title>
<script>
    function myFunction(){
        var xhttp = new XMLHttpRequest();
        xhttp.open("GET","my-ajax-test/", true);
        xhttp.send();
    }
</script>
</head>
<body>
<h1>hello world</h1>
<img src='{% static "sensorui/muca.jpg" %}'>
<button onclick="myFunction()">Vzgi lucko</button>
sin(pi/2)={{ sinpi2 }}
<hr />
Zahtevek podal: {{ moje_ime }}
@@ -19,9 +32,9 @@
</tr>
    {% for row in data_table %}
<tr>
  <td>{{ row.sensor_id }}</td>
  <td>{{ row.data }}</td>
  <td>{{ row.date }}</td>
  <td>{{ row.sensor_id.pk }}</td>
  <td>{{ row.value }}{{ row.sensor_id.sensor_type.unit }}</td>
  <td>{{ row.timestamp }}</td>
</tr>
    {% endfor %}
</table>
djsenzor/sensorui/urls.py
@@ -17,5 +17,7 @@
from django.urls import path
from . import views
urlpatterns = [
    path('', views.index, name='index'),
    path('<int:pk>', views.index, name='index'),
    path('api/measurement', views.SensorData.as_view(), name='measurement'),
    path('my-ajax-test/', views.myajaxtestview, name='ajax-test-view'),
]
djsenzor/sensorui/views.py
@@ -1,37 +1,42 @@
from django.shortcuts import render
from .models import *
from django.http.response import HttpResponse
# Create your views here.
from math import pi, sin
from rest_framework.views import APIView
from rest_framework.response import Response
def index(request):
class SensorData(APIView):
    def post(self, request):
        data=request.data
        m=Measurement(sensor_id=Sensor.objects.get(pk=data['sensor_id']), value=data['value'])
        m.save()
        return Response(None)
def index(request, pk):
    sinpi2=sin(pi/2)
    intlist=list(range(1,11))
    moj_template='sensorui/index.html'
    data_table=[]
    measurements=Measurement.objects.filter(sensor_id=pk).all()
    data_table.append({'sensor_id':1,
                       'data': 10.0,
                       'date': '10.10.1010'
                       })
    data_table.append({'sensor_id':1,
                       'data': 8.0,
                       'date': '11.10.1010'
                       })
    data_table.append({'sensor_id':1,
                       'data': 12.0,
                       'date': '11.11.1010'
                       })
    context={
        'sinpi2':sinpi2,
        'moje_ime': "Samo Penic",
        'intlist': intlist,
        'data_table': data_table,
        'data_table': measurements,
    }
    return render(request, moj_template, context)
def myajaxtestview(request):
    print("AJAX REQUEST")
    rezultat=(int(request.GET['a'])+int(request.GET['b']))
    return HttpResponse(rezultat)