Feature: Weather Service Integration
Relevant source files
The following files were used as context for generating this wiki page:
The Weather Service Integration is a core feature of the VineSight application, providing farmers with detailed weather data, forecasts, and derived agricultural insights. It fetches data from external APIs and processes it to generate actionable recommendations for irrigation, pest management, and harvest timing. The system is designed to be modular, with multiple data sources and a dedicated AI service for generating intelligent advisories.
This feature is primarily surfaced to the user through the "Weather Intelligence" page and specialized dashboard cards. It directly supports other modules by providing crucial data for Scientific Calculators and the AI Assistant.
Architecture Overview
The weather integration architecture is composed of UI components, backend services that abstract external APIs, and a serverless function for AI-powered analysis. There are two distinct weather service implementations, WeatherService and OpenMeteoWeatherService, which are used by different UI components.
The following diagram illustrates the high-level data flow:
Data Sources and Services
The system utilizes two separate services to fetch weather data from different providers, likely to leverage the specific strengths of each API.
WeatherService (WeatherAPI.com)
This service is the primary source for the main WeatherDashboard. It fetches comprehensive current and forecast data and includes business logic for calculating agricultural metrics.
- Source File:
src/lib/weather-service.ts - External API:
http://api.weatherapi.com/v1 - Authentication: Uses an API key stored in
process.env.NEXT_PUBLIC_WEATHER_API_KEY. - Fallback: Provides mock data via
getMockWeatherData()if the API key is missing or the request fails, ensuring functionality during development.
The class diagram below shows the structure of the WeatherService.
Sources: src/lib/weather-service.ts:85-455
OpenMeteoWeatherService (Open-Meteo)
This service is used by the more compact WeatherCard component and appears specialized for fetching daily aggregates and granular hourly data, such as solar radiation.
- Source File:
src/lib/open-meteo-weather.ts - External API:
https://api.open-meteo.com/v1/forecast - Key Methods:
getWeatherData(): Fetches a range of daily weather parameters.getHourlySolarRadiation(): Fetches hourly solar radiation and converts it to lux, calculating min, max, and average values.
Sources: src/lib/open-meteo-weather.ts
Data Models
The system uses several TypeScript interfaces to structure weather-related data.
WeatherData (from WeatherService)
This is the main data structure used by the WeatherDashboard.
| Property | Type | Description |
|---|---|---|
current | CurrentWeather | Real-time weather conditions. |
forecast | ForecastDay[] | An array of daily forecast data. |
location | LocationData | Geographic and timezone information. |
lastUpdated | Date | Timestamp of the last data fetch. |
| Sources: src/lib/weather-service.ts:1-7 |
OpenMeteoWeatherData
This structure is used by WeatherCard and is returned by the OpenMeteoWeatherService.
| Property | Type | Description |
|---|---|---|
date | string | The date for the weather data (YYYY-MM-DD). |
temperatureMax | number | Maximum daily temperature (°C). |
temperatureMin | number | Minimum daily temperature (°C). |
temperatureMean | number | Mean daily temperature (°C). |
relativeHumidityMax | number | Maximum daily relative humidity (%). |
relativeHumidityMin | number | Minimum daily relative humidity (%). |
relativeHumidityMean | number | Mean daily relative humidity (%). |
precipitationSum | number | Total daily precipitation (mm). |
windSpeed10m | number | Maximum wind speed at 10m (m/s). |
shortwaveRadiationSum | number | Total daily shortwave radiation (MJ/m²). |
sunshineDuration | number | Total daily sunshine duration (hours). |
et0FaoEvapotranspiration | number | Reference evapotranspiration (mm). |
timezone | string | The timezone of the location. |
elevation | number | The elevation of the location in meters. |
| Sources: src/lib/open-meteo-weather.ts:1-16 |
Agricultural Calculations & Insights
A key aspect of the feature is its ability to transform raw weather data into farming-specific advice.
Evapotranspiration (ETc) Calculation
The WeatherService.calculateETc method estimates the amount of water lost by the crop.
This diagram shows the calculation flow:
Sources: src/lib/weather-service.ts:218-255
The crop coefficients (kc) are hardcoded for various grape growth stages.
| Growth Stage | Crop Coefficient (Kc) |
|---|---|
| Budbreak | 0.3 |
| Leaf development | 0.5 |
| Flowering | 0.7 |
| Fruit set | 0.8 |
| Veraison | 0.8 |
| Harvest | 0.6 |
| Post-harvest | 0.4 |
| Dormant | 0.2 |
| Sources: src/lib/weather-service.ts:222-231, src/app/weather/page.tsx:160-167 |
Weather Alerts
The generateWeatherAlerts method assesses weather data to produce alerts for irrigation, pests, and harvesting.
- Irrigation Alert: Considers upcoming rain, rain probability, temperature, and humidity to determine if irrigation is needed and its urgency.
- Pest Alert: Assesses risk for fungal diseases based on humidity and temperature. It also checks for wet conditions and temperature extremes.
- Harvest Alert: Evaluates conditions for the next 5 days (rain, temperature) to determine if it's an optimal time for harvesting.
Sources: src/lib/weather-service.ts:273-410
Irrigation Scheduling
The generateIrrigationSchedule method creates a 7-day irrigation plan by performing a daily water balance calculation. It models soil moisture by subtracting daily ETc and adding rainfall, triggering irrigation when moisture drops below a 40% threshold of the soil's holding capacity.
Sources: src/lib/weather-service.ts:458-511
AI-Powered Weather Insights
The application includes a dedicated API endpoint to generate high-level, actionable insights from weather data using a large language model.
- Endpoint:
POST /api/ai/weather-insights - Source File:
src/app/api/ai/weather-insights/route.ts - AI Model:
google/gemini-2.0-flash-lite
The sequence diagram below illustrates the process of generating AI insights.
The API expects a POST request with weatherData, farmData, and history, and returns an array of WeatherInsightData objects.
WeatherInsightData Interface
| Property | Type | Description |
|---|---|---|
type | string | The type of advisory (e.g., "weather_advisory"). |
priority | 'critical' | 'high' | 'medium' | 'low' | The urgency of the insight. |
title | string | A concise title for the insight. |
subtitle | string | A subtitle with specific conditions and metrics. |
confidence | number | The AI's confidence in the insight (0.0-1.0). |
timeRelevant | boolean | Indicates if the insight is time-sensitive. |
actionLabel | string | Suggested text for an action button. |
| Sources: src/app/api/ai/weather-insights/route.ts:4-12 |
UI Components
The weather feature is presented to the user through several React components.
WeatherPage
This is the main entry point for the "Weather Intelligence" feature. It allows the user to select a farm, the current growth stage of the crop, and the soil type. These selections are then passed as props to the WeatherDashboard component.
Sources: src/app/weather/page.tsx
WeatherDashboard
This is the primary component for displaying comprehensive weather information. It uses WeatherService to fetch data and orchestrates the display of:
- Current weather overview (temperature, humidity, wind, etc.).
- ETc calculations.
- Irrigation recommendations and schedule.
- Pest and harvest alerts.
- A 7-day forecast.
Sources: src/components/weather/WeatherDashboard.tsx
WeatherCard
A more compact, focused component intended for display on other dashboards (e.g., FarmerDashboard). It uses the OpenMeteoWeatherService to display:
- Today's temperature (min/max/avg) and humidity.
- Wind speed and rainfall.
- Solar radiation data, including total energy (MJ/m²) and average daylight intensity (lux).
- Reference Evapotranspiration (ETo).
Sources: src/components/farm-details/WeatherCard.tsx
Summary
The Weather Service Integration is a sophisticated feature that abstracts multiple external data sources to provide tailored agricultural intelligence. It separates concerns effectively, with dedicated services for data fetching (WeatherService, OpenMeteoWeatherService), a robust set of internal calculations for agricultural metrics (ETc, alerts), and a modern AI-driven layer for generating high-level insights (/api/ai/weather-insights). The modular UI components (WeatherDashboard, WeatherCard) consume these services to present the information to the user in different contexts. The system's use of fallback mock data and two distinct external APIs demonstrates a resilient and flexible design.