mirror of
https://github.com/daniviga/bite.git
synced 2024-12-23 08:41:24 +01:00
Implement IoT device and hub
This commit is contained in:
parent
c38622eaaf
commit
9e39d4c7d2
94
arduino/tempLightSensor/tempLightSensor.ino
Normal file
94
arduino/tempLightSensor/tempLightSensor.ino
Normal file
@ -0,0 +1,94 @@
|
||||
#include <Ethernet.h>
|
||||
#include <ArduinoJson.h>
|
||||
|
||||
#define DEBUG_TO_SERIAL 1
|
||||
#define AREF_VOLTAGE 3.3
|
||||
|
||||
const String serverName = "sensor.server.domain";
|
||||
|
||||
const size_t capacity = JSON_OBJECT_SIZE(1) + 2*JSON_OBJECT_SIZE(6);
|
||||
DynamicJsonDocument doc(capacity);
|
||||
JsonObject payload = doc.createNestedObject("payload");
|
||||
JsonObject temp = payload.createNestedObject("temperature");
|
||||
|
||||
int tempPin = A0;
|
||||
int tempReading;
|
||||
int photocellPin = A1;
|
||||
int photocellReading;
|
||||
|
||||
const byte mac[] = {
|
||||
0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
|
||||
const byte remoteAddr[] = {
|
||||
192, 168, 10, 123 };
|
||||
const int remotePort = 8000;
|
||||
const int postDelay = 10*1000;
|
||||
|
||||
const String serialNum = "abcde12345";
|
||||
const String URL = "/telemetry/";
|
||||
|
||||
void printAddr(byte addr[], Stream *stream) {
|
||||
for (byte thisByte = 0; thisByte < 4; thisByte++) {
|
||||
// print the value of each byte of the IP address:
|
||||
stream->print(addr[thisByte], DEC);
|
||||
if (thisByte < 3) {
|
||||
stream->print(".");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void setup(void) {
|
||||
Serial.begin(9600);
|
||||
|
||||
analogReference(EXTERNAL);
|
||||
|
||||
if (Ethernet.begin(mac) == 0) {
|
||||
Serial.println("Failed to configure Ethernet using DHCP");
|
||||
// no point in carrying on, so do nothing forevermore:
|
||||
for(;;)
|
||||
;
|
||||
}
|
||||
|
||||
Serial.print("IoT started at address: ");
|
||||
printAddr(Ethernet.localIP(), &Serial);
|
||||
Serial.println();
|
||||
|
||||
doc["device"] = 1; // FIXME
|
||||
payload["id"] = serverName;
|
||||
}
|
||||
|
||||
void loop(void) {
|
||||
photocellReading = analogRead(photocellPin);
|
||||
tempReading = analogRead(tempPin);
|
||||
|
||||
float tempVoltage = tempReading * AREF_VOLTAGE / 1024.0;
|
||||
float tempC = (tempVoltage - 0.5) * 100 ;
|
||||
|
||||
payload["light"] = photocellReading;
|
||||
|
||||
temp["celsius"] = tempC;
|
||||
temp["raw"] = tempReading;
|
||||
temp["volts"] = tempVoltage;
|
||||
|
||||
if (EthernetClient client = client.connect(remoteAddr, remotePort)) {
|
||||
client.print("POST ");
|
||||
client.print(URL);
|
||||
client.println(" HTTP/1.1");
|
||||
client.print("Host: ");
|
||||
printAddr(remoteAddr, &client);
|
||||
client.print(":");
|
||||
client.println(remotePort);
|
||||
client.println("Content-Type: application/json");
|
||||
client.print("Content-Length: ");
|
||||
client.println(measureJsonPretty(doc));
|
||||
client.println("Connection: close");
|
||||
client.println();
|
||||
serializeJson(doc, client);
|
||||
client.stop();
|
||||
|
||||
#if DEBUG_TO_SERIAL
|
||||
serializeJsonPretty(doc, Serial);
|
||||
#endif
|
||||
}
|
||||
|
||||
delay(postDelay);
|
||||
}
|
@ -1 +1,25 @@
|
||||
# Placeholder
|
||||
version: "3.7"
|
||||
|
||||
networks:
|
||||
net:
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
|
||||
x-op-service-default: &service_default
|
||||
restart: unless-stopped
|
||||
init: true
|
||||
|
||||
services:
|
||||
timescale:
|
||||
<<: *service_default
|
||||
image: timescale/timescaledb:latest-pg12
|
||||
environment:
|
||||
POSTGRES_USER: "timescale"
|
||||
POSTGRES_PASSWORD: "password"
|
||||
volumes:
|
||||
- "pgdata:/var/lib/postgresql/data"
|
||||
networks:
|
||||
- net
|
||||
ports:
|
||||
- "127.0.0.1:5432:5432"
|
||||
|
0
freedcs/api/__init__.py
Normal file
0
freedcs/api/__init__.py
Normal file
32
freedcs/api/admin.py
Normal file
32
freedcs/api/admin.py
Normal file
@ -0,0 +1,32 @@
|
||||
from django.contrib import admin
|
||||
from api.models import Device, WhiteList
|
||||
|
||||
|
||||
@admin.register(Device)
|
||||
class DeviceAdmin(admin.ModelAdmin):
|
||||
readonly_fields = ('creation_time', 'updated_time',)
|
||||
|
||||
fieldsets = (
|
||||
(None, {
|
||||
'fields': ('serial', )
|
||||
}),
|
||||
('Audit', {
|
||||
'classes': ('collapse',),
|
||||
'fields': ('creation_time', 'updated_time',)
|
||||
}),
|
||||
)
|
||||
|
||||
|
||||
@admin.register(WhiteList)
|
||||
class WhiteListAdmin(admin.ModelAdmin):
|
||||
readonly_fields = ('creation_time', 'updated_time',)
|
||||
|
||||
fieldsets = (
|
||||
(None, {
|
||||
'fields': ('serial', 'is_published',)
|
||||
}),
|
||||
('Audit', {
|
||||
'classes': ('collapse',),
|
||||
'fields': ('creation_time', 'updated_time',)
|
||||
}),
|
||||
)
|
5
freedcs/api/apps.py
Normal file
5
freedcs/api/apps.py
Normal file
@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class ApiConfig(AppConfig):
|
||||
name = 'api'
|
33
freedcs/api/migrations/0001_initial.py
Normal file
33
freedcs/api/migrations/0001_initial.py
Normal file
@ -0,0 +1,33 @@
|
||||
# Generated by Django 3.0.6 on 2020-06-01 14:13
|
||||
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Device',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('serial', models.CharField(max_length=128, unique=True)),
|
||||
('creation_time', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_time', models.DateTimeField(auto_now=True)),
|
||||
],
|
||||
),
|
||||
migrations.CreateModel(
|
||||
name='WhiteList',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('serial', models.CharField(max_length=128, unique=True)),
|
||||
('creation_time', models.DateTimeField(auto_now_add=True)),
|
||||
('updated_time', models.DateTimeField(auto_now=True)),
|
||||
('is_published', models.BooleanField(default=True)),
|
||||
],
|
||||
),
|
||||
]
|
21
freedcs/api/migrations/0002_auto_20200601_1523.py
Normal file
21
freedcs/api/migrations/0002_auto_20200601_1523.py
Normal file
@ -0,0 +1,21 @@
|
||||
# Generated by Django 3.0.6 on 2020-06-01 15:23
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('api', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='device',
|
||||
options={'ordering': ['updated_time', 'serial']},
|
||||
),
|
||||
migrations.AlterModelOptions(
|
||||
name='whitelist',
|
||||
options={'ordering': ['serial', 'updated_time']},
|
||||
),
|
||||
]
|
0
freedcs/api/migrations/__init__.py
Normal file
0
freedcs/api/migrations/__init__.py
Normal file
35
freedcs/api/models.py
Normal file
35
freedcs/api/models.py
Normal file
@ -0,0 +1,35 @@
|
||||
from django.db import models
|
||||
from django.core.exceptions import ValidationError
|
||||
|
||||
|
||||
def device_validation(value):
|
||||
published_devices = WhiteList.objects.filter(serial=value,
|
||||
is_published=True)
|
||||
if not published_devices:
|
||||
raise ValidationError("Device is not published")
|
||||
|
||||
|
||||
class WhiteList(models.Model):
|
||||
serial = models.CharField(max_length=128, unique=True)
|
||||
creation_time = models.DateTimeField(auto_now_add=True)
|
||||
updated_time = models.DateTimeField(auto_now=True)
|
||||
is_published = models.BooleanField(default=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['serial', 'updated_time']
|
||||
|
||||
def __str__(self):
|
||||
return self.serial
|
||||
|
||||
|
||||
class Device(models.Model):
|
||||
serial = models.CharField(max_length=128, unique=True,
|
||||
validators=[device_validation])
|
||||
creation_time = models.DateTimeField(auto_now_add=True)
|
||||
updated_time = models.DateTimeField(auto_now=True)
|
||||
|
||||
class Meta:
|
||||
ordering = ['updated_time', 'serial']
|
||||
|
||||
def __str__(self):
|
||||
return self.serial
|
14
freedcs/api/serializers.py
Normal file
14
freedcs/api/serializers.py
Normal file
@ -0,0 +1,14 @@
|
||||
from rest_framework import serializers
|
||||
from api.models import Device, WhiteList
|
||||
|
||||
|
||||
class DeviceSerializer(serializers.ModelSerializer):
|
||||
class Meta:
|
||||
model = Device
|
||||
fields = ('serial', 'creation_time', 'updated_time',)
|
||||
|
||||
|
||||
# class WhiteListSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = Device
|
||||
# fields = ('serial', 'creation_time', 'updated_time',)
|
3
freedcs/api/tests.py
Normal file
3
freedcs/api/tests.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
1
freedcs/api/tests/sample.json
Normal file
1
freedcs/api/tests/sample.json
Normal file
@ -0,0 +1 @@
|
||||
{"serial": "abcde"}
|
23
freedcs/api/urls.py
Normal file
23
freedcs/api/urls.py
Normal file
@ -0,0 +1,23 @@
|
||||
"""freedcs URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/3.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.urls import path
|
||||
from api.views import APISubscribe
|
||||
|
||||
urlpatterns = [
|
||||
path('subscribe/',
|
||||
APISubscribe.as_view({'get': 'list', 'post': 'create'}),
|
||||
name='api_subscribe'),
|
||||
]
|
22
freedcs/api/views.py
Normal file
22
freedcs/api/views.py
Normal file
@ -0,0 +1,22 @@
|
||||
from rest_framework.viewsets import ModelViewSet
|
||||
|
||||
from api.models import Device
|
||||
from api.serializers import DeviceSerializer
|
||||
|
||||
|
||||
class APISubscribe(ModelViewSet):
|
||||
queryset = Device.objects.all()
|
||||
serializer_class = DeviceSerializer
|
||||
|
||||
# def post(self, request):
|
||||
# serializer = DeviceSerializer(data=request.data)
|
||||
# if serializer.is_valid():
|
||||
# serializer.save()
|
||||
# return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# def get(self, request):
|
||||
# devices = Device.objects.all()
|
||||
# import pdb; pdb.set_trace()
|
||||
# serializer = DeviceSerializer(devices)
|
||||
# return Response(serializer.serial)
|
@ -25,7 +25,7 @@ SECRET_KEY = 'i4z%50+4b4ek(l0#!w2-r1hpo%&r6tk7p$p_-(=6d!c9n=g5m&'
|
||||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
|
||||
ALLOWED_HOSTS = []
|
||||
ALLOWED_HOSTS = ['*']
|
||||
|
||||
|
||||
# Application definition
|
||||
@ -37,13 +37,16 @@ INSTALLED_APPS = [
|
||||
'django.contrib.sessions',
|
||||
'django.contrib.messages',
|
||||
'django.contrib.staticfiles',
|
||||
'rest_framework',
|
||||
'api',
|
||||
'telemetry',
|
||||
]
|
||||
|
||||
MIDDLEWARE = [
|
||||
'django.middleware.security.SecurityMiddleware',
|
||||
'django.contrib.sessions.middleware.SessionMiddleware',
|
||||
'django.middleware.common.CommonMiddleware',
|
||||
'django.middleware.csrf.CsrfViewMiddleware',
|
||||
# 'django.middleware.csrf.CsrfViewMiddleware',
|
||||
'django.contrib.auth.middleware.AuthenticationMiddleware',
|
||||
'django.contrib.messages.middleware.MessageMiddleware',
|
||||
'django.middleware.clickjacking.XFrameOptionsMiddleware',
|
||||
@ -75,8 +78,12 @@ WSGI_APPLICATION = 'freedcs.wsgi.application'
|
||||
|
||||
DATABASES = {
|
||||
'default': {
|
||||
'ENGINE': 'django.db.backends.sqlite3',
|
||||
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
|
||||
'ENGINE': 'django.db.backends.postgresql',
|
||||
'NAME': 'freedcs',
|
||||
'USER': 'freedcs',
|
||||
'PASSWORD': 'password',
|
||||
'HOST': '127.0.0.1',
|
||||
'PORT': '5432',
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -13,9 +13,15 @@ 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 django.urls import include, path
|
||||
|
||||
from api import urls as api_urls
|
||||
from telemetry import urls as telemetry_urls
|
||||
|
||||
urlpatterns = [
|
||||
path('admin/', admin.site.urls),
|
||||
path('api/', include(api_urls)),
|
||||
path('telemetry/', include(telemetry_urls)),
|
||||
]
|
||||
|
0
freedcs/telemetry/__init__.py
Normal file
0
freedcs/telemetry/__init__.py
Normal file
7
freedcs/telemetry/admin.py
Normal file
7
freedcs/telemetry/admin.py
Normal file
@ -0,0 +1,7 @@
|
||||
from django.contrib import admin
|
||||
from telemetry.models import Telemetry
|
||||
|
||||
|
||||
@admin.register(Telemetry)
|
||||
class TelemetryAdmin(admin.ModelAdmin):
|
||||
readonly_fields = ('device', 'time', 'payload',)
|
5
freedcs/telemetry/apps.py
Normal file
5
freedcs/telemetry/apps.py
Normal file
@ -0,0 +1,5 @@
|
||||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class TelemetryConfig(AppConfig):
|
||||
name = 'telemetry'
|
26
freedcs/telemetry/migrations/0001_initial.py
Normal file
26
freedcs/telemetry/migrations/0001_initial.py
Normal file
@ -0,0 +1,26 @@
|
||||
# Generated by Django 3.0.6 on 2020-06-01 14:45
|
||||
|
||||
import django.contrib.postgres.fields.jsonb
|
||||
from django.db import migrations, models
|
||||
import django.db.models.deletion
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
('api', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='Telemetry',
|
||||
fields=[
|
||||
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('time', models.DateTimeField(auto_now_add=True)),
|
||||
('payload', django.contrib.postgres.fields.jsonb.JSONField()),
|
||||
('device', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='api.Device')),
|
||||
],
|
||||
),
|
||||
]
|
17
freedcs/telemetry/migrations/0002_auto_20200601_1557.py
Normal file
17
freedcs/telemetry/migrations/0002_auto_20200601_1557.py
Normal file
@ -0,0 +1,17 @@
|
||||
# Generated by Django 3.0.6 on 2020-06-01 15:57
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('telemetry', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.AlterModelOptions(
|
||||
name='telemetry',
|
||||
options={'ordering': ['time', 'device']},
|
||||
),
|
||||
]
|
13
freedcs/telemetry/migrations/0003_auto_20200601_1710.py
Normal file
13
freedcs/telemetry/migrations/0003_auto_20200601_1710.py
Normal file
@ -0,0 +1,13 @@
|
||||
# Generated by Django 3.0.6 on 2020-06-01 17:10
|
||||
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('telemetry', '0002_auto_20200601_1557'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
]
|
0
freedcs/telemetry/migrations/__init__.py
Normal file
0
freedcs/telemetry/migrations/__init__.py
Normal file
17
freedcs/telemetry/models.py
Normal file
17
freedcs/telemetry/models.py
Normal file
@ -0,0 +1,17 @@
|
||||
from django.db import models
|
||||
from django.contrib.postgres.fields import JSONField
|
||||
|
||||
from api.models import Device
|
||||
|
||||
|
||||
class Telemetry(models.Model):
|
||||
device = models.ForeignKey(Device, on_delete=models.CASCADE)
|
||||
time = models.DateTimeField(auto_now_add=True)
|
||||
payload = JSONField()
|
||||
|
||||
class Meta:
|
||||
ordering = ['time', 'device']
|
||||
verbose_name_plural = "Telemetry"
|
||||
|
||||
def __str__(self):
|
||||
return "%s - %s" % (self.time, self.device.serial)
|
20
freedcs/telemetry/serializers.py
Normal file
20
freedcs/telemetry/serializers.py
Normal file
@ -0,0 +1,20 @@
|
||||
from rest_framework import serializers
|
||||
from api.serializers import DeviceSerializer
|
||||
from telemetry.models import Telemetry
|
||||
|
||||
|
||||
class TelemetrySerializer(serializers.ModelSerializer):
|
||||
# device = DeviceSerializer(read_only=True)
|
||||
|
||||
def validate(self, data):
|
||||
return data
|
||||
|
||||
class Meta:
|
||||
model = Telemetry
|
||||
fields = ('device', 'time', 'payload',)
|
||||
|
||||
|
||||
# class WhiteListSerializer(serializers.ModelSerializer):
|
||||
# class Meta:
|
||||
# model = Device
|
||||
# fields = ('serial', 'creation_time', 'updated_time',)
|
3
freedcs/telemetry/tests.py
Normal file
3
freedcs/telemetry/tests.py
Normal file
@ -0,0 +1,3 @@
|
||||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
11
freedcs/telemetry/tests/sample.json
Normal file
11
freedcs/telemetry/tests/sample.json
Normal file
@ -0,0 +1,11 @@
|
||||
{"device": 1,
|
||||
"payload": {
|
||||
"id": "sensor.server.domain",
|
||||
"light": 434,
|
||||
"temperature": {
|
||||
"celsius": 27.02149,
|
||||
"raw": 239,
|
||||
"volts": 0.770215
|
||||
}
|
||||
}
|
||||
}
|
23
freedcs/telemetry/urls.py
Normal file
23
freedcs/telemetry/urls.py
Normal file
@ -0,0 +1,23 @@
|
||||
"""freedcs URL Configuration
|
||||
|
||||
The `urlpatterns` list routes URLs to views. For more information please see:
|
||||
https://docs.djangoproject.com/en/3.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.urls import path
|
||||
from telemetry.views import Telemetry
|
||||
|
||||
urlpatterns = [
|
||||
path('',
|
||||
Telemetry.as_view({'get': 'list', 'post': 'create'}),
|
||||
name='telemetry'),
|
||||
]
|
22
freedcs/telemetry/views.py
Normal file
22
freedcs/telemetry/views.py
Normal file
@ -0,0 +1,22 @@
|
||||
from rest_framework.viewsets import ModelViewSet
|
||||
|
||||
from telemetry.models import Telemetry
|
||||
from telemetry.serializers import TelemetrySerializer
|
||||
|
||||
|
||||
class Telemetry(ModelViewSet):
|
||||
queryset = Telemetry.objects.all()
|
||||
serializer_class = TelemetrySerializer
|
||||
|
||||
# def post(self, request):
|
||||
# serializer = DeviceSerializer(data=request.data)
|
||||
# if serializer.is_valid():
|
||||
# serializer.save()
|
||||
# return Response(serializer.data, status=status.HTTP_201_CREATED)
|
||||
# return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
|
||||
|
||||
# def get(self, request):
|
||||
# devices = Device.objects.all()
|
||||
# import pdb; pdb.set_trace()
|
||||
# serializer = DeviceSerializer(devices)
|
||||
# return Response(serializer.serial)
|
@ -1 +1,3 @@
|
||||
Django
|
||||
djangorestframework
|
||||
psycopg2-binary
|
||||
|
Loading…
Reference in New Issue
Block a user