SwapStation_WebApp/backend/models.py

44 lines
1.9 KiB
Python

from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.dialects.postgresql import JSONB
from werkzeug.security import generate_password_hash, check_password_hash
# Create a SQLAlchemy instance. This will be linked to the Flask app in main.py.
db = SQLAlchemy()
class User(db.Model):
"""Represents a user in the database."""
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
password_hash = db.Column(db.String(256), nullable=False)
is_admin = db.Column(db.Boolean, default=False, nullable=False)
def set_password(self, password):
"""Creates a secure hash of the password."""
self.password_hash = generate_password_hash(password)
def check_password(self, password):
"""Checks if the provided password matches the stored hash."""
return check_password_hash(self.password_hash, password)
class Station(db.Model):
"""Represents a battery swap station in the database."""
id = db.Column(db.Integer, primary_key=True)
station_id = db.Column(db.String(120), unique=True, nullable=False)
product_id = db.Column(db.String(80), unique=True, nullable=False)
name = db.Column(db.String(120), nullable=True)
location = db.Column(db.String(200), nullable=True)
mqtt_broker = db.Column(db.String(255), nullable=False)
mqtt_port = db.Column(db.Integer, nullable=False)
mqtt_user = db.Column(db.String(120), nullable=True)
mqtt_password = db.Column(db.String(120), nullable=True)
class MqttLog(db.Model):
"""Represents a single MQTT message payload for historical logging."""
id = db.Column(db.Integer, primary_key=True)
timestamp = db.Column(db.DateTime, server_default=db.func.now())
station_id = db.Column(db.String(120), nullable=False, index=True)
topic = db.Column(db.String(255), nullable=False)
topic_type = db.Column(db.String(50), nullable=False, index=True)
payload = db.Column(JSONB)