Skip to content

Commit

Permalink
feat: support offline mode (#29)
Browse files Browse the repository at this point in the history
  • Loading branch information
rmoesbergen authored Mar 30, 2024
1 parent d834922 commit 400a69e
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 1 deletion.
4 changes: 3 additions & 1 deletion deps/tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from conf import settings
from deps.logs import logger
from deps.utils import repeat_every
from deps.utils import repeat_every, check_for_internet


@asynccontextmanager
Expand All @@ -20,6 +20,8 @@ async def startup(_app: FastAPI) -> None:
@repeat_every(seconds=settings.library_index_refresh_interval, logger=logger)
async def refresh_library_index():
"""Update the Arduino library index"""
if not check_for_internet():
return
logger.info("Updating library index...")
installer = await asyncio.create_subprocess_exec(
settings.arduino_cli_path,
Expand Down
14 changes: 14 additions & 0 deletions deps/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from traceback import format_exception
from typing import Any, Callable, Coroutine, Optional, Union

import httpx
from starlette.concurrency import run_in_threadpool

NoArgsNoReturnFuncT = Callable[[], None]
Expand Down Expand Up @@ -85,3 +86,16 @@ async def loop() -> None:
return wrapped

return decorator


async def check_for_internet() -> bool:
"""Check if internet connection is available"""
client = httpx.AsyncClient()
try:
response = await client.get(
"https://downloads.arduino.cc", headers={"User-Agent": ""}
)
response.raise_for_status()
except (httpx.RequestError, httpx.HTTPError):
return False
return True
4 changes: 4 additions & 0 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
from deps.logs import logger
from deps.session import Session, sessions
from deps.tasks import startup
from deps.utils import check_for_internet
from models import Sketch, Library, PythonProgram

app = FastAPI(lifespan=startup)
Expand All @@ -32,6 +33,9 @@

async def _install_libraries(libraries: list[Library]) -> None:
# Install required libraries
if not check_for_internet():
logger.warning("No internet connection, skipping library install")
return
for library in libraries:
if library_cache.get(library):
continue
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ pydantic-settings==2.2.1
cachetools==5.3.3
python-minifier==2.9.0
pyserial==3.5
httpx==0.27.0

0 comments on commit 400a69e

Please sign in to comment.