@@ -28,10 +28,41 @@ const generateInverterStatus = () => {
2828
2929const generateBatteryLevel = ( ) => Math . max ( 20 , Math . min ( 100 , Math . floor ( Math . random ( ) * 30 ) + 70 ) ) ;
3030const generateEnergyConsumption = ( ) => Math . floor ( Math . random ( ) * 500 ) + 100 ;
31- const generateSensorData = ( ) => ( {
32- temperature : Math . floor ( Math . random ( ) * 10 ) + 28 ,
33- humidity : Math . floor ( Math . random ( ) * 20 ) + 60
34- } ) ;
31+ const generateSensorData = async ( ) => {
32+ const latitude = 25.2500 ; // Bhagalpur coordinates
33+ const longitude = 87.0169 ;
34+
35+ try {
36+ const url = `https://api.open-meteo.com/v1/forecast?latitude=${ latitude } &longitude=${ longitude } ¤t_weather=true&hourly=relativehumidity_2m` ;
37+ const response = await fetch ( url ) ;
38+ const data = await response . json ( ) ;
39+ if (
40+ data &&
41+ data . current_weather &&
42+ typeof data . current_weather . temperature === "number"
43+ ) {
44+ const temperature = data . current_weather . temperature ;
45+ const humidity =
46+ data . hourly ?. relativehumidity_2m ?. [ 0 ] ??
47+ Math . floor ( Math . random ( ) * 20 ) + 60 ; // fallback if humidity missing
48+ return { temperature, humidity } ;
49+ } else {
50+ // Invalid data → fallback
51+ return {
52+ temperature : Math . floor ( Math . random ( ) * 10 ) + 28 ,
53+ humidity : Math . floor ( Math . random ( ) * 20 ) + 60 ,
54+ } ;
55+ }
56+ } catch ( error ) {
57+ console . error ( "API error:" , error ) ;
58+ // API failed → fallback
59+ return {
60+ temperature : Math . floor ( Math . random ( ) * 10 ) + 28 ,
61+ humidity : Math . floor ( Math . random ( ) * 20 ) + 60 ,
62+ } ;
63+ }
64+ } ;
65+
3566
3667const initializeClientData = ( socketId ) => {
3768 connectedClients . set ( socketId , {
@@ -95,10 +126,10 @@ io.on('connection', (socket) => {
95126 }
96127 } , 5000 ) ;
97128
98- intervals . sensor = setInterval ( ( ) => {
129+ intervals . sensor = setInterval ( async ( ) => {
99130 const clientData = connectedClients . get ( socket . id ) ;
100131 if ( clientData ) {
101- const sensorData = generateSensorData ( ) ;
132+ const sensorData = await generateSensorData ( ) ;
102133 clientData . temperature = sensorData . temperature ;
103134 clientData . humidity = sensorData . humidity ;
104135 socket . emit ( 'sensorData' , sensorData ) ;
0 commit comments