Files
lzwcai-mcp/terminal_dhr_mcp/terminal_dhr_mcp/door_control.py

215 lines
8.4 KiB
Python

import httpx
import logging
from typing import Dict, Any, Optional
from .config import Config
logger = logging.getLogger(__name__)
class DoorControlService:
"""Door control service using new API interface"""
def __init__(self):
self.base_url = Config.BASE_URL
self.endpoint = Config.DOOR_API_ENDPOINT
self.enterprise_id = Config.DOOR_ENTERPRISE_ID
self.default_entity_id = Config.DOOR_DEFAULT_ENTITY_ID
self.timeout = Config.DOOR_API_TIMEOUT
async def control_door(
self,
action: str,
entity_id: Optional[str] = None
) -> Dict[str, Any]:
"""
Control door via new API interface
Args:
action: 'open' or 'close'
entity_id: Entity ID for the door device (optional, uses default if not provided)
Returns:
Dict with success status and message
"""
try:
# Validate action
if action.lower() not in ['open', 'close']:
return {
"success": False,
"message": f"Invalid action '{action}'. Must be 'open' or 'close'"
}
# Use provided parameters or defaults
target_entity_id = entity_id or self.default_entity_id
# Map action to API command
command_mapping = {
'open': 'turn_on',
'close': 'turn_off'
}
command = command_mapping.get(action.lower())
# Prepare request data according to new API format
json_body = {
"enterpriseId": self.enterprise_id,
"entityId": target_entity_id,
"command": command
}
# Prepare headers
headers = {
"Content-Type": "application/json",
"Accept": "*/*",
"User-Agent": "Apifox/1.0.0 (https://apifox.com)",
"Connection": "keep-alive"
}
# Construct full URL
url = f"{self.base_url}{self.endpoint}"
logger.info(f"Attempting to {action} - Entity: {target_entity_id}, Command: {command}, URL: {url}")
# Make API request using httpx
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.post(url, json=json_body, headers=headers)
if response.status_code == 200:
result_data = response.json()
logger.info(f"Door control successful: {action}")
return {
"success": True,
"message": f"Door control successful: {action}",
"action": action,
"entity_id": target_entity_id,
"command": command,
"response": result_data
}
else:
error_text = response.text
logger.error(f"Door control failed: HTTP {response.status_code} - {error_text}")
return {
"success": False,
"message": f"Door control failed: HTTP {response.status_code} - {error_text}",
"action": action,
"entity_id": target_entity_id,
"command": command
}
except httpx.TimeoutException:
logger.error("Timeout during door control request")
return {
"success": False,
"message": "Request timeout, please check network connection",
"action": action
}
except httpx.RequestError as e:
logger.error(f"Network error during door control: {e}")
return {
"success": False,
"message": f"Network connection error: {str(e)}",
"action": action
}
except Exception as e:
logger.error(f"Unexpected error during door control: {e}")
return {
"success": False,
"message": f"System error: {str(e)}",
"action": action
}
async def get_door_status(self, entity_id: Optional[str] = None) -> Dict[str, Any]:
"""
Get current door status from new API interface
Args:
entity_id: Entity ID for the door device (optional, uses default if not provided)
Returns:
Dict with door status information optimized for AI understanding
"""
try:
target_entity_id = entity_id or self.default_entity_id
# Prepare request data for status query
json_body = {
"enterpriseId": self.enterprise_id,
"entityId": target_entity_id,
"command": "get_status" # Assuming this command exists for status query
}
# Prepare headers
headers = {
"Content-Type": "application/json",
"Accept": "*/*",
"User-Agent": "Apifox/1.0.0 (https://apifox.com)",
"Connection": "keep-alive"
}
# Construct full URL
url = f"{self.base_url}{self.endpoint}"
async with httpx.AsyncClient(timeout=self.timeout) as client:
response = await client.post(url, json=json_body, headers=headers)
if response.status_code == 200:
result_data = response.json()
# Extract status information from response
# Note: This is a placeholder implementation as the actual response format
# from the new API is not known. You may need to adjust this based on
# the actual API response structure.
# Default status mapping
status_mapping = {
"on": "open",
"off": "closed",
"unavailable": "unavailable",
"unknown": "unknown"
}
# Try to extract status from response
current_state = "unknown"
if isinstance(result_data, dict):
current_state = result_data.get("state", "unknown")
if current_state in status_mapping:
current_state = status_mapping[current_state]
# Build AI-friendly response
ai_response = {
"success": True,
"device_name": target_entity_id,
"current_state": current_state,
"raw_state": result_data.get("state", "unknown"),
"entity_id": target_entity_id,
"response": result_data
}
return ai_response
else:
error_text = response.text
return {
"success": False,
"message": f"Failed to get door status: HTTP {response.status_code} - {error_text}",
"entity_id": target_entity_id
}
except httpx.TimeoutException:
logger.error("Timeout getting door status")
return {
"success": False,
"message": "Timeout getting door status, please check network connection",
"entity_id": entity_id or self.default_entity_id
}
except httpx.RequestError as e:
logger.error(f"Network error getting door status: {e}")
return {
"success": False,
"message": f"Network error getting door status: {str(e)}",
"entity_id": entity_id or self.default_entity_id
}
except Exception as e:
logger.error(f"Error getting door status: {e}")
return {
"success": False,
"message": f"Error getting door status: {str(e)}",
"entity_id": entity_id or self.default_entity_id
}