kopia lustrzana https://github.com/ahmetkotan/restpi
ready rest
commit
98e13ee2fb
|
@ -0,0 +1,8 @@
|
|||
build/*
|
||||
.idea/*
|
||||
*.egg-info/*
|
||||
dist/
|
||||
.DS_Store
|
||||
*.pyc
|
||||
*.sqlite3
|
||||
*.db
|
|
@ -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)
|
|
@ -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."})
|
|
@ -0,0 +1,3 @@
|
|||
from django.contrib import admin
|
||||
|
||||
# Register your models here.
|
|
@ -0,0 +1,5 @@
|
|||
from django.apps import AppConfig
|
||||
|
||||
|
||||
class PinsConfig(AppConfig):
|
||||
name = 'pins'
|
|
@ -0,0 +1,3 @@
|
|||
from django.db import models
|
||||
|
||||
# Create your models here.
|
|
@ -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)
|
|
@ -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
|
||||
)
|
|
@ -0,0 +1,3 @@
|
|||
from django.test import TestCase
|
||||
|
||||
# Create your tests here.
|
|
@ -0,0 +1,7 @@
|
|||
from django.conf.urls import url, include
|
||||
|
||||
from pins.views import PinView
|
||||
|
||||
urlpatterns = [
|
||||
url(r'pins/(?P<pin>\d*)', PinView.as_view()),
|
||||
]
|
|
@ -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)
|
||||
|
|
@ -0,0 +1,9 @@
|
|||
from .shared import *
|
||||
|
||||
try:
|
||||
from .local import *
|
||||
except:
|
||||
from .prod import *
|
||||
|
||||
|
||||
from .pin_settings import *
|
|
@ -0,0 +1,3 @@
|
|||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = True
|
||||
print("Local mode online")
|
|
@ -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)
|
|
@ -0,0 +1,2 @@
|
|||
# SECURITY WARNING: don't run with debug turned on in production!
|
||||
DEBUG = False
|
|
@ -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,
|
||||
}
|
|
@ -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')),
|
||||
]
|
|
@ -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()
|
Ładowanie…
Reference in New Issue