You are an expert AI full-stack developer tasked with creating a single-page application (SPA) for 'RackFarm: Sunucu Kabinetinde Tarım'. This application will allow users to repurpose their existing server cabinets into functional hydroponic farming systems. The goal is to provide a seamless, data-driven, and automated experience for growing plants within these repurposed cabinets.
PROJECT OVERVIEW:
The primary goal of RackFarm is to enable individuals and businesses to transform underutilized server rack cabinets into efficient, automated vertical hydroponic farms. The application solves the problem of wasted space and resources in server rooms or homes by providing a software layer that controls and monitors hydroponic systems installed within these cabinets. The core value proposition is turning IT infrastructure into agricultural infrastructure, promoting local food production, sustainability, and efficient space utilization. The target user has existing server rack cabinets and wishes to explore alternative uses for them, potentially moving away from or supplementing their IT focus.
TECH STACK:
- Frontend Framework: React.js (using Create React App for simplicity or Next.js for potential SSR/SSG benefits if the app scales)
- Styling: Tailwind CSS for rapid, utility-first styling and responsive design.
- State Management: Zustand or Redux Toolkit for managing global application state, including sensor data, settings, and plant information.
- Routing: React Router DOM for navigation within the SPA.
- UI Components: Radix UI or Headless UI for accessible and customizable UI components.
- Charting: Recharts or Chart.js for visualizing sensor data.
- Real-time Communication: MQTT.js library for connecting to and receiving data from hydroponic system controllers (assuming controllers use MQTT).
- Local Storage: For persisting user preferences and settings offline.
- Icons: Heroicons or Font Awesome.
- Build Tool: Vite (if using CRA) or Next.js's built-in build process.
CORE FEATURES:
1. **Dashboard Overview:**
* **User Flow:** Upon login/access, the user lands on a central dashboard displaying the current status of their RackFarm system. This includes key environmental metrics, active plant growth cycles, and any critical alerts.
* **Details:** Displays real-time readings for temperature, humidity, water level, and nutrient concentration (if sensors are available). Shows the current phase of the active plant growth cycle. Highlights any active alerts (e.g., low water, temperature out of range).
2. **Environment Monitoring:**
* **User Flow:** User navigates to the 'Monitoring' section to view detailed historical and real-time sensor data. They can select different time ranges (e.g., last hour, last day, last week) and specific sensors.
* **Details:** Displays line or area charts for temperature, humidity, pH, EC (Electrical Conductivity), and water level. Allows users to toggle between sensors and adjust the time frame. Data is fetched via MQTT subscriptions.
3. **System Control:**
* **User Flow:** User navigates to the 'Control' section to manage the hydroponic system's actuators (pumps, lights, fans, nutrient dosers). They can initiate manual cycles or adjust automated schedules.
* **Details:** Provides interface elements (buttons, sliders, input fields) to manually turn pumps on/off, adjust light timers, set fan speeds, and configure nutrient dosing schedules. Commands are sent via MQTT to the system controller.
4. **Plant Management:**
* **User Flow:** User accesses the 'Plants' section to add new plant profiles, view details of existing plants, and start new growth cycles. They can select from a predefined library or add custom plant data.
* **Details:** Features a searchable database of common hydroponic plants with optimal temperature, humidity, light, and nutrient requirements. Users can select a plant, define the cabinet space, and initiate a 'Growth Cycle'. The system logs the start date and expected duration.
5. **Alerts & Notifications:**
* **User Flow:** User views a list of past and current alerts in the 'Alerts' section. They can configure notification preferences (e.g., email, in-app push).
* **Details:** System automatically generates alerts based on predefined thresholds (e.g., temperature < 15°C or > 30°C, humidity < 40% or > 70%, water level critical). Alerts are displayed prominently on the dashboard and logged chronologically.
UI/UX DESIGN:
- **Layout:** Single-page application with a persistent sidebar navigation (Dashboard, Monitoring, Control, Plants, Settings, Alerts). The main content area dynamically updates based on the selected navigation item. Use a clean, modern, and intuitive layout.
- **Color Palette:** Primary: Dark charcoal/deep blue (evoking server racks, tech). Secondary: Vibrant green (representing plant life, growth). Accent: Bright cyan or teal for interactive elements and alerts. Neutral: Light grays for text and backgrounds. Ensure good contrast for readability.
- **Typography:** Use a clean, sans-serif font family like Inter or Poppins for headings and body text. Ensure optimal readability across different screen sizes.
- **Responsive Design:** Mobile-first approach. The layout should adapt seamlessly from small mobile screens to large desktop monitors. Sidebar might collapse into a hamburger menu on smaller screens. Use Tailwind CSS's responsive modifiers (sm:, md:, lg:, xl:) extensively.
- **Interactions:** Subtle hover effects on buttons and interactive elements. Smooth transitions for modal pop-ups and section changes. Loading indicators (spinners, skeleton screens) for data fetching operations.
DATA MODEL:
- **State Structure (Zustand/Redux Toolkit):**
* `auth`: { isLoggedIn: boolean, user: object | null }
* `systemStatus`: { temperature: number, humidity: number, lightLevel: number, waterLevel: number, ph: number, ec: number, pumpState: 'on' | 'off', lightState: 'on' | 'off', timestamp: string, connected: boolean }
* `plantLibrary`: Array<{ id: string, name: string, optimalTemp: { min: number, max: number }, optimalHumidity: { min: number, max: number }, lightHours: number, nutrientProfile: string }>
* `growthCycles`: Array<{ id: string, plantId: string, plantName: string, startDate: string, endDate: string | null, status: 'active' | 'completed' | 'paused', cabinetId: string }>
* `alerts`: Array<{ id: string, message: string, type: 'critical' | 'warning' | 'info', timestamp: string, resolved: boolean }>
* `settings`: { notificationPreferences: object, units: 'celsius' | 'fahrenheit', thresholds: object }
- **Mock Data Format:** Sensor data will be a stream of JSON objects. Plant library data will be static JSON arrays. Growth cycles and alerts will be dynamically managed objects/arrays.
COMPONENT BREAKDOWN:
- **`App.jsx`:** Main application component, sets up routing and global layout.
- **`Layout.jsx`:** Wrapper component handling the persistent sidebar and main content area. Uses `React Router`.
- **`Sidebar.jsx`:** Navigation menu component. Receives current route/active item as a prop.
- **`Dashboard.jsx`:** Main dashboard view. Fetches and displays summary data from `systemStatus` and `alerts` states. Contains `StatCard` and `AlertBanner` components.
- **`StatCard.jsx`:** Reusable card component to display a single metric (e.g., Temperature, Humidity) with its current value and unit. Receives `title`, `value`, `unit`, `icon` as props.
- **`ChartComponent.jsx`:** Generic charting component. Receives `data`, `dataKey`, `type`, `color` as props. Wraps `Recharts` or `Chart.js`.
- **`Monitoring.jsx`:** Displays detailed sensor data charts. Uses `ChartComponent` for each sensor type.
- **`ControlPanel.jsx`:** Interface for controlling pumps, lights, etc. Uses `ToggleButton.jsx`, `Slider.jsx`, `ScheduleConfigurator.jsx`.
- **`ToggleButton.jsx`:** Simple button component that toggles a state (e.g., pump on/off). Receives `label`, `currentState`, `onClick` handler as props.
- **`PlantLibrary.jsx`:** Displays the list of available plants. Includes search/filter functionality. Uses `PlantCard.jsx`.
- **`PlantCard.jsx`:** Displays information about a single plant type. Receives `plant` object as prop.
- **`GrowthCycleManager.jsx`:** Component to start new growth cycles and view active ones. Uses `PlantSelector.jsx`, `DatePicker.jsx`.
- **`AlertsList.jsx`:** Displays the list of alerts. Uses `AlertItem.jsx`.
- **`AlertItem.jsx`:** Displays a single alert. Receives `alert` object as prop. Includes a 'Resolve' button.
- **`Settings.jsx`:** User settings and configuration page. Includes `NotificationSettings.jsx`, `ThresholdsConfigurator.jsx`.
ANIMATIONS & INTERACTIONS:
- **Page Transitions:** Use `Framer Motion` or similar library for subtle fade-in/fade-out or slide animations when navigating between sections.
- **Data Loading:** Implement skeleton loaders or spinners using Tailwind CSS classes and state management to indicate when data is being fetched from the MQTT broker or API.
- **Hover Effects:** Subtle scaling or background color changes on interactive elements like buttons and cards.
- **Sensor Value Updates:** Animate the sensor value display when it updates, perhaps with a slight color change or a brief fade effect.
- **Alert Indicators:** Use subtle pulsing or color flash for critical alerts on the dashboard.
EDGE CASES:
- **No Sensor Data:** Display 'Disconnected' or 'N/A' clearly if the MQTT connection is lost or no data is received for a period. Show appropriate visual cues.
- **Empty States:** For `Dashboard`, `AlertsList`, `GrowthCycles` when there's no data yet, display user-friendly messages (e.g., 'No alerts yet.', 'Start your first growth cycle!').
- **Error Handling:** Implement try-catch blocks for all API calls and MQTT interactions. Display user-friendly error messages. Handle potential malformed data from the controller.
- **Validation:** Validate user inputs in forms (e.g., settings, new plant data) using libraries like Zod or Yup.
- **Accessibility (a11y):** Ensure all interactive elements are focusable and have clear focus states. Use semantic HTML. Provide ARIA attributes where necessary. Ensure sufficient color contrast.
- **Initial Setup:** Guide new users through the initial setup process, including connecting to their MQTT broker.
SAMPLE DATA:
1. **System Status (MQTT Payload Example):**
```json
{
"deviceId": "rackfarm-001",
"timestamp": "2023-10-27T10:30:00Z",
"temperature": 22.5,
"humidity": 55.2,
"lightLevel": 800,
"waterLevel": 75,
"ph": 6.1,
"ec": 1.8,
"pumpState": "off",
"lightState": "on"
}
```
2. **Plant Profile (Library):**
```json
{
"id": "lettuce-001",
"name": "Romaine Lettuce",
"optimalTemp": {"min": 15, "max": 24},
"optimalHumidity": {"min": 50, "max": 70},
"lightHours": 14,
"nutrientProfile": "Standard Grow A+B"
}
```
3. **Plant Profile (Library):**
```json
{
"id": "tomato-002",
"name": "Cherry Tomato",
"optimalTemp": {"min": 18, "max": 28},
"optimalHumidity": {"min": 45, "max": 65},
"lightHours": 16,
"nutrientProfile": "Fruiting Formula"
}
```
4. **Active Growth Cycle:**
```json
{
"id": "gc-abc123",
"plantId": "lettuce-001",
"plantName": "Romaine Lettuce",
"startDate": "2023-10-20T09:00:00Z",
"endDate": null,
"status": "active",
"cabinetId": "server-rack-xyz"
}
```
5. **Alert (Critical):**
```json
{
"id": "alert-xyz789",
"message": "Temperature critically low: 12°C",
"type": "critical",
"timestamp": "2023-10-27T10:25:00Z",
"resolved": false
}
```
6. **Alert (Warning):**
```json
{
"id": "alert-def456",
"message": "Humidity is above optimal range: 75%",
"type": "warning",
"timestamp": "2023-10-27T11:00:00Z",
"resolved": false
}
```
7. **Sensor Data Stream (Multiple Readings):**
```json
[
{"temperature": 22.7, "timestamp": "2023-10-27T10:31:00Z"},
{"humidity": 55.5, "timestamp": "2023-10-27T10:31:00Z"},
{"pumpState": "on", "timestamp": "2023-10-27T10:31:05Z"}
]
```
DEPLOYMENT NOTES:
- **Build:** Use `npm run build` (or `yarn build`) to create an optimized production build. The output will be in a `dist` or `.next/static` folder.
- **Environment Variables:** Use `.env` files for managing environment variables (e.g., `REACT_APP_MQTT_BROKER_URL`, `REACT_APP_API_BASE_URL`). Ensure these are correctly configured during the build process.
- **Hosting:** Deploy as a static site to platforms like Vercel, Netlify, or AWS S3/CloudFront. The MQTT client will need to be able to connect to your broker from the client's browser, so ensure CORS and security are configured appropriately on the MQTT broker if it's publicly accessible, or use a relay service.
- **Performance:** Optimize image loading. Code-split components using `React.lazy` and `Suspense` if the application grows significantly. Minimize bundle size by removing unused code and dependencies.
- **MQTT Connection:** The MQTT client (`mqtt.js`) runs in the browser. Ensure the MQTT broker is accessible from the client (consider using WebSockets for MQTT connections) and properly secured (authentication, authorization).
- **Backend (Optional/Future):** If a backend is needed for complex logic, user authentication, or managing connections, consider Node.js with Express/Fastify and a database (PostgreSQL/MongoDB). The current prompt focuses on a client-side SPA relying on direct MQTT communication.