Add room and analytics services with CRUD API endpoints
- Implement RoomService for room management and metrics - Add AnalyticsService for sensor data analytics and trends - Extend models with Room, RoomCreate, RoomUpdate, RoomInfo - Add room CRUD endpoints to FastAPI app - Add database connection logic for MongoDB and Redis - Refactor sensor service logic into SensorService class
This commit is contained in:
66
microservices/sensor-service/database.py
Normal file
66
microservices/sensor-service/database.py
Normal file
@@ -0,0 +1,66 @@
|
||||
"""
|
||||
Database connection and management for sensor service
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from motor.motor_asyncio import AsyncIOMotorClient
|
||||
import redis.asyncio as redis
|
||||
from typing import Optional
|
||||
import os
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Global database connections
|
||||
mongo_client: Optional[AsyncIOMotorClient] = None
|
||||
redis_client: Optional[redis.Redis] = None
|
||||
database = None
|
||||
|
||||
async def connect_to_mongo():
|
||||
"""Connect to MongoDB"""
|
||||
global mongo_client, database
|
||||
|
||||
try:
|
||||
mongo_url = os.getenv("MONGO_URL", "mongodb://admin:password123@mongodb:27017/energy_dashboard_sensors?authSource=admin")
|
||||
|
||||
mongo_client = AsyncIOMotorClient(mongo_url)
|
||||
database = mongo_client.energy_dashboard_sensors
|
||||
|
||||
# Test connection
|
||||
await mongo_client.admin.command('ping')
|
||||
logger.info("Connected to MongoDB successfully")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to connect to MongoDB: {e}")
|
||||
raise
|
||||
|
||||
async def close_mongo_connection():
|
||||
"""Close MongoDB connection"""
|
||||
global mongo_client
|
||||
if mongo_client:
|
||||
mongo_client.close()
|
||||
logger.info("Closed MongoDB connection")
|
||||
|
||||
async def connect_to_redis():
|
||||
"""Connect to Redis"""
|
||||
global redis_client
|
||||
|
||||
try:
|
||||
redis_url = os.getenv("REDIS_URL", "redis://redis:6379")
|
||||
redis_client = redis.from_url(redis_url, decode_responses=True)
|
||||
|
||||
# Test connection
|
||||
await redis_client.ping()
|
||||
logger.info("Connected to Redis successfully")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to connect to Redis: {e}")
|
||||
raise
|
||||
|
||||
async def get_database():
|
||||
"""Get database instance"""
|
||||
return database
|
||||
|
||||
async def get_redis():
|
||||
"""Get Redis client instance"""
|
||||
return redis_client
|
||||
Reference in New Issue
Block a user