From e72d461461ae5f09bcd46d382731a26dd236deab Mon Sep 17 00:00:00 2001 From: Roland Date: Wed, 31 Jul 2024 12:41:53 -0600 Subject: [PATCH] Refusing to start hotspot if Wifi device is in use. --- app/src/components/Common.js | 55 +++++++++++++++++++++++++++--------- app/src/hooks/customHooks.js | 10 +++++-- wrolpi/admin.py | 40 ++++++++++++++++++++++++-- wrolpi/root_api.py | 3 +- 4 files changed, 90 insertions(+), 18 deletions(-) diff --git a/app/src/components/Common.js b/app/src/components/Common.js index ed8b3858..752cc314 100644 --- a/app/src/components/Common.js +++ b/app/src/components/Common.js @@ -1042,30 +1042,59 @@ export function UnsupportedModal(header, message, icon) { } export function HotspotStatusIcon() { - const {on, setHotspot, dockerized} = useHotspot(); - const {modal, doOpen} = UnsupportedModal('Unsupported', 'You cannot toggle the hotspot on this machine.'); - const [confirmOpen, setConfirmOpen] = React.useState(false); + const {on, inUse, setHotspot, dockerized, hotspotSsid} = useHotspot(); + const {modal: unsupportedModal, doOpen: openUnsupportedModal} = + UnsupportedModal('Unsupported', 'You cannot toggle the hotspot on this machine.'); + const [disableHotspotOpen, setDisableHotspotOpen] = React.useState(false); + const [inUseOpen, setInUseOpen] = React.useState(false); - const handleConfirm = (e) => { + const handleConfirmDisable = (e) => { if (e) { e.preventDefault() } - setConfirmOpen(false); + setDisableHotspotOpen(false); setHotspot(false); } - if (dockerized === false && on === true) { + const handleConfirmInUse = (e) => { + if (e) { + e.preventDefault() + } + setInUseOpen(false); + setHotspot(true); + } + + if (inUse === true) { + const content = hotspotSsid ? `Wifi device is in use for ${hotspotSsid}. Disconnect and enable hotspot?` + : 'Wifi device is in use. Disconnect and enable hotspot?' + return <> + setInUseOpen(false)} + onClose={() => setInUseOpen(false)} + onConfirm={handleConfirmInUse} + header='Wifi is in-use' + content={content} + confirmButton='Enable Hotspot' + /> + setInUseOpen(true)}> + + + + + + + } else if (dockerized === false && on === true) { return <> setConfirmOpen(false)} - onClose={() => setConfirmOpen(false)} - onConfirm={handleConfirm} + open={disableHotspotOpen} + onCancel={() => setDisableHotspotOpen(false)} + onClose={() => setDisableHotspotOpen(false)} + onConfirm={handleConfirmDisable} header='Disable the hotspot' content='You will be disconnected when using the hotspot. Are you sure?' confirmButton='Disable' /> - setConfirmOpen(true)}> + setDisableHotspotOpen(true)}> {on === false && } @@ -1084,13 +1113,13 @@ export function HotspotStatusIcon() { // Hotspot is not available, or, status has not yet been fetched. return <> - + - {modal} + {unsupportedModal} } diff --git a/app/src/hooks/customHooks.js b/app/src/hooks/customHooks.js index fa3a52be..beb40eae 100644 --- a/app/src/hooks/customHooks.js +++ b/app/src/hooks/customHooks.js @@ -623,17 +623,23 @@ export const useFilesProgressInterval = () => { export const useHotspot = () => { const [on, setOn] = useState(null); + const [inUse, setInUse] = useState(false); const {status} = useContext(StatusContext); // Hotspot is unsupported on Docker. - const {dockerized} = status; + const {dockerized, hotspot_ssid} = status; useEffect(() => { if (status && status['hotspot_status']) { const {hotspot_status} = status; if (hotspot_status === 'connected') { setOn(true); + setInUse(false); + } else if (hotspot_status === 'in_use') { + setInUse(true); + setOn(false); } else if (hotspot_status === 'disconnected' || hotspot_status === 'unavailable') { setOn(false); + setInUse(false); } else { setOn(null); } @@ -645,7 +651,7 @@ export const useHotspot = () => { await setHotspot(on); } - return {on, setOn, setHotspot: localSetHotspot, dockerized}; + return {on, inUse, hotspotSsid: hotspot_ssid, setOn, setHotspot: localSetHotspot, dockerized}; } export const useDownloads = () => { diff --git a/wrolpi/admin.py b/wrolpi/admin.py index dcf11e64..7ac8240f 100644 --- a/wrolpi/admin.py +++ b/wrolpi/admin.py @@ -20,12 +20,19 @@ class HotspotStatus(enum.Enum): unavailable = enum.auto() # Radio is off. connected = enum.auto() # Radio is on, Hotspot is on. unknown = enum.auto() # Unknown status. Hotspot may not be supported on this hardware. + in_use = enum.auto() # WI-FI device is in use, and cannot be used for Hotspot. def hotspot_status() -> HotspotStatus: if NMCLI_BIN is None: return HotspotStatus.unknown + device = WROLPI_CONFIG.hotspot_device + + if get_current_ssid(device): + # Hotspot device is currently connected to a WI-FI network. + return HotspotStatus.in_use + cmd = (NMCLI_BIN,) try: output = subprocess.check_output(cmd, stderr=subprocess.PIPE).decode().strip() @@ -33,7 +40,6 @@ def hotspot_status() -> HotspotStatus: warn_once(e) return HotspotStatus.unknown - device = WROLPI_CONFIG.hotspot_device for line in output.splitlines(): if line.startswith(f'{device}: connected'): return HotspotStatus.connected @@ -45,7 +51,30 @@ def hotspot_status() -> HotspotStatus: return HotspotStatus.unknown -def enable_hotspot(depth: int = 10): +def get_current_ssid(interface='wlan0') -> str | None: + """Returns the name of the SSID that is currently connected. Returns None if Hotspot, or no WIFI network is being + used.""" + try: + # Run the iwgetid command and capture the output + cmd = ('iwgetid', interface, '--raw') + result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) + + # Check if the command was successful + if result.returncode == 0: + ssid = result.stdout.strip() + return ssid + elif result.returncode == 255: + # Hotspot is in use. + return None + else: + print(f"Error: {result.stderr}") + return None + except Exception as e: + print(f"Exception occurred: {e}") + return None + + +def enable_hotspot(depth: int = 10, overwrite: bool = False): """Turn the Wi-Fi interface into a hotspot. If Wi-Fi is already running, replace that with a hotspot. @@ -56,10 +85,17 @@ def enable_hotspot(depth: int = 10): status = hotspot_status() logger.info(f'Hotspot status: {status}') + if overwrite is False and (current_ssid := get_current_ssid(WROLPI_CONFIG.hotspot_device)): + raise RuntimeError(f'Refusing to start hotspot because Wi-Fi device is already being used for {current_ssid}.') + if status == HotspotStatus.connected: logger.info('Hotspot already connected. Rebooting hotspot.') disable_hotspot() return enable_hotspot(depth=depth - 1) + elif status == HotspotStatus.in_use: + logger.info('Wifi already in use. Rebooting hotspot.') + disable_hotspot() + return enable_hotspot(depth=depth - 1) elif status == HotspotStatus.disconnected: # Radio is on, but not connected. Good, turn it into a hotspot. cmd = (SUDO_BIN, NMCLI_BIN, 'device', 'wifi', 'hotspot', 'ifname', WROLPI_CONFIG.hotspot_device, diff --git a/wrolpi/root_api.py b/wrolpi/root_api.py index 4d2263ae..09282acc 100644 --- a/wrolpi/root_api.py +++ b/wrolpi/root_api.py @@ -371,7 +371,7 @@ async def get_downloaders(_: Request): @openapi.description('Turn on the hotspot') @native_only async def hotspot_on(_: Request): - result = admin.enable_hotspot() + result = admin.enable_hotspot(overwrite=True) if result: return response.empty() return response.empty(HTTPStatus.INTERNAL_SERVER_ERROR) @@ -430,6 +430,7 @@ async def get_status(_: Request): drives=s.drives, flags=flags.get_flags(), hotspot_status=admin.hotspot_status().name, + hotspot_ssid=admin.get_current_ssid(get_wrolpi_config().hotspot_device), load=s.load, memory_stats=s.memory_stats, throttle_status=admin.throttle_status().name,