Skip to content

Commit

Permalink
Merge pull request #20 from columbiaspace/setup-status
Browse files Browse the repository at this point in the history
created a status indicator for the setup page
  • Loading branch information
adenjonah authored May 15, 2024
2 parents d6c2010 + 9e078bc commit 09e53c6
Show file tree
Hide file tree
Showing 8 changed files with 230 additions and 73 deletions.
5 changes: 5 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,8 @@ tss_data.json
*.pyc
tss_data.json
tss_data.json
tss_data.json
__pycache__/server.cpython-312.pyc
config_keys.json
__pycache__/server.cpython-312.pyc
tss_data.json
46 changes: 44 additions & 2 deletions server.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from fastapi import FastAPI, HTTPException, Request
from fastapi import FastAPI, HTTPException, Request, Query
import httpx
from fastapi.middleware.cors import CORSMiddleware
import logging
Expand Down Expand Up @@ -46,7 +46,8 @@ async def startup_event():
default_config_data = {
"TSS_IP": "localhost:14141",
"MAPBOX_KEY": "your_mapbox_key_here",
"HOLO_IP": "your_holo_ip_here"
"HOLO_IP": "your_holo_ip_here",
"SERVER_IP": "localhost:8000" # Assuming a default server IP
}

# Load existing config if it exists, otherwise use the default
Expand Down Expand Up @@ -86,6 +87,13 @@ async def update_config(request: Request):

return {"message": "Config updated successfully"}

@app.get("/config")
async def get_config():
"""Endpoint to get the current configuration."""
with open(CONFIG_FILE, 'r') as f:
config_data = json.load(f)
return config_data

async def periodic_fetch_and_store():
"""Fetch specific JSON data every second and store it."""
eva_url = f"http://{tss_ip}/json_data/teams/0/EVA.json"
Expand Down Expand Up @@ -125,6 +133,40 @@ async def get_mapbox_key():
config = json.load(f)
return {"MAPBOX_KEY": config["MAPBOX_KEY"]}

# New endpoint to check connection
@app.get("/check_connection")
async def check_connection(tss_ip: str = None, holo_ip: str = None, server_ip: str = None):
async with httpx.AsyncClient() as client:
if tss_ip:
try:
response = await client.get(f"http://{tss_ip}/")
if response.status_code == 200:
return {"status": "connected", "type": "TSS_IP"}
else:
return {"status": "no connection", "type": "TSS_IP"}
except Exception:
return {"status": "no connection", "type": "TSS_IP"}
elif holo_ip:
try:
response = await client.get(f"https://{holo_ip}/")
if response.status_code == 200:
return {"status": "connected", "type": "HOLO_IP"}
else:
return {"status": "no connection", "type": "HOLO_IP"}
except Exception:
return {"status": "no connection", "type": "HOLO_IP"}
elif server_ip:
try:
response = await client.get(f"http://{server_ip}/docs")
if response.status_code == 200:
return {"status": "connected", "type": "SERVER_IP"}
else:
return {"status": "no connection", "type": "SERVER_IP"}
except Exception:
return {"status": "no connection", "type": "SERVER_IP"}
else:
raise HTTPException(status_code=400, detail="Invalid request, provide either tss_ip, holo_ip, or server_ip")

# Existing endpoints
@app.get("/json_data/{filename}")
async def get_general_json(filename: str):
Expand Down
1 change: 0 additions & 1 deletion src/components/Map.js
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,6 @@ const MapboxComponent = () => {
});
});


return () => {
markers.forEach((marker) => marker.marker.remove());
landmarks.forEach((landmark) => landmark.marker.remove());
Expand Down
Empty file removed src/pages-style/setup 2.css
Empty file.
23 changes: 22 additions & 1 deletion src/pages-style/setup.css
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,25 @@
display: flex;
align-items: center;
justify-content: center;
}
}

.status {
width: 10px;
height: 10px;
border-radius: 50%;
display: inline-block;
margin-left: 10px;
}

.status.green {
background-color: green;
}

.status.yellow {
background-color: yellow;
}

.status.red {
background-color: red;
}

51 changes: 51 additions & 0 deletions src/pages/focus/MapboxComponent.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React, { useEffect, useState } from "react";
import mapboxgl from "mapbox-gl/dist/mapbox-gl.js";
import "mapbox-gl/dist/mapbox-gl.css";

const MapboxComponent = ({ handleMapBoxAPIStatus }) => {
const [mapBoxAPIKey, setMapBoxAPIKey] = useState(null);

useEffect(() => {
const fetchMapBoxAPIKey = async () => {
try {
const response = await fetch("http://localhost:8000/get_mapbox_key");
const data = await response.json();
setMapBoxAPIKey(data.MAPBOX_KEY);
checkMapboxAPIKey(data.MAPBOX_KEY);
} catch (error) {
console.error("Error fetching MapBox API key:", error);
handleMapBoxAPIStatus("red");
}
};

fetchMapBoxAPIKey();
}, [handleMapBoxAPIStatus]);

const checkMapboxAPIKey = (key) => {
handleMapBoxAPIStatus('yellow'); // Set to yellow while checking
const tempDiv = document.createElement('div');
tempDiv.style.display = 'none';
document.body.appendChild(tempDiv);

const map = new mapboxgl.Map({
container: tempDiv,
accessToken: key,
});

map.on('load', () => {
handleMapBoxAPIStatus('green');
map.remove();
document.body.removeChild(tempDiv);
});

map.on('error', () => {
handleMapBoxAPIStatus('red');
map.remove();
document.body.removeChild(tempDiv);
});
};

return null;
};

export default MapboxComponent;
129 changes: 108 additions & 21 deletions src/pages/focus/setup.js
Original file line number Diff line number Diff line change
@@ -1,13 +1,55 @@
import React, { useState } from 'react';
import { getTSS_IP, setTSS_IP, getHOLO_IP, setHOLO_IP, getMapBox_API, setMapBox_API, getSERVER_IP, setSERVER_IP } from '../../helpers/ipAddress';
import React, { useState, useEffect } from 'react';
import '../../pages-style/page.css';
import '../../pages-style/setup.css';
import MapboxComponent from '../../components/Map.js';
import mapboxgl from "mapbox-gl/dist/mapbox-gl.js"; // Import mapboxgl here

function Setup() {
const [, setTssIP] = useState(getTSS_IP());
const [, setHoloIP] = useState(getHOLO_IP());
const [, setMapBoxAPI] = useState(getMapBox_API());
const [, setServerIP] = useState(getSERVER_IP());
const [tssIP, setTssIP] = useState('');
const [holoIP, setHoloIP] = useState('');
const [mapBoxAPI, setMapBoxAPI] = useState('');
const [serverIP, setServerIP] = useState('');

const [tssIPStatus, setTssIPStatus] = useState('yellow');
const [holoIPStatus, setHoloIPStatus] = useState('yellow');
const [serverIPStatus, setServerIPStatus] = useState('yellow');
const [mapBoxAPIStatus, setMapBoxAPIStatus] = useState('yellow');

useEffect(() => {
const fetchConfig = async () => {
try {
const response = await fetch('http://localhost:8000/config');
const config = await response.json();
setTssIP(config.TSS_IP);
setHoloIP(config.HOLO_IP);
setMapBoxAPI(config.MAPBOX_KEY);
setServerIP(config.SERVER_IP);

checkConnection(config.TSS_IP, setTssIPStatus, 'tss_ip');
checkConnection(config.HOLO_IP, setHoloIPStatus, 'holo_ip');
checkConnection(config.SERVER_IP, setServerIPStatus, 'server_ip');
// Check Mapbox API Key
checkMapboxAPIKey(config.MAPBOX_KEY);
} catch (error) {
console.error('Error fetching config:', error);
}
};
fetchConfig();
}, []);

const checkConnection = async (key, setStatus, type) => {
try {
const response = await fetch(`http://localhost:8000/check_connection?${type}=${key}`);
const result = await response.json();
if (result.status === 'connected') {
setStatus('green');
} else {
setStatus('red');
}
} catch (error) {
setStatus('red');
}
};

const updateConfigOnServer = async (newConfig) => {
try {
Expand All @@ -20,48 +62,86 @@ function Setup() {
});
const result = await response.json();
console.log(result.message);

if (newConfig.TSS_IP) checkConnection(newConfig.TSS_IP, setTssIPStatus, 'tss_ip');
if (newConfig.HOLO_IP) checkConnection(newConfig.HOLO_IP, setHoloIPStatus, 'holo_ip');
if (newConfig.SERVER_IP) checkConnection(newConfig.SERVER_IP, setServerIPStatus, 'server_ip');
if (newConfig.MAPBOX_KEY) {
checkMapboxAPIKey(newConfig.MAPBOX_KEY);
}
} catch (error) {
console.error('Error updating config:', error);
}
};

const checkMapboxAPIKey = (key) => {
setMapBoxAPIStatus('yellow'); // Set to yellow while checking
const tempDiv = document.createElement('div');
tempDiv.style.display = 'none';
document.body.appendChild(tempDiv);

const map = new mapboxgl.Map({
container: tempDiv,
style: 'mapbox://styles/mapbox/streets-v11',
center: [-74.5, 40],
zoom: 9,
accessToken: key,
});

map.on('load', () => {
setMapBoxAPIStatus('green');
map.remove();
document.body.removeChild(tempDiv);
});

map.on('error', () => {
setMapBoxAPIStatus('red');
map.remove();
document.body.removeChild(tempDiv);
});
};

const handleSetTSS_IP = () => {
const inputTSS_IP = document.getElementById('tss_ip').value;
setTSS_IP(inputTSS_IP);
setTssIP(inputTSS_IP);
updateConfigOnServer({
TSS_IP: inputTSS_IP,
MAPBOX_KEY: getMapBox_API(),
HOLO_IP: getHOLO_IP(),
MAPBOX_KEY: mapBoxAPI,
HOLO_IP: holoIP,
SERVER_IP: serverIP,
});
};

const handleSetSERVER_IP = () => {
const inputSERVER_IP = document.getElementById('server_ip').value;
setSERVER_IP(inputSERVER_IP);
setServerIP(inputSERVER_IP);
// Update the config file accordingly if SERVER_IP needs to be added
updateConfigOnServer({
TSS_IP: tssIP,
MAPBOX_KEY: mapBoxAPI,
HOLO_IP: holoIP,
SERVER_IP: inputSERVER_IP,
});
};

const handleSetHOLO_IP = () => {
const inputHOLO_IP = document.getElementById('holo_ip').value;
setHOLO_IP(inputHOLO_IP);
setHoloIP(inputHOLO_IP);
updateConfigOnServer({
TSS_IP: getTSS_IP(),
MAPBOX_KEY: getMapBox_API(),
TSS_IP: tssIP,
MAPBOX_KEY: mapBoxAPI,
HOLO_IP: inputHOLO_IP,
SERVER_IP: serverIP,
});
};

const handleSetMapBoxAPI = () => {
const inputMapBox_API = document.getElementById('mapbox_api').value;
setMapBox_API(inputMapBox_API);
setMapBoxAPI(inputMapBox_API);
updateConfigOnServer({
TSS_IP: getTSS_IP(),
TSS_IP: tssIP,
MAPBOX_KEY: inputMapBox_API,
HOLO_IP: getHOLO_IP(),
HOLO_IP: holoIP,
SERVER_IP: serverIP,
});
};

Expand All @@ -73,25 +153,32 @@ function Setup() {
<div className='entryBoxes'>
<div className='dataEntry'>
<label htmlFor='tss_ip'>TSS IP Address: </label>
<input type='text' id='tss_ip' name='tss_ip' defaultValue={getTSS_IP()} />
<input type='text' id='tss_ip' name='tss_ip' defaultValue={tssIP} />
<button onClick={handleSetTSS_IP}>Set TSS IP</button>
<span className={`status ${tssIPStatus}`}></span>
</div>
<div className='dataEntry'>
<label htmlFor='server_ip'>Server IP Address:</label>
<input type='text' id='server_ip' name='server_ip' defaultValue={getSERVER_IP()} />
<input type='text' id='server_ip' name='server_ip' defaultValue={serverIP} />
<button onClick={handleSetSERVER_IP}>Set Server IP</button>
<span className={`status ${serverIPStatus}`}></span>
</div>
<div className='dataEntry'>
<label htmlFor='holo_ip'>HOLO Lens IP Address: </label>
<input type='text' id='holo_ip' name='holo_ip' defaultValue={getHOLO_IP()} />
<input type='text' id='holo_ip' name='holo_ip' defaultValue={holoIP} />
<button onClick={handleSetHOLO_IP}>Set HOLO IP</button>
<span className={`status ${holoIPStatus}`}></span>
</div>
<div className='dataEntry'>
<label htmlFor='mapbox_api'>Map Box API Key: </label>
<input type='text' id='mapbox_api' name='mapbox_api' defaultValue={getMapBox_API()} />
<input type='text' id='mapbox_api' name='mapbox_api' defaultValue={mapBoxAPI} />
<button onClick={handleSetMapBoxAPI}>Set MapBox API Key</button>
<span className={`status ${mapBoxAPIStatus}`}></span>
</div>
</div>
<div style={{ display: 'none' }}>
<MapboxComponent handleMapBoxAPIStatus={setMapBoxAPIStatus} />
</div>
</div>
);
}
Expand Down
Loading

0 comments on commit 09e53c6

Please sign in to comment.