Initial commit: ICU Patient Display Management System
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
FROM python:3.12-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
default-libmysqlclient-dev \
|
||||
pkg-config \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt .
|
||||
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
COPY . .
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,51 @@
|
||||
from datetime import timedelta
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordRequestForm
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.core.security import verify_password, create_access_token
|
||||
from app.schemas.user import Token, UserResponse, UserCreate
|
||||
from app.services.user_service import user_service
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter(prefix="/api/auth", tags=["auth"])
|
||||
|
||||
@router.post("/login", response_model=Token)
|
||||
async def login_for_access_token(
|
||||
form_data: OAuth2PasswordRequestForm = Depends(),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
user = await user_service.get_user_by_email(db, email=form_data.username)
|
||||
if not user or not verify_password(form_data.password, user.hashed_password):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Incorrect email or password",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
access_token_expires = timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
access_token = create_access_token(
|
||||
data={"sub": user.email, "role": user.role.value},
|
||||
expires_delta=access_token_expires
|
||||
)
|
||||
return {"access_token": access_token, "token_type": "bearer"}
|
||||
|
||||
@router.post("/register", response_model=UserResponse)
|
||||
async def register(
|
||||
user_in: UserCreate,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
try:
|
||||
from app.models.user import UserRole
|
||||
user_in.role = UserRole.NURSE
|
||||
user = await user_service.create_user(db, user_in=user_in)
|
||||
return user
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
@router.get("/me", response_model=UserResponse)
|
||||
async def get_me(current_user: User = Depends(get_current_user)):
|
||||
return current_user
|
||||
@@ -0,0 +1,110 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from typing import List
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.schemas.display import DisplayCreate, DisplayUpdate, DisplayResponse, ESP32Heartbeat, ESP32HeartbeatResponse, ESP32DisplayData
|
||||
from app.services.display_service import display_service
|
||||
from app.repositories.display_repo import display_repo
|
||||
|
||||
from app.models.room import ICURoom
|
||||
from app.models.patient import Patient
|
||||
from app.models.vitals import Vitals
|
||||
|
||||
router = APIRouter(tags=["displays"])
|
||||
|
||||
@router.get("/api/displays", response_model=List[DisplayResponse])
|
||||
async def read_displays(
|
||||
skip: int = 0, limit: int = 100,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
return await display_repo.get_all(db, skip=skip, limit=limit)
|
||||
|
||||
@router.post("/api/displays", response_model=DisplayResponse)
|
||||
async def register_device(
|
||||
device_in: DisplayCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
return await display_service.register_device(db, obj_in=device_in)
|
||||
|
||||
@router.post("/api/device/heartbeat", response_model=ESP32HeartbeatResponse)
|
||||
async def device_heartbeat(
|
||||
heartbeat: ESP32Heartbeat,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
try:
|
||||
pending_update = await display_service.process_heartbeat(db, heartbeat)
|
||||
return {"pending_update": pending_update}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=401, detail=str(e))
|
||||
|
||||
@router.get("/api/display/{display_id}", response_model=List[ESP32DisplayData])
|
||||
async def get_display_data(
|
||||
display_id: str,
|
||||
db: AsyncSession = Depends(get_db)
|
||||
):
|
||||
device = await display_repo.get_by_device_id(db, display_id)
|
||||
if not device:
|
||||
raise HTTPException(status_code=404, detail="Device not found")
|
||||
|
||||
device.pending_update = False
|
||||
await db.commit()
|
||||
|
||||
# Fetch up to 5 most recently updated patients
|
||||
patient_result = await db.execute(
|
||||
select(Patient).order_by(Patient.last_updated.desc()).limit(5)
|
||||
)
|
||||
patients = patient_result.scalars().all()
|
||||
|
||||
if not patients:
|
||||
return [ESP32DisplayData(
|
||||
patient_name="No Patients Found",
|
||||
status="Empty"
|
||||
)]
|
||||
|
||||
display_data_list = []
|
||||
|
||||
for patient in patients:
|
||||
# Get the Room for this patient
|
||||
room_name = "N/A"
|
||||
if patient.room_id:
|
||||
room_result = await db.execute(select(ICURoom).filter(ICURoom.id == patient.room_id))
|
||||
room = room_result.scalars().first()
|
||||
if room:
|
||||
room_name = room.room_number
|
||||
|
||||
# Get the latest Vitals for this patient
|
||||
vitals_result = await db.execute(
|
||||
select(Vitals).filter(Vitals.patient_id == patient.id).order_by(Vitals.updated_at.desc())
|
||||
)
|
||||
latest_vitals = vitals_result.scalars().first()
|
||||
|
||||
display_data_list.append(
|
||||
ESP32DisplayData(
|
||||
patient_name=patient.patient_name,
|
||||
age=patient.age,
|
||||
gender=patient.gender,
|
||||
blood_group=patient.blood_group,
|
||||
doctor=patient.doctor_name,
|
||||
room=room_name,
|
||||
heart_rate=latest_vitals.heart_rate if latest_vitals else None,
|
||||
spo2=latest_vitals.spo2 if latest_vitals else None,
|
||||
blood_pressure=latest_vitals.blood_pressure if latest_vitals else None,
|
||||
temperature=latest_vitals.temperature if latest_vitals else None,
|
||||
respiration_rate=latest_vitals.respiration_rate if latest_vitals else None,
|
||||
diagnosis=patient.diagnosis,
|
||||
status=patient.status,
|
||||
food_instructions=patient.food_instructions or "No outside food allowed",
|
||||
visiting_rules=patient.visiting_rules or "2 times visits",
|
||||
visiting_hours=patient.visiting_hours or "9 - 11 AM, 4 - 6 PM",
|
||||
restrictions=patient.restrictions or "Dogs are not allowed",
|
||||
last_updated=latest_vitals.updated_at.isoformat() if latest_vitals else patient.last_updated.isoformat() if patient.last_updated else None
|
||||
)
|
||||
)
|
||||
|
||||
return display_data_list
|
||||
@@ -0,0 +1,67 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from typing import List
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.schemas.patient import PatientCreate, PatientUpdate, PatientResponse
|
||||
from app.services.patient_service import patient_service
|
||||
|
||||
router = APIRouter(prefix="/api/patients", tags=["patients"])
|
||||
|
||||
@router.get("", response_model=List[PatientResponse])
|
||||
async def read_patients(
|
||||
skip: int = 0, limit: int = 100,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
return await patient_service.get_patients(db, skip=skip, limit=limit)
|
||||
|
||||
@router.get("/{id}", response_model=PatientResponse)
|
||||
async def read_patient(
|
||||
id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
patient = await patient_service.get_patient(db, id=id)
|
||||
if not patient:
|
||||
raise HTTPException(status_code=404, detail="Patient not found")
|
||||
return patient
|
||||
|
||||
@router.post("", response_model=PatientResponse)
|
||||
async def create_patient(
|
||||
patient_in: PatientCreate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
try:
|
||||
return await patient_service.create_patient(db, patient_in=patient_in)
|
||||
except IntegrityError:
|
||||
await db.rollback()
|
||||
raise HTTPException(status_code=400, detail="A patient with this MRN already exists.")
|
||||
|
||||
@router.put("/{id}", response_model=PatientResponse)
|
||||
async def update_patient(
|
||||
id: int,
|
||||
patient_in: PatientUpdate,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
patient = await patient_service.get_patient(db, id=id)
|
||||
if not patient:
|
||||
raise HTTPException(status_code=404, detail="Patient not found")
|
||||
return await patient_service.update_patient(db, patient=patient, patient_in=patient_in)
|
||||
|
||||
@router.delete("/{id}")
|
||||
async def delete_patient(
|
||||
id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user)
|
||||
):
|
||||
patient = await patient_service.get_patient(db, id=id)
|
||||
if not patient:
|
||||
raise HTTPException(status_code=404, detail="Patient not found")
|
||||
await patient_service.delete_patient(db, id=id)
|
||||
return {"message": "Patient deleted successfully"}
|
||||
@@ -0,0 +1,38 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from typing import List
|
||||
from sqlalchemy.future import select
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User
|
||||
from app.models.room import ICURoom
|
||||
from app.core.dependencies import get_current_user
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter(tags=["rooms"])
|
||||
|
||||
class RoomBase(BaseModel):
|
||||
room_number: str
|
||||
ward: str
|
||||
hospital_id: int | None = None
|
||||
display_id: int | None = None
|
||||
|
||||
class RoomCreate(RoomBase):
|
||||
pass
|
||||
|
||||
class RoomResponse(RoomBase):
|
||||
id: int
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@router.get("/api/rooms", response_model=List[RoomResponse])
|
||||
async def get_rooms(db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(select(ICURoom))
|
||||
return result.scalars().all()
|
||||
|
||||
@router.post("/api/rooms", response_model=RoomResponse)
|
||||
async def create_room(room_in: RoomCreate, db: AsyncSession = Depends(get_db)):
|
||||
room = ICURoom(**room_in.model_dump())
|
||||
db.add(room)
|
||||
await db.commit()
|
||||
await db.refresh(room)
|
||||
return room
|
||||
@@ -0,0 +1,44 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from typing import List
|
||||
from pydantic import BaseModel
|
||||
from datetime import datetime
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.models.vitals import Vitals
|
||||
from app.core.dependencies import get_current_user
|
||||
from app.models.user import User
|
||||
|
||||
router = APIRouter(tags=["vitals"])
|
||||
|
||||
class VitalsBase(BaseModel):
|
||||
patient_id: int
|
||||
heart_rate: int | None = None
|
||||
spo2: int | None = None
|
||||
blood_pressure: str | None = None
|
||||
temperature: float | None = None
|
||||
respiration_rate: int | None = None
|
||||
|
||||
class VitalsCreate(VitalsBase):
|
||||
pass
|
||||
|
||||
class VitalsResponse(VitalsBase):
|
||||
id: int
|
||||
updated_at: datetime
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
@router.get("/api/vitals/{patient_id}", response_model=List[VitalsResponse])
|
||||
async def get_patient_vitals(patient_id: int, db: AsyncSession = Depends(get_db)):
|
||||
result = await db.execute(
|
||||
select(Vitals).filter(Vitals.patient_id == patient_id).order_by(Vitals.updated_at.desc())
|
||||
)
|
||||
return result.scalars().all()
|
||||
|
||||
@router.post("/api/vitals", response_model=VitalsResponse)
|
||||
async def create_vitals(vitals_in: VitalsCreate, db: AsyncSession = Depends(get_db)):
|
||||
vitals = Vitals(**vitals_in.model_dump())
|
||||
db.add(vitals)
|
||||
await db.commit()
|
||||
await db.refresh(vitals)
|
||||
return vitals
|
||||
@@ -0,0 +1,23 @@
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
class Settings(BaseSettings):
|
||||
MYSQL_USER: str = "icu_user"
|
||||
MYSQL_PASSWORD: str = "icupassword"
|
||||
MYSQL_DATABASE: str = "icu_db"
|
||||
DATABASE_URL: str | None = None
|
||||
|
||||
JWT_SECRET: str = "supersecretkey_change_me_in_production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
REFRESH_TOKEN_EXPIRE_DAYS: int = 7
|
||||
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore")
|
||||
|
||||
@property
|
||||
def get_database_url(self) -> str:
|
||||
if self.DATABASE_URL:
|
||||
return self.DATABASE_URL
|
||||
# Fallback to local SQLite so Docker isn't required to run the project
|
||||
return "sqlite+aiosqlite:///./icu_local.db"
|
||||
|
||||
settings = Settings()
|
||||
@@ -0,0 +1,25 @@
|
||||
from typing import AsyncGenerator
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
from app.core.config import settings
|
||||
|
||||
engine = create_async_engine(
|
||||
settings.get_database_url,
|
||||
echo=False,
|
||||
future=True,
|
||||
pool_pre_ping=True
|
||||
)
|
||||
|
||||
AsyncSessionLocal = async_sessionmaker(
|
||||
bind=engine,
|
||||
class_=AsyncSession,
|
||||
expire_on_commit=False,
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
)
|
||||
|
||||
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with AsyncSessionLocal() as session:
|
||||
try:
|
||||
yield session
|
||||
finally:
|
||||
await session.close()
|
||||
@@ -0,0 +1,50 @@
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
import jwt
|
||||
from jwt.exceptions import InvalidTokenError
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.core.config import settings
|
||||
from app.core.database import get_db
|
||||
from app.models.user import User, UserRole
|
||||
from app.services.user_service import user_service
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/api/auth/login", auto_error=False)
|
||||
|
||||
async def get_current_user(
|
||||
token: str = Depends(oauth2_scheme),
|
||||
db: AsyncSession = Depends(get_db)
|
||||
) -> User:
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
if not token:
|
||||
raise credentials_exception
|
||||
|
||||
try:
|
||||
payload = jwt.decode(token, settings.JWT_SECRET, algorithms=[settings.JWT_ALGORITHM])
|
||||
email: str = payload.get("sub")
|
||||
if email is None:
|
||||
raise credentials_exception
|
||||
except InvalidTokenError:
|
||||
raise credentials_exception
|
||||
|
||||
user = await user_service.get_user_by_email(db, email=email)
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
|
||||
return user
|
||||
|
||||
|
||||
async def get_current_active_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role != UserRole.ADMIN:
|
||||
raise HTTPException(status_code=403, detail="Not enough privileges")
|
||||
return current_user
|
||||
|
||||
async def get_current_doctor_or_admin(current_user: User = Depends(get_current_user)) -> User:
|
||||
if current_user.role not in [UserRole.ADMIN, UserRole.DOCTOR]:
|
||||
raise HTTPException(status_code=403, detail="Not enough privileges")
|
||||
return current_user
|
||||
@@ -0,0 +1,44 @@
|
||||
from typing import Any, Generic, Type, TypeVar, Optional, List
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from pydantic import BaseModel
|
||||
|
||||
ModelType = TypeVar("ModelType")
|
||||
CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel)
|
||||
UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel)
|
||||
|
||||
class BaseRepository(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
||||
def __init__(self, model: Type[ModelType]):
|
||||
self.model = model
|
||||
|
||||
async def get(self, db: AsyncSession, id: Any) -> Optional[ModelType]:
|
||||
result = await db.execute(select(self.model).filter(self.model.id == id))
|
||||
return result.scalars().first()
|
||||
|
||||
async def get_all(self, db: AsyncSession, skip: int = 0, limit: int = 100) -> List[ModelType]:
|
||||
result = await db.execute(select(self.model).offset(skip).limit(limit))
|
||||
return list(result.scalars().all())
|
||||
|
||||
async def create(self, db: AsyncSession, obj_in: CreateSchemaType) -> ModelType:
|
||||
obj_in_data = obj_in.model_dump()
|
||||
db_obj = self.model(**obj_in_data)
|
||||
db.add(db_obj)
|
||||
await db.commit()
|
||||
await db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
async def update(self, db: AsyncSession, db_obj: ModelType, obj_in: UpdateSchemaType) -> ModelType:
|
||||
update_data = obj_in.model_dump(exclude_unset=True)
|
||||
for field, value in update_data.items():
|
||||
setattr(db_obj, field, value)
|
||||
db.add(db_obj)
|
||||
await db.commit()
|
||||
await db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
async def remove(self, db: AsyncSession, id: int) -> Optional[ModelType]:
|
||||
obj = await self.get(db=db, id=id)
|
||||
if obj:
|
||||
await db.delete(obj)
|
||||
await db.commit()
|
||||
return obj
|
||||
@@ -0,0 +1,22 @@
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import jwt
|
||||
from passlib.context import CryptContext
|
||||
from app.core.config import settings
|
||||
|
||||
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
|
||||
|
||||
def verify_password(plain_password: str, hashed_password: str) -> bool:
|
||||
return pwd_context.verify(plain_password, hashed_password)
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return pwd_context.hash(password)
|
||||
|
||||
def create_access_token(data: dict, expires_delta: timedelta | None = None) -> str:
|
||||
to_encode = data.copy()
|
||||
if expires_delta:
|
||||
expire = datetime.now(timezone.utc) + expires_delta
|
||||
else:
|
||||
expire = datetime.now(timezone.utc) + timedelta(minutes=settings.ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
to_encode.update({"exp": expire})
|
||||
encoded_jwt = jwt.encode(to_encode, settings.JWT_SECRET, algorithm=settings.JWT_ALGORITHM)
|
||||
return encoded_jwt
|
||||
@@ -0,0 +1,40 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from app.core.config import settings
|
||||
from app.controllers import auth, patient, display, room, vitals
|
||||
from app.core.database import engine
|
||||
from app.models.base import Base
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
# Create SQLite tables on startup automatically
|
||||
async with engine.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
yield
|
||||
|
||||
app = FastAPI(
|
||||
title="ICU Patient Display Management System API",
|
||||
description="Backend API for managing ICU patients and ESP32 displays",
|
||||
version="1.0.0",
|
||||
lifespan=lifespan
|
||||
)
|
||||
|
||||
# CORS Middleware configuration
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.include_router(auth.router)
|
||||
app.include_router(patient.router)
|
||||
app.include_router(display.router)
|
||||
app.include_router(room.router)
|
||||
app.include_router(vitals.router)
|
||||
|
||||
@app.get("/")
|
||||
async def root():
|
||||
return {"message": "Welcome to ICU Patient Display API"}
|
||||
@@ -0,0 +1,8 @@
|
||||
from .base import Base
|
||||
from .user import User
|
||||
from .hospital import Hospital
|
||||
from .room import ICURoom
|
||||
from .display import DisplayDevice
|
||||
from .patient import Patient
|
||||
from .vitals import Vitals
|
||||
from .audit import AuditLog
|
||||
@@ -0,0 +1,12 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class AuditLog(Base):
|
||||
__tablename__ = "audit_logs"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id"))
|
||||
action = Column(String(255), nullable=False)
|
||||
details = Column(Text)
|
||||
timestamp = Column(DateTime, server_default=func.now())
|
||||
@@ -0,0 +1,3 @@
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
@@ -0,0 +1,22 @@
|
||||
from sqlalchemy import Column, Integer, String, Boolean, DateTime, ForeignKey
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class DisplayDevice(Base):
|
||||
__tablename__ = "display_devices"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
device_id = Column(String(100), unique=True, index=True, nullable=False)
|
||||
device_secret = Column(String(255), nullable=False)
|
||||
name = Column(String(100))
|
||||
firmware_version = Column(String(50))
|
||||
ip_address = Column(String(50))
|
||||
mac_address = Column(String(50))
|
||||
wifi_rssi = Column(Integer)
|
||||
uptime = Column(Integer)
|
||||
battery = Column(Integer)
|
||||
online_status = Column(Boolean, default=False)
|
||||
last_seen = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||
pending_update = Column(Boolean, default=False)
|
||||
|
||||
room_id = Column(Integer, ForeignKey("icu_rooms.id"), nullable=True)
|
||||
@@ -0,0 +1,9 @@
|
||||
from sqlalchemy import Column, Integer, String
|
||||
from .base import Base
|
||||
|
||||
class Hospital(Base):
|
||||
__tablename__ = "hospitals"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(255), nullable=False)
|
||||
address = Column(String(500), nullable=True)
|
||||
@@ -0,0 +1,25 @@
|
||||
from sqlalchemy import Column, Integer, String, Text, ForeignKey, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class Patient(Base):
|
||||
__tablename__ = "patients"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
mrn = Column(String(50), unique=True, index=True, nullable=False)
|
||||
patient_name = Column(String(255), nullable=False)
|
||||
age = Column(Integer)
|
||||
gender = Column(String(50))
|
||||
blood_group = Column(String(10))
|
||||
diagnosis = Column(Text)
|
||||
allergies = Column(Text)
|
||||
doctor_name = Column(String(255))
|
||||
status = Column(String(50), default="Stable")
|
||||
notes = Column(Text)
|
||||
food_instructions = Column(String(255), default="No outside food allowed")
|
||||
visiting_rules = Column(String(255), default="2 times visits")
|
||||
visiting_hours = Column(String(255), default="9 - 11 AM, 4 - 6 PM")
|
||||
restrictions = Column(String(255), default="Dogs are not allowed")
|
||||
last_updated = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||
|
||||
room_id = Column(Integer, ForeignKey("icu_rooms.id"))
|
||||
@@ -0,0 +1,13 @@
|
||||
from sqlalchemy import Column, Integer, String, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from .base import Base
|
||||
|
||||
class ICURoom(Base):
|
||||
__tablename__ = "icu_rooms"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
room_number = Column(String(50), nullable=False)
|
||||
ward = Column(String(100), nullable=False)
|
||||
|
||||
hospital_id = Column(Integer, ForeignKey("hospitals.id"))
|
||||
display_id = Column(Integer, ForeignKey("display_devices.id"), nullable=True)
|
||||
@@ -0,0 +1,17 @@
|
||||
from sqlalchemy import Column, Integer, String, Enum
|
||||
import enum
|
||||
from .base import Base
|
||||
|
||||
class UserRole(str, enum.Enum):
|
||||
ADMIN = "admin"
|
||||
DOCTOR = "doctor"
|
||||
NURSE = "nurse"
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
hashed_password = Column(String(255), nullable=False)
|
||||
role = Column(Enum(UserRole), default=UserRole.NURSE)
|
||||
@@ -0,0 +1,15 @@
|
||||
from sqlalchemy import Column, Integer, String, Float, ForeignKey, DateTime
|
||||
from sqlalchemy.sql import func
|
||||
from .base import Base
|
||||
|
||||
class Vitals(Base):
|
||||
__tablename__ = "vitals"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
patient_id = Column(Integer, ForeignKey("patients.id"))
|
||||
heart_rate = Column(Integer)
|
||||
spo2 = Column(Integer)
|
||||
blood_pressure = Column(String(20))
|
||||
temperature = Column(Float)
|
||||
respiration_rate = Column(Integer)
|
||||
updated_at = Column(DateTime, server_default=func.now(), onupdate=func.now())
|
||||
@@ -0,0 +1,13 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from app.core.repository import BaseRepository
|
||||
from app.models.display import DisplayDevice
|
||||
from app.schemas.display import DisplayCreate, DisplayUpdate
|
||||
|
||||
class DisplayRepository(BaseRepository[DisplayDevice, DisplayCreate, DisplayUpdate]):
|
||||
async def get_by_device_id(self, db: AsyncSession, device_id: str) -> Optional[DisplayDevice]:
|
||||
result = await db.execute(select(DisplayDevice).filter(DisplayDevice.device_id == device_id))
|
||||
return result.scalars().first()
|
||||
|
||||
display_repo = DisplayRepository(DisplayDevice)
|
||||
@@ -0,0 +1,8 @@
|
||||
from app.core.repository import BaseRepository
|
||||
from app.models.patient import Patient
|
||||
from app.schemas.patient import PatientCreate, PatientUpdate
|
||||
|
||||
class PatientRepository(BaseRepository[Patient, PatientCreate, PatientUpdate]):
|
||||
pass
|
||||
|
||||
patient_repo = PatientRepository(Patient)
|
||||
@@ -0,0 +1,13 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from sqlalchemy.future import select
|
||||
from app.core.repository import BaseRepository
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate, UserBase
|
||||
|
||||
class UserRepository(BaseRepository[User, UserCreate, UserBase]):
|
||||
async def get_by_email(self, db: AsyncSession, email: str) -> Optional[User]:
|
||||
result = await db.execute(select(User).filter(User.email == email))
|
||||
return result.scalars().first()
|
||||
|
||||
user_repo = UserRepository(User)
|
||||
@@ -0,0 +1,61 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
class DisplayBase(BaseModel):
|
||||
name: Optional[str] = None
|
||||
room_id: Optional[int] = None
|
||||
mac_address: Optional[str] = None
|
||||
ip_address: Optional[str] = None
|
||||
|
||||
class DisplayCreate(DisplayBase):
|
||||
device_id: str
|
||||
device_secret: str
|
||||
|
||||
class DisplayUpdate(DisplayBase):
|
||||
pass
|
||||
|
||||
class DisplayResponse(DisplayBase):
|
||||
id: int
|
||||
device_id: str
|
||||
firmware_version: Optional[str] = None
|
||||
wifi_rssi: Optional[int] = None
|
||||
uptime: Optional[int] = None
|
||||
battery: Optional[int] = None
|
||||
online_status: bool
|
||||
last_seen: datetime
|
||||
pending_update: bool
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
class ESP32Heartbeat(BaseModel):
|
||||
device_id: str
|
||||
api_key: str
|
||||
firmware_version: Optional[str] = None
|
||||
ip_address: Optional[str] = None
|
||||
wifi_rssi: Optional[int] = None
|
||||
uptime: Optional[int] = None
|
||||
battery: Optional[int] = None
|
||||
|
||||
class ESP32HeartbeatResponse(BaseModel):
|
||||
pending_update: bool
|
||||
|
||||
class ESP32DisplayData(BaseModel):
|
||||
patient_name: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
gender: Optional[str] = None
|
||||
blood_group: Optional[str] = None
|
||||
doctor: Optional[str] = None
|
||||
room: Optional[str] = None
|
||||
heart_rate: Optional[int] = None
|
||||
spo2: Optional[int] = None
|
||||
blood_pressure: Optional[str] = None
|
||||
temperature: Optional[float] = None
|
||||
respiration_rate: Optional[int] = None
|
||||
diagnosis: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
food_instructions: Optional[str] = None
|
||||
visiting_rules: Optional[str] = None
|
||||
visiting_hours: Optional[str] = None
|
||||
restrictions: Optional[str] = None
|
||||
last_updated: Optional[str] = None
|
||||
@@ -0,0 +1,45 @@
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
class PatientBase(BaseModel):
|
||||
mrn: str
|
||||
patient_name: str
|
||||
age: Optional[int] = None
|
||||
gender: Optional[str] = None
|
||||
blood_group: Optional[str] = None
|
||||
diagnosis: Optional[str] = None
|
||||
allergies: Optional[str] = None
|
||||
doctor_name: Optional[str] = None
|
||||
status: Optional[str] = "Stable"
|
||||
notes: Optional[str] = None
|
||||
food_instructions: Optional[str] = "No outside food allowed"
|
||||
visiting_rules: Optional[str] = "2 times visits"
|
||||
visiting_hours: Optional[str] = "9 - 11 AM, 4 - 6 PM"
|
||||
restrictions: Optional[str] = "Dogs are not allowed"
|
||||
room_id: Optional[int] = None
|
||||
|
||||
class PatientCreate(PatientBase):
|
||||
pass
|
||||
|
||||
class PatientUpdate(BaseModel):
|
||||
patient_name: Optional[str] = None
|
||||
age: Optional[int] = None
|
||||
gender: Optional[str] = None
|
||||
blood_group: Optional[str] = None
|
||||
diagnosis: Optional[str] = None
|
||||
allergies: Optional[str] = None
|
||||
doctor_name: Optional[str] = None
|
||||
status: Optional[str] = None
|
||||
notes: Optional[str] = None
|
||||
food_instructions: Optional[str] = None
|
||||
visiting_rules: Optional[str] = None
|
||||
visiting_hours: Optional[str] = None
|
||||
restrictions: Optional[str] = None
|
||||
room_id: Optional[int] = None
|
||||
|
||||
class PatientResponse(PatientBase):
|
||||
id: int
|
||||
last_updated: datetime
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
@@ -0,0 +1,19 @@
|
||||
from pydantic import BaseModel, EmailStr
|
||||
from app.models.user import UserRole
|
||||
|
||||
class UserBase(BaseModel):
|
||||
name: str
|
||||
email: EmailStr
|
||||
role: UserRole = UserRole.NURSE
|
||||
|
||||
class UserCreate(UserBase):
|
||||
password: str
|
||||
|
||||
class UserResponse(UserBase):
|
||||
id: int
|
||||
|
||||
model_config = {"from_attributes": True}
|
||||
|
||||
class Token(BaseModel):
|
||||
access_token: str
|
||||
token_type: str
|
||||
@@ -0,0 +1,47 @@
|
||||
from datetime import datetime, timezone
|
||||
from typing import List
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.repositories.display_repo import display_repo
|
||||
from app.models.display import DisplayDevice
|
||||
from app.schemas.display import DisplayCreate, DisplayUpdate, ESP32Heartbeat
|
||||
from app.core.security import get_password_hash, verify_password
|
||||
|
||||
class DisplayService:
|
||||
async def register_device(self, db: AsyncSession, obj_in: DisplayCreate) -> DisplayDevice:
|
||||
hashed_secret = get_password_hash(obj_in.device_secret)
|
||||
obj_in.device_secret = hashed_secret
|
||||
return await display_repo.create(db, obj_in=obj_in)
|
||||
|
||||
async def process_heartbeat(self, db: AsyncSession, heartbeat: ESP32Heartbeat) -> bool:
|
||||
device = await display_repo.get_by_device_id(db, heartbeat.device_id)
|
||||
print(f"DEBUG heartbeat: device_id={heartbeat.device_id}, api_key={heartbeat.api_key}")
|
||||
if not device:
|
||||
print(f"DEBUG: device not found in db for id {heartbeat.device_id}")
|
||||
raise ValueError("Unauthorized device")
|
||||
|
||||
is_valid = verify_password(heartbeat.api_key, device.device_secret)
|
||||
print(f"DEBUG: verify_password={is_valid}")
|
||||
|
||||
if not is_valid:
|
||||
raise ValueError("Unauthorized device")
|
||||
|
||||
update_data = DisplayUpdate(
|
||||
ip_address=heartbeat.ip_address,
|
||||
firmware_version=heartbeat.firmware_version,
|
||||
wifi_rssi=heartbeat.wifi_rssi,
|
||||
uptime=heartbeat.uptime,
|
||||
battery=heartbeat.battery,
|
||||
)
|
||||
device = await display_repo.update(db, device, update_data)
|
||||
device.online_status = True
|
||||
device.last_seen = datetime.now(timezone.utc)
|
||||
await db.commit()
|
||||
|
||||
return device.pending_update
|
||||
|
||||
async def trigger_display_update_for_room(self, db: AsyncSession, room_id: int):
|
||||
from sqlalchemy import text
|
||||
await db.execute(text("UPDATE display_devices SET pending_update = 1 WHERE room_id = :room_id"), {"room_id": room_id})
|
||||
await db.commit()
|
||||
|
||||
display_service = DisplayService()
|
||||
@@ -0,0 +1,45 @@
|
||||
from typing import List
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.repositories.patient_repo import patient_repo
|
||||
from app.models.patient import Patient
|
||||
from app.schemas.patient import PatientCreate, PatientUpdate
|
||||
|
||||
class PatientService:
|
||||
async def get_patient(self, db: AsyncSession, id: int) -> Patient:
|
||||
return await patient_repo.get(db, id=id)
|
||||
|
||||
async def get_patients(self, db: AsyncSession, skip: int = 0, limit: int = 100) -> List[Patient]:
|
||||
return await patient_repo.get_all(db, skip=skip, limit=limit)
|
||||
|
||||
async def create_patient(self, db: AsyncSession, patient_in: PatientCreate) -> Patient:
|
||||
patient = await patient_repo.create(db, obj_in=patient_in)
|
||||
if patient.room_id:
|
||||
from app.services.display_service import display_service
|
||||
await display_service.trigger_display_update_for_room(db, patient.room_id)
|
||||
return patient
|
||||
|
||||
async def update_patient(self, db: AsyncSession, patient: Patient, patient_in: PatientUpdate) -> Patient:
|
||||
old_room_id = patient.room_id
|
||||
patient = await patient_repo.update(db, db_obj=patient, obj_in=patient_in)
|
||||
|
||||
from app.services.display_service import display_service
|
||||
if patient.room_id:
|
||||
await display_service.trigger_display_update_for_room(db, patient.room_id)
|
||||
if old_room_id and old_room_id != patient.room_id:
|
||||
await display_service.trigger_display_update_for_room(db, old_room_id)
|
||||
|
||||
return patient
|
||||
|
||||
async def delete_patient(self, db: AsyncSession, id: int) -> Patient:
|
||||
patient = await patient_repo.get(db, id=id)
|
||||
room_id = patient.room_id if patient else None
|
||||
|
||||
deleted_patient = await patient_repo.remove(db, id=id)
|
||||
|
||||
if room_id:
|
||||
from app.services.display_service import display_service
|
||||
await display_service.trigger_display_update_for_room(db, room_id)
|
||||
|
||||
return deleted_patient
|
||||
|
||||
patient_service = PatientService()
|
||||
@@ -0,0 +1,30 @@
|
||||
from typing import Optional
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from app.repositories.user_repo import user_repo
|
||||
from app.models.user import User
|
||||
from app.schemas.user import UserCreate
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
class UserService:
|
||||
async def create_user(self, db: AsyncSession, user_in: UserCreate) -> User:
|
||||
user = await user_repo.get_by_email(db, email=user_in.email)
|
||||
if user:
|
||||
raise ValueError("Email already registered")
|
||||
|
||||
hashed_password = get_password_hash(user_in.password)
|
||||
|
||||
db_obj = User(
|
||||
name=user_in.name,
|
||||
email=user_in.email,
|
||||
role=user_in.role,
|
||||
hashed_password=hashed_password
|
||||
)
|
||||
db.add(db_obj)
|
||||
await db.commit()
|
||||
await db.refresh(db_obj)
|
||||
return db_obj
|
||||
|
||||
async def get_user_by_email(self, db: AsyncSession, email: str) -> Optional[User]:
|
||||
return await user_repo.get_by_email(db, email=email)
|
||||
|
||||
user_service = UserService()
|
||||
@@ -0,0 +1,36 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("icu_local.db")
|
||||
c = conn.cursor()
|
||||
|
||||
# Check rooms
|
||||
c.execute("SELECT * FROM icu_rooms")
|
||||
rooms = c.fetchall()
|
||||
c.execute("PRAGMA table_info(icu_rooms)")
|
||||
room_cols = [col[1] for col in c.fetchall()]
|
||||
print("=== Rooms ===")
|
||||
for r in rooms:
|
||||
print(dict(zip(room_cols, r)))
|
||||
|
||||
# Check displays
|
||||
c.execute("SELECT * FROM display_devices")
|
||||
devices = c.fetchall()
|
||||
c.execute("PRAGMA table_info(display_devices)")
|
||||
dev_cols = [col[1] for col in c.fetchall()]
|
||||
print("\n=== Displays ===")
|
||||
for d in devices:
|
||||
print(dict(zip(dev_cols, d)))
|
||||
|
||||
# Assign room_id=1 to display id=1 if not already assigned
|
||||
if rooms and devices:
|
||||
room_id = rooms[0][0] # first room's id
|
||||
device_id = devices[0][0] # first device's id
|
||||
c.execute("UPDATE display_devices SET room_id = ? WHERE id = ?", (room_id, device_id))
|
||||
conn.commit()
|
||||
print(f"\nAssigned room id={room_id} to display id={device_id}")
|
||||
|
||||
# Verify
|
||||
c.execute("SELECT id, device_id, room_id FROM display_devices WHERE id = ?", (device_id,))
|
||||
print("Updated display:", c.fetchone())
|
||||
|
||||
conn.close()
|
||||
@@ -0,0 +1,25 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("icu_local.db")
|
||||
c = conn.cursor()
|
||||
|
||||
# List tables
|
||||
c.execute("SELECT name FROM sqlite_master WHERE type='table'")
|
||||
print("Tables:", [r[0] for r in c.fetchall()])
|
||||
|
||||
# Check display_devices
|
||||
try:
|
||||
c.execute("SELECT * FROM display_devices")
|
||||
rows = c.fetchall()
|
||||
if rows:
|
||||
c.execute("PRAGMA table_info(display_devices)")
|
||||
cols = [col[1] for col in c.fetchall()]
|
||||
print("Columns:", cols)
|
||||
for row in rows:
|
||||
print(dict(zip(cols, row)))
|
||||
else:
|
||||
print("No devices registered yet!")
|
||||
except Exception as e:
|
||||
print("Error:", e)
|
||||
|
||||
conn.close()
|
||||
@@ -0,0 +1,15 @@
|
||||
fastapi
|
||||
uvicorn[standard]
|
||||
sqlalchemy[asyncio]
|
||||
alembic
|
||||
aiomysql
|
||||
aiosqlite
|
||||
pydantic
|
||||
pydantic[email]
|
||||
pydantic-settings
|
||||
pyjwt
|
||||
passlib[bcrypt]
|
||||
bcrypt<4.0.0
|
||||
argon2-cffi
|
||||
python-multipart
|
||||
pytest
|
||||
@@ -0,0 +1,21 @@
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from app.models.user import User, UserRole
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
engine = create_async_engine("sqlite+aiosqlite:///./icu_local.db", echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
async def seed_user():
|
||||
async with AsyncSessionLocal() as session:
|
||||
user = User(
|
||||
name="Demo Nurse",
|
||||
email="nurse@hospital.com",
|
||||
hashed_password=get_password_hash("password123"),
|
||||
role=UserRole.NURSE
|
||||
)
|
||||
session.add(user)
|
||||
await session.commit()
|
||||
print("Demo user created successfully.")
|
||||
|
||||
asyncio.run(seed_user())
|
||||
@@ -0,0 +1,53 @@
|
||||
"""
|
||||
Seed script to register the ESP32 display device in the database.
|
||||
Run this once to create the device entry that the ESP32 heartbeat authenticates against.
|
||||
"""
|
||||
import asyncio
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
from app.models.display import DisplayDevice
|
||||
from app.core.security import get_password_hash
|
||||
|
||||
engine = create_async_engine("sqlite+aiosqlite:///./icu_local.db", echo=False)
|
||||
AsyncSessionLocal = async_sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Set your device credentials here.
|
||||
# The DEVICE_SECRET below is what the ESP32
|
||||
# must send as "api_key" in its heartbeat JSON.
|
||||
# ──────────────────────────────────────────────
|
||||
DEVICE_ID = "ESP32_WAVESHARE_1"
|
||||
DEVICE_SECRET = "esp32_secret_key_2024" # <-- Put this in your ESP32 code as api_key
|
||||
DEVICE_NAME = "ICU Bedside Display 1"
|
||||
|
||||
async def seed_device():
|
||||
async with AsyncSessionLocal() as session:
|
||||
# Check if device already exists
|
||||
from sqlalchemy.future import select
|
||||
result = await session.execute(
|
||||
select(DisplayDevice).filter(DisplayDevice.device_id == DEVICE_ID)
|
||||
)
|
||||
existing = result.scalars().first()
|
||||
|
||||
if existing:
|
||||
print(f"Device '{DEVICE_ID}' already exists (id={existing.id}). Skipping.")
|
||||
return
|
||||
|
||||
device = DisplayDevice(
|
||||
device_id=DEVICE_ID,
|
||||
device_secret=get_password_hash(DEVICE_SECRET),
|
||||
name=DEVICE_NAME,
|
||||
online_status=False,
|
||||
pending_update=False,
|
||||
)
|
||||
session.add(device)
|
||||
await session.commit()
|
||||
print(f"✅ Device registered successfully!")
|
||||
print(f" Device ID: {DEVICE_ID}")
|
||||
print(f" API Key: {DEVICE_SECRET}")
|
||||
print(f" Name: {DEVICE_NAME}")
|
||||
print()
|
||||
print(f"Now update your ESP32 code with:")
|
||||
print(f' const char* device_id = "{DEVICE_ID}";')
|
||||
print(f' const char* api_key = "{DEVICE_SECRET}";')
|
||||
|
||||
asyncio.run(seed_device())
|
||||
@@ -0,0 +1,11 @@
|
||||
import sqlite3
|
||||
|
||||
conn = sqlite3.connect("icu_local.db")
|
||||
c = conn.cursor()
|
||||
|
||||
# Set pending_update to 1 for all displays to force them to refresh
|
||||
c.execute("UPDATE display_devices SET pending_update = 1")
|
||||
conn.commit()
|
||||
|
||||
print("Set pending_update = 1 for all displays. The ESP32 should pick this up on its next heartbeat!")
|
||||
conn.close()
|
||||
@@ -0,0 +1,7 @@
|
||||
from app.core.security import verify_password
|
||||
|
||||
secret = "esp32_secret_key_2024"
|
||||
stored_hash = "$2b$12$2dm4v2h2GyzL7MrWG9zOWuMmcUoJgkIWZi34xgv3zfTpiGe2ajJEm"
|
||||
|
||||
result = verify_password(secret, stored_hash)
|
||||
print(f"Password verification: {result}")
|
||||
Reference in New Issue
Block a user