"""
DHT11 MCP Server Script

This script implements a simple MCP (Model Context Protocol) server for a DHT11 temperature and humidity sensor,
using the FastMCP framework. It defines three MCP tools for reading temperature, humidity, or both from the DHT11 sensor,
and communicates with an underlying hardware communication protocol server via HTTP requests.
The server exposes these sensor functions to be called by external AI agents through MCP.
"""

import requests
from mcp.server.fastmcp import FastMCP

# ===============================
# Constants for Communication Protocol
# ===============================

# The hostname or IP address of the communication protocol server (usually running locally)
COMMUNICATION_PROTOCOL_HOST = 'localhost'
# The port number where the protocol server is listening
COMMUNICATION_PROTOCOL_PORT = 8000
# The full URL endpoint for sending commands to the communication protocol server
URL = f"http://{COMMUNICATION_PROTOCOL_HOST}:{COMMUNICATION_PROTOCOL_PORT}/send_cmd"

# ===============================
# MCP Server Initialization
# ===============================

server = FastMCP(
    "DHT11",
    description="DHT11 PC data monitoring via MCP. Supports general_accuracy temperature and humidity reading."
)

# ===============================
# MCP Tools Registration
# ===============================

@server.tool()
async def read_temperature():
    """
    Read temperature values from the DHT11 sensor.

    Returns:
    A json-format data of temperature with time stamp.
    """
    cmd = {"sensor": "DHT11","command": "read_temp"}
    temperature = requests.post(URL, json=cmd).text
    return temperature

@server.tool()
async def read_humidity():
    """
    Read humidity values from the DHT11 sensor.

    Returns:
    A json-format data of humidity with time stamp.
    """
    cmd = {"sensor": "DHT11","command": "read_hum"}
    humidity = requests.post(URL, json=cmd).text
    return humidity

@server.tool()
async def read_all():
    """
    Read temperature & humidity values from the DHT11 sensor.

    Returns:
    A json-format data of temperature & humidity with time stamp.
    """
    cmd = {"sensor": "DHT11","command": "read_all"}
    all_data = requests.post(URL, json=cmd).text
    return all_data

# ===============================
# Main Entry Point
# ===============================
if __name__ == '__main__':
    # Start the MCP server and register the sensor tools
    server.run()