using UnityEngine;
using System;
using System.Net;
using System.Collections.Generic;
using Newtonsoft.Json;
public class DatabaseConnector : MonoBehaviour
{
[Serializable]
public class SensorReading
{
public string sensor_id;
public float reading_value;
}
public string apiUrl = "http://localhost/sensor_data/test.php";
public float updateInterval = 1f;
private List<SensorReading> sensorReadings = new List<SensorReading>();
private void Start()
{
ServicePointManager.ServerCertificateValidationCallback += (sender, cert, chain, sslPolicyErrors) => true;
InvokeRepeating("FetchData", 0f, updateInterval);
}
private void FetchData()
{
try
{
using (WebClient client = new WebClient())
{
string jsonResult = client.DownloadString(apiUrl);
Debug.Log("Received JSON: " + jsonResult);
sensorReadings = JsonConvert.DeserializeObject<List<SensorReading>>(jsonResult);
DisplaySensorReadings();
}
}
catch (WebException e)
{
Debug.LogError("WebException Error: " + e.Message);
if (e.Response != null)
{
using (var errorResponse = (HttpWebResponse)e.Response)
{
Debug.LogError("HTTP Status Code: " + errorResponse.StatusCode);
using (var reader = new System.IO.StreamReader(errorResponse.GetResponseStream()))
{
string errorText = reader.ReadToEnd();
Debug.LogError("Error Response Body: " + errorText);
}
}
}
}
catch (JsonException je)
{
Debug.LogError("JSON Parsing Error: " + je.Message);
}
catch (Exception ex)
{
Debug.LogError("General Error: " + ex.Message);
}
}
private void DisplaySensorReadings()
{
foreach (SensorReading reading in sensorReadings)
{
Debug.Log($"Sensor ID: {reading.sensor_id}, Value: {reading.reading_value}");
}
}
}