Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ node_modules/
*.db*
*.log
.eslintrc.*
.env

requirements-dev.txt
tilix.json
79 changes: 70 additions & 9 deletions NodeMCU/AdvancedWS_Node/AdvancedWS_Node.ino
Original file line number Diff line number Diff line change
Expand Up @@ -23,10 +23,14 @@ DHT dht(DHTPin, DHTTYPE);
WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, NTP_ADDRESS, NTP_OFFSET, NTP_INTERVAL);

const char *host = "192.168.0.106";
const int led = D7;
const char *host = "192.168.0.106";
const int httpPort = 5000;
const int led = D7;

int estacao = 1;
String versao = "1.2";
String token = "";

int estacao = 1;
int ldrPin = A0;
int tmp = 80;
int ldrValor = 0;
Expand Down Expand Up @@ -110,12 +114,14 @@ void EncontraValor(String str1, String str2, String str3, int inicio, int fim, i
if (str2 == "Pressao") {
pos = str1.indexOf("Pressao", 0);
Serial.println(pos);
if (pos > 0)
if (pos > 0) {
str1 = str1.substring(pos);
Serial.println(str1);
}
else if (pos == 0) {
temp = str1.substring(1);
pos = temp.indexOf("Pressao", 0);
if (pos >= 0) {
if (pos > 0) {
Serial.println(pos);
str1 = temp.substring(pos);
}
Expand All @@ -140,7 +146,6 @@ void EncontraValor(String str1, String str2, String str3, int inicio, int fim, i

void EnviaDados(float valor, String tipo, int estacao) {
WiFiClient client;
const int httpPort = 5000;
timeClient.update();

if (!client.connect(host, httpPort)) {
Expand All @@ -151,17 +156,32 @@ void EnviaDados(float valor, String tipo, int estacao) {
String formattedTime = timeClient.getFormattedTime();
unsigned long epcohTime = timeClient.getEpochTime();

data = "{\"valor\": " + String(valor) + ", \"datahora\": " + String(epcohTime) + "}";

client.println("POST /api/v1.1/sensor/" + String(estacao) + "/" + tipo + " HTTP/1.1");
data = "{\"valor\": " + String(valor) + ", \"datahora\": " + String(epcohTime) + "}";
/*
json=
{
"valor": 304.00,
"datahora": 1607109786
},
headers=
{
"Authorization": "jwt eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJleHAiOjE2MDcxOTI0NzUsImlhdCI6MTYwNzEwNjA3NSwibmJmIjoxNjA3MTA2MDc1LCJpZGVudGl0eSI6MX0.gpFQ_KaX0DFd3ps8VHK7E5ly5L0doueUSbaYptgQVHI"
}
*/
client.println("POST /api/v" + versao + "/sensor/" + String(estacao) + "/" + tipo + " HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Accept: */*");
client.println("Content-Type: application/json");
client.print("Authorization: ");
client.println(token);
client.print("Content-Length: ");
client.println(data.length());

client.println();
client.print(data);

Serial.println(token);
Serial.println(data);

delay(20); // Can be changed
Expand All @@ -171,6 +191,43 @@ void EnviaDados(float valor, String tipo, int estacao) {
delay(20);
}

String RecebeToken() {
WiFiClient client;
String line, token2;

if (!client.connect(host, httpPort)) {
Serial.println("connection failed");
return "Erro ao conectar";
}

data = "{\"email\": \"admin@gmail.com\", \"password\": \"12345678\"}";

client.println("POST /token HTTP/1.1");
client.print("Host: ");
client.println(host);
client.println("Accept: */*");
client.println("Content-Type: application/json");
client.print("Content-Length: ");
client.println(data.length());
client.println();
client.print(data);

delay(20); // Can be changed
while (client.connected()) {
if (client.available()) {
line = client.readStringUntil('\n');
if (line.indexOf("HTTP", 0) > 0) {
Serial.print("[Response:]");
Serial.println(line.substring(0, 15));
}
if (line.indexOf("access_token", 0) > 0)
token2 = "\"jwt " + line.substring(line.indexOf("access_token", 0)+16);
}
}
delay(20);
return token2;
}

void setup() {
Serial.begin(115200);

Expand All @@ -188,6 +245,10 @@ void setup() {

dht.begin();

token = RecebeToken();
Serial.print("Token: ");
Serial.println(token);

digitalWrite(led, HIGH);
delay(100);
digitalWrite(led, LOW);
Expand Down
File renamed without changes.
4 changes: 2 additions & 2 deletions prototipo/Vagrantfile → Vagrantfile
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,12 @@ Vagrant.configure("2") do |config|
# config.vm.network "private_network", ip: "192.168.33.10"
config.vm.network "public_network"

config.vm.synced_folder "./", "/vagrant_data"
config.vm.synced_folder "./prototipo", "/vagrant_data"

config.vm.provider "virtualbox" do |vb|
vb.name = "focal64_flaskAPI"
vb.gui = false
vb.memory = "2048"
vb.memory = "1024"
end

config.vm.provision :shell, :path => "Vagrant-setup/bootstrap.sh"
Expand Down
File renamed without changes.
File renamed without changes.
5 changes: 2 additions & 3 deletions prototipo/migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,8 @@
import logging
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context
from sqlalchemy import engine_from_config, pool

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
Expand All @@ -22,6 +20,7 @@
# from myapp import mymodel
# target_metadata = mymodel.Base.metadata
from flask import current_app

config.set_main_option(
'sqlalchemy.url',
str(current_app.extensions['migrate'].db.engine.url).replace('%', '%%'))
Expand Down
29 changes: 29 additions & 0 deletions prototipo/migrations/versions/175235720f56_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""empty message

Revision ID: 175235720f56
Revises: 61fd7b1a6054
Create Date: 2020-12-14 13:59:25.369944

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = '175235720f56'
down_revision = '61fd7b1a6054'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('estacao', sa.Column('created_on', sa.DateTime(), nullable=True))
op.add_column('estacao', sa.Column('updated_on', sa.DateTime(), nullable=True))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('estacao', 'updated_on')
op.drop_column('estacao', 'created_on')
# ### end Alembic commands ###
3 changes: 1 addition & 2 deletions prototipo/migrations/versions/3eeb4ae85a13_.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
Create Date: 2020-11-16 16:11:48.278616

"""
from alembic import op
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = '3eeb4ae85a13'
Expand Down
3 changes: 1 addition & 2 deletions prototipo/migrations/versions/61fd7b1a6054_.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
Create Date: 2020-11-30 14:31:27.250926

"""
from alembic import op
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = '61fd7b1a6054'
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,8 @@
Create Date: 2020-11-16 16:05:42.270171

"""
from alembic import op
import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = '8384895bb7ff'
Expand Down
44 changes: 44 additions & 0 deletions prototipo/migrations/versions/bb88fe255549_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""empty message

Revision ID: bb88fe255549
Revises: 175235720f56
Create Date: 2020-12-15 20:37:21.871157

"""
import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision = 'bb88fe255549'
down_revision = '175235720f56'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('sensor_tipo',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('codigo', sa.String(length=255), nullable=False),
sa.Column('descricao', sa.String(length=255), nullable=False),
sa.Column('params', sa.String(length=255), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('codigo')
)
op.add_column('sensor', sa.Column('tipo_id', sa.Integer(), nullable=False))
op.create_foreign_key(None, 'sensor', 'sensor_tipo', ['tipo_id'], ['id'])
op.drop_column('sensor', 'tipo')
op.drop_column('sensor', 'params')
op.drop_column('sensor', 'descricao')
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('sensor', sa.Column('descricao', sa.VARCHAR(length=255), autoincrement=False, nullable=False))
op.add_column('sensor', sa.Column('params', sa.VARCHAR(length=255), autoincrement=False, nullable=False))
op.add_column('sensor', sa.Column('tipo', sa.VARCHAR(length=255), autoincrement=False, nullable=False))
op.drop_constraint(None, 'sensor', type_='foreignkey')
op.drop_column('sensor', 'tipo_id')
op.drop_table('sensor_tipo')
# ### end Alembic commands ###
12 changes: 1 addition & 11 deletions prototipo/projeto/app.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,12 @@
from datetime import timedelta

from flask import Flask

from projeto.ext import admin, api, auth, db, jwt, site


def create_app():
app = Flask(__name__)

app.config[
"SQLALCHEMY_DATABASE_URI"] = "postgresql://" + \
"flaskapi:flaskapi@localhost:5432/flaskapi"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False
app.config["SECRET_KEY"] = "super-secret-key"
app.config["JWT_AUTH_USERNAME_KEY"] = "email"
app.config["JWT_AUTH_URL_RULE"] = "/token"
app.config["JWT_EXPIRATION_DELTA"] = timedelta(seconds=86400) # one day
app.config["FLASK_ADMIN_SWATCH"] = "sandstone"
app.config.from_object("projeto.config.DevConfig")

db.init_app(app)
api.init_app(app)
Expand Down
37 changes: 37 additions & 0 deletions prototipo/projeto/config.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import os
from datetime import timedelta
from dotenv import load_dotenv

basedir = os.path.abspath(os.path.dirname(__file__))
load_dotenv(os.path.join(basedir, ".env"), verbose=True)


class BaseConfig:
"""Base configs"""

DEBUG = False
TESTING = False
SECRET_KEY = os.getenv("SECRET_KEY")
STATIC_FOLDER = "static"
TEMPLATE_FOLDER = "templates"
SQLALCHEMY_TRACK_MODIFICATIONS = False
JWT_AUTH_USERNAME_KEY = "email"
JWT_AUTH_URL_RULE = "/token"
JWT_EXPIRATION_DELTA = timedelta(seconds=86400) # one day
FLASK_ADMIN_SWATCH = "sandstone"


class ProdConfig(BaseConfig):
"""Production configs"""

FLASK_ENV = "production"
SQLALCHEMY_DATABASE_URI = os.getenv("PROD_DATABASE_URI")


class DevConfig(BaseConfig):
"""Development configs"""

FLASK_ENV = "development"
DEBUG = True
TESTING = True
SQLALCHEMY_DATABASE_URI = os.getenv("DEV_DATABASE_URI")
5 changes: 3 additions & 2 deletions prototipo/projeto/ext/admin/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from flask_admin import Admin
from projeto.ext.admin.views import EstacaoView, SensorView, UserView
from projeto.ext.api.models import Estacao, Sensor
from projeto.ext.admin.views import EstacaoView, SensorView, SensorTipoView, UserView
from projeto.ext.api.models import Estacao, Sensor, SensorTipo
from projeto.ext.auth.models import UserAuth
from projeto.ext.db import db

Expand All @@ -12,6 +12,7 @@ def init_app(app):
views = [
UserView(UserAuth, db.session),
EstacaoView(Estacao, db.session),
SensorTipoView(SensorTipo, db.session),
SensorView(Sensor, db.session),
]
admin.add_views(*views)
15 changes: 13 additions & 2 deletions prototipo/projeto/ext/admin/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,14 +19,25 @@ class UserView(AdminView):
column_list = ("id", "email", "is_admin")
column_sortable_list = ()

can_create = True
can_delete = True
can_edit = False


class EstacaoView(AdminView):
column_list = ("id", "local", "latitude", "longitude")
column_list = ("id", "local", "latitude", "longitude", "created_on",
"updated_on")
form_excluded_columns = ("created_on", "updated_on")
column_sortable_list = ()


class SensorTipoView(AdminView):
# column_list = ("id", "codigo", "descricao", "params")
column_sortable_list = ()


class SensorView(AdminView):
column_list = ("id", "tipo", "descricao", "params", "estacao")
# column_list = ("id", "tipo", "estacao")
column_sortable_list = ()

form_excluded_columns = [
Expand Down
Loading