From 98e13ee2fb26b1bf95b312f31f4d65b826c53f1c Mon Sep 17 00:00:00 2001 From: ahmetkotan Date: Mon, 28 Jan 2019 03:09:01 +0300 Subject: [PATCH] ready rest --- .gitignore | 8 ++ manage.py | 22 +++++ picontrol/__init__.py | 0 picontrol/control.py | 83 ++++++++++++++++++ pins/__init__.py | 0 pins/admin.py | 3 + pins/apps.py | 5 ++ pins/migrations/__init__.py | 0 pins/models.py | 3 + pins/pagination.py | 32 +++++++ pins/serializers.py | 42 +++++++++ pins/tests.py | 3 + pins/urls.py | 7 ++ pins/views.py | 51 +++++++++++ restpi/__init__.py | 0 restpi/settings/__init__.py | 9 ++ restpi/settings/local.py | 3 + restpi/settings/pin_settings.py | 63 ++++++++++++++ restpi/settings/prod.py | 2 + restpi/settings/shared.py | 146 ++++++++++++++++++++++++++++++++ restpi/urls.py | 24 ++++++ restpi/wsgi.py | 16 ++++ 22 files changed, 522 insertions(+) create mode 100644 .gitignore create mode 100755 manage.py create mode 100644 picontrol/__init__.py create mode 100644 picontrol/control.py create mode 100644 pins/__init__.py create mode 100644 pins/admin.py create mode 100644 pins/apps.py create mode 100644 pins/migrations/__init__.py create mode 100644 pins/models.py create mode 100644 pins/pagination.py create mode 100644 pins/serializers.py create mode 100644 pins/tests.py create mode 100644 pins/urls.py create mode 100644 pins/views.py create mode 100644 restpi/__init__.py create mode 100644 restpi/settings/__init__.py create mode 100644 restpi/settings/local.py create mode 100644 restpi/settings/pin_settings.py create mode 100644 restpi/settings/prod.py create mode 100644 restpi/settings/shared.py create mode 100644 restpi/urls.py create mode 100644 restpi/wsgi.py diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..854f5ab --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +build/* +.idea/* +*.egg-info/* +dist/ +.DS_Store +*.pyc +*.sqlite3 +*.db \ No newline at end of file diff --git a/manage.py b/manage.py new file mode 100755 index 0000000..b120934 --- /dev/null +++ b/manage.py @@ -0,0 +1,22 @@ +#!/usr/bin/env python +import os +import sys + +if __name__ == "__main__": + os.environ.setdefault("DJANGO_SETTINGS_MODULE", "restpi.settings") + try: + from django.core.management import execute_from_command_line + except ImportError: + # The above import may fail for some other reason. Ensure that the + # issue is really that Django is missing to avoid masking other + # exceptions on Python 2. + try: + import django + except ImportError: + 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?" + ) + raise + execute_from_command_line(sys.argv) diff --git a/picontrol/__init__.py b/picontrol/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/picontrol/control.py b/picontrol/control.py new file mode 100644 index 0000000..c76e05e --- /dev/null +++ b/picontrol/control.py @@ -0,0 +1,83 @@ +from django.conf import settings +from rest_framework.exceptions import ValidationError + +import RPi.GPIO as gpio + + +def pin_physical_control(physical): + if type(physical) != int: + raise ValidationError({"physical": "Wrong pin number."}) + + if physical > 40 and physical < 1: + raise ValidationError({"physical": "Wrong pin number."}) + +def get_pin(physical): + pins = settings.PINS + + for pin in pins: + if pin["physical"] == physical: + return pin + +def read_pin(physical): + physical = int(physical) + + pin_physical_control(physical) + pin = get_pin(physical) + + pin_mode = gpio.gpio_function(physical) + if pin_mode == 1: + pin_setup = gpio.IN + elif pin_mode == 0: + pin_setup = gpio.OUT + + + gpio.setup(physical, pin_setup) + pin_value = gpio.input(physical) + pin["value"] = pin_value + pin["mode"] = pin_mode + pin["hr_mode"] = settings.PORT_MODES[pin_mode] + pin["hr_value"] = settings.PORT_VALUES[pin_value] + + return pin + +def read_all_pin(): + ports = settings.BOARD_PORTS + + for port in ports: + read_pin(port) + + return settings.PINS + +def write_pin_mode(physical, mode): + physical = int(physical) + pin_physical_control(physical) + + if mode == gpio.OUT: + new_mode = gpio.OUT + elif mode == gpio.IN: + new_mode = gpio.IN + else: + raise ValidationError({"mode": "Wrong mode."}) + + gpio.setup(physical, new_mode) + return read_pin(physical) + + +def write_pin_value(physical, value): + physical = int(physical) + pin_physical_control(physical) + + if value == 1: + new_value = gpio.HIGH + elif value == 0: + new_value = gpio.LOW + else: + raise ValidationError({"value": "Wrong value."}) + + pin = read_pin(physical) + if pin["mode"] == gpio.OUT: + gpio.setup(physical, gpio.OUT) + gpio.output(physical, new_value) + return read_pin(physical) + else: + raise ValidationError({"mode": "Pin's mode is not OUT."}) diff --git a/pins/__init__.py b/pins/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pins/admin.py b/pins/admin.py new file mode 100644 index 0000000..8c38f3f --- /dev/null +++ b/pins/admin.py @@ -0,0 +1,3 @@ +from django.contrib import admin + +# Register your models here. diff --git a/pins/apps.py b/pins/apps.py new file mode 100644 index 0000000..cbcbc00 --- /dev/null +++ b/pins/apps.py @@ -0,0 +1,5 @@ +from django.apps import AppConfig + + +class PinsConfig(AppConfig): + name = 'pins' diff --git a/pins/migrations/__init__.py b/pins/migrations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/pins/models.py b/pins/models.py new file mode 100644 index 0000000..d49766e --- /dev/null +++ b/pins/models.py @@ -0,0 +1,3 @@ +from django.db import models + +# Create your models here. \ No newline at end of file diff --git a/pins/pagination.py b/pins/pagination.py new file mode 100644 index 0000000..ea690c8 --- /dev/null +++ b/pins/pagination.py @@ -0,0 +1,32 @@ +from rest_framework.settings import api_settings +from rest_framework.views import APIView + +class PaginationAPIView(APIView): + pagination_class = api_settings.DEFAULT_PAGINATION_CLASS + + @property + def paginator(self): + """ + The paginator instance associated with the view, or `None`. + """ + if not hasattr(self, '_paginator'): + if self.pagination_class is None: + self._paginator = None + else: + self._paginator = self.pagination_class() + return self._paginator + + def paginate_queryset(self, queryset): + """ + Return a single page of results, or `None` if pagination is disabled. + """ + if self.paginator is None: + return None + return self.paginator.paginate_queryset(queryset, self.request, view=self) + + def get_paginated_response(self, data): + """ + Return a paginated style `Response` object for the given output data. + """ + assert self.paginator is not None + return self.paginator.get_paginated_response(data) \ No newline at end of file diff --git a/pins/serializers.py b/pins/serializers.py new file mode 100644 index 0000000..34bdc2f --- /dev/null +++ b/pins/serializers.py @@ -0,0 +1,42 @@ +from django.core.validators import MaxValueValidator, MinValueValidator +from rest_framework import serializers + +class PinSerializer(serializers.Serializer): + physical = serializers.IntegerField( + label="Pin Physical Number", + validators=[MaxValueValidator(40), MinValueValidator(1)], + ) + + hr_mode = serializers.CharField( + max_length=12, + label="Human Readable Pin Mode", + read_only=True + ) + + hr_value = serializers.CharField( + max_length=4, + label="Human Readable Pin Value", + read_only=True + ) + + mode = serializers.IntegerField( + validators=[MaxValueValidator(1), MinValueValidator(0)], + label="Pin Mode", + required=False + ) + + name = serializers.CharField( + max_length=7, + label="Pin Name", + read_only=True + ) + + value = serializers.IntegerField( + label="Pin Value", + required=False + ) + + BCM = serializers.IntegerField( + label="Pin BCM Number", + read_only=True + ) diff --git a/pins/tests.py b/pins/tests.py new file mode 100644 index 0000000..7ce503c --- /dev/null +++ b/pins/tests.py @@ -0,0 +1,3 @@ +from django.test import TestCase + +# Create your tests here. diff --git a/pins/urls.py b/pins/urls.py new file mode 100644 index 0000000..598d07c --- /dev/null +++ b/pins/urls.py @@ -0,0 +1,7 @@ +from django.conf.urls import url, include + +from pins.views import PinView + +urlpatterns = [ + url(r'pins/(?P\d*)', PinView.as_view()), +] \ No newline at end of file diff --git a/pins/views.py b/pins/views.py new file mode 100644 index 0000000..9311b93 --- /dev/null +++ b/pins/views.py @@ -0,0 +1,51 @@ +from django.shortcuts import render + +from rest_framework.response import Response + +# Create your views here. + +from picontrol.control import read_pin, read_all_pin, write_pin_value, write_pin_mode +from pins.pagination import PaginationAPIView +from pins.serializers import PinSerializer + +class PinView(PaginationAPIView): + serializer_class = PinSerializer + + def get(self, request, pin=None): + if pin: + pin = int(pin) + response = read_pin(pin) + + return Response(data=response) + else: + queryset = read_all_pin() + page = self.paginate_queryset(queryset) + if page is not None: + return self.get_paginated_response(page) + + serializer = self.serializer_class(queryset, many=True) + return Response(serializer.data) + + def post(self, request, pin=None): + if not pin: + return Response({"physical": "No pin number."}) + + serializer = self.serializer_class(data=request.data) + serializer.is_valid(raise_exception=True) + + mode = serializer.validated_data.pop("mode", None) + value = serializer.validated_data.pop("value", None) + physical = serializer.validated_data.pop("physical") + + if mode is None and value is None: + response = {"operation": False, "pin": read_pin(physical)} + return Response(data=response) + + if mode is not None: + response = write_pin_mode(physical, mode) + + if value is not None: + response = write_pin_value(physical, value) + data = {"operation": True, "pin": response} + return Response(data=data) + diff --git a/restpi/__init__.py b/restpi/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/restpi/settings/__init__.py b/restpi/settings/__init__.py new file mode 100644 index 0000000..61df4f9 --- /dev/null +++ b/restpi/settings/__init__.py @@ -0,0 +1,9 @@ +from .shared import * + +try: + from .local import * +except: + from .prod import * + + +from .pin_settings import * \ No newline at end of file diff --git a/restpi/settings/local.py b/restpi/settings/local.py new file mode 100644 index 0000000..2335e33 --- /dev/null +++ b/restpi/settings/local.py @@ -0,0 +1,3 @@ +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = True +print("Local mode online") \ No newline at end of file diff --git a/restpi/settings/pin_settings.py b/restpi/settings/pin_settings.py new file mode 100644 index 0000000..fe8298d --- /dev/null +++ b/restpi/settings/pin_settings.py @@ -0,0 +1,63 @@ +from RPi.GPIO import * + +PINS = [ + {"physical": 1, "name": "3.3v", "mode": None, "value": None, "BCM": None}, + {"physical": 2, "name": "5v", "mode": None, "value": None, "BCM": None}, + {"physical": 3, "name": "SDA.1", "mode": None, "value": None, "BCM": 2}, + {"physical": 4, "name": "5v", "mode": None, "value": None, "BCM": None}, + {"physical": 5, "name": "SCL.1", "mode": None, "value": None, "BCM": 3}, + {"physical": 6, "name": "0v", "mode": None, "value": None}, + {"physical": 7, "name": "GPIO.7", "mode": None, "value": None, "BCM": 4}, + {"physical": 8, "name": "TxD", "mode": "ALT0", "value": None, "BCM": 14}, + {"physical": 9, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 10, "name": "RxD", "mode": "ALT0", "value": None, "BCM": 15}, + {"physical": 11, "name": "GPIO.0", "mode": None, "value": None, "BCM": 17}, + {"physical": 12, "name": "GPIO.1", "mode": None, "value": None, "BCM": 18}, + {"physical": 13, "name": "GPIO.2", "mode": None, "value": None, "BCM": 27}, + {"physical": 14, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 15, "name": "GPIO.3", "mode": None, "value": None, "BCM": 22}, + {"physical": 16, "name": "GPIO.4", "mode": None, "value": None, "BCM": 23}, + {"physical": 17, "name": "3.3v", "mode": None, "value": None, "BCM": None}, + {"physical": 18, "name": "GPIO.5", "mode": None, "value": None, "BCM": 24}, + {"physical": 19, "name": "MOSI", "mode": None, "value": None, "BCM": 10}, + {"physical": 20, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 21, "name": "MISO", "mode": None, "value": None, "BCM": 9}, + {"physical": 22, "name": "GPIO.6", "mode": None, "value": None, "BCM": 25}, + {"physical": 23, "name": "SCLK", "mode": None, "value": None, "BCM": 11}, + {"physical": 24, "name": "CE0", "mode": None, "value": None, "BCM": 8}, + {"physical": 25, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 26, "name": "CE1", "mode": None, "value": None, "BCM": 7}, + {"physical": 27, "name": "SDA.0", "mode": None, "value": None, "BCM": 0}, + {"physical": 28, "name": "SCL.0", "mode": None, "value": None, "BCM": 1}, + {"physical": 29, "name": "GPIO.21", "mode": None, "value": None, "BCM": 5}, + {"physical": 30, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 31, "name": "GPIO.22", "mode": None, "value": None, "BCM": 6}, + {"physical": 32, "name": "GPIO.26", "mode": None, "value": None, "BCM": 12}, + {"physical": 33, "name": "GPIO.23", "mode": None, "value": None, "BCM": 13}, + {"physical": 34, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 35, "name": "GPIO.24", "mode": None, "value": None, "BCM": 19}, + {"physical": 36, "name": "GPIO.27", "mode": None, "value": None, "BCM": 16}, + {"physical": 37, "name": "GPIO.25", "mode": None, "value": None, "BCM": 26}, + {"physical": 38, "name": "GPIO.28", "mode": None, "value": None, "BCM": 20}, + {"physical": 39, "name": "0v", "mode": None, "value": None, "BCM": None}, + {"physical": 40, "name": "GPIO.29", "mode": None, "value": None, "BCM": 21}, +] + +BOARD_PORTS = [3, 5, 7, 8, 10, 11, 12, 13, 15, 16, 18, 19, 21, 22, 23, 24, 26, 29, 31, 32, 33, 35, 36, 37, 38, 40] +PORT_MODES = { + OUT: "OUT", + IN: "IN", + SERIAL: "SERIAL(ALT0)", + SPI: "SPI", + I2C: "I2C", + HARD_PWM: "HARD_PWM", + UNKNOWN: "UNKNOWN" +} + +PORT_VALUES = { + HIGH: "HIGH", + LOW: "LOW" +} + +setmode(BOARD) +setwarnings(False) \ No newline at end of file diff --git a/restpi/settings/prod.py b/restpi/settings/prod.py new file mode 100644 index 0000000..5016877 --- /dev/null +++ b/restpi/settings/prod.py @@ -0,0 +1,2 @@ +# SECURITY WARNING: don't run with debug turned on in production! +DEBUG = False \ No newline at end of file diff --git a/restpi/settings/shared.py b/restpi/settings/shared.py new file mode 100644 index 0000000..217be29 --- /dev/null +++ b/restpi/settings/shared.py @@ -0,0 +1,146 @@ +""" +Django settings for restpi project. + +Generated by 'django-admin startproject' using Django 1.11. + +For more information on this file, see +https://docs.djangoproject.com/en/1.11/topics/settings/ + +For the full list of settings and their values, see +https://docs.djangoproject.com/en/1.11/ref/settings/ +""" + +import os + +# Build paths inside the project like this: os.path.join(BASE_DIR, ...) +BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + + +# Quick-start development settings - unsuitable for production +# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ + +# SECURITY WARNING: keep the secret key used in production secret! +SECRET_KEY = 'k_p(!8*ltmsr+++wt5ip=xah%8b^g$go+n6nnx*+p46=se7&l6' + +ALLOWED_HOSTS = ['*'] + + +# Application definition + +INSTALLED_APPS = [ + 'django.contrib.admin', + 'django.contrib.auth', + 'django.contrib.contenttypes', + 'django.contrib.sessions', + 'django.contrib.messages', + 'django.contrib.staticfiles', + + 'pins', + + # 3rd party + 'rest_framework', + 'tokenauth' +] + +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 = 'restpi.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 = 'restpi.wsgi.application' + + +# Database +# https://docs.djangoproject.com/en/1.11/ref/settings/#databases + +DATABASES = { + 'default': { + 'ENGINE': 'django.db.backends.sqlite3', + 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), + } +} + + +# Password validation +# https://docs.djangoproject.com/en/1.11/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/1.11/topics/i18n/ + +LANGUAGE_CODE = 'en-us' + +TIME_ZONE = 'UTC' + +USE_I18N = True + +USE_L10N = True + +USE_TZ = True + + +# Static files (CSS, JavaScript, Images) +# https://docs.djangoproject.com/en/1.11/howto/static-files/ + +STATIC_URL = '/static/' + +# Rest Framework +REST_FRAMEWORK = { + 'DEFAULT_PERMISSION_CLASSES': ( + 'rest_framework.permissions.IsAuthenticated', + ), + 'DEFAULT_AUTHENTICATION_CLASSES': ( + 'rest_framework.authentication.BasicAuthentication', + 'tokenauth.auth.TokenAuthentication', + ), + 'DEFAULT_PARSER_CLASSES': ( + 'rest_framework.parsers.JSONParser', + 'rest_framework.parsers.FormParser', + 'rest_framework.parsers.MultiPartParser', + ), + 'DEFAULT_RENDERER_CLASSES': ( + 'rest_framework.renderers.JSONRenderer', + 'rest_framework.renderers.BrowsableAPIRenderer', + ), + 'DEFAULT_FILTER_BACKENDS': ('django_filters.rest_framework.DjangoFilterBackend',), + 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', + 'PAGE_SIZE': 40, +} diff --git a/restpi/urls.py b/restpi/urls.py new file mode 100644 index 0000000..c10505f --- /dev/null +++ b/restpi/urls.py @@ -0,0 +1,24 @@ +"""restpi URL Configuration + +The `urlpatterns` list routes URLs to views. For more information please see: + https://docs.djangoproject.com/en/1.11/topics/http/urls/ +Examples: +Function views + 1. Add an import: from my_app import views + 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') +Class-based views + 1. Add an import: from other_app.views import Home + 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') +Including another URLconf + 1. Import the include() function: from django.conf.urls import url, include + 2. Add a URL to urlpatterns: url(r'^blog/', include('blog.urls')) +""" +from django.conf.urls import url, include +from django.contrib import admin + +urlpatterns = [ + url(r'^admin/', admin.site.urls), + + url(r'', include('tokenauth.urls')), + url(r'', include('pins.urls')), +] diff --git a/restpi/wsgi.py b/restpi/wsgi.py new file mode 100644 index 0000000..63a599b --- /dev/null +++ b/restpi/wsgi.py @@ -0,0 +1,16 @@ +""" +WSGI config for restpi 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/1.11/howto/deployment/wsgi/ +""" + +import os + +from django.core.wsgi import get_wsgi_application + +os.environ.setdefault("DJANGO_SETTINGS_MODULE", "restpi.settings") + +application = get_wsgi_application()