Skip to content

Instantly share code, notes, and snippets.

@rsmoorthy
Last active October 3, 2022 18:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsmoorthy/30e2b373cf4fcae59af12af060d21134 to your computer and use it in GitHub Desktop.
Save rsmoorthy/30e2b373cf4fcae59af12af060d21134 to your computer and use it in GitHub Desktop.
Raspberry PI - Switch between Hotspot and Wifi modes

Inspiration from http://www.raspberryconnect.com/network/item/330-raspberry-pi-auto-wifi-hotspot-switch-internet

Pre-requisites:

  • A working Wifi (configured in /etc/wpa_supplicant/wpa_supplicant.conf)
  • A working hotspot setup (configured in /etc/hostapd/hostapd.conf)
  • The /etc/dhcpcd.conf file has following contents:
interface wlan0
  nohook wpa_supplicant

Installation:

  • Copy the file autohotspot to /usr/bin/autohotspot and chmod a+x

  • Copy the file autohotspot.service to /etc/systemd/system/

  • systemctl enable autohotspot

  • Create a file /boot/wificfg.txt with a single line. The contents supported are:

    • hotspot
      • Automatically start Raspberry PI in hotspot mode
    • wifi
      • Automatically start Raspberry PI in wifi mode
    • wifiOrhotspot
      • While booting, Try Wifi client for 10s, if not connected, Start hotspot mode
  • If the file /boot/wificfg.txt is not present, then start in hotspot mode

[Unit]
Description=Automatically generates an internet Hotspot when a valid ssid is not in range
After=multi-user.target
[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/autohotspot service
[Install]
WantedBy=multi-user.target
#!/bin/bash
echo "$1"
function show_status() {
sleep 2
ifconfig wlan0
iwconfig
ps auxww | grep wpa_supplicant
systemctl status dnsmasq
systemctl status hostapd
}
function hotspot_off() {
echo "Stopping hotspot and starting normal"
ip link set dev wlan0 down
systemctl stop dnsmasq
systemctl stop hostapd
ip addr flush wlan0
ip link set dev wlan0 up
wpa_supplicant -B -i wlan0 -c /etc/wpa_supplicant/wpa_supplicant.conf
dhcpcd -n wlan0
}
function hotspot_on() {
echo "Creating hotspot"
wpa_cli terminate
ip addr flush wlan0
ip link set dev wlan0 down
rm -rf /var/run/wpa_supplicant
ip addr add 192.168.90.1/24 brd + dev wlan0
ip link set dev wlan0 up
dhcpcd -k wlan0
systemctl start dnsmasq
systemctl start hostapd
dhcpcd -n wlan0
}
if [[ $1 == "off" ]]; then
hotspot_off
elif [[ $1 == "status" ]]; then
show_status
elif [[ $1 == "on" ]]; then
hotspot_on
elif [[ $1 == "service" ]]; then
if [[ ! -f /boot/wificfg.txt ]]; then
hotspot_on
exit
fi
if grep -E '^hotspot' /boot/wificfg.txt
then
hotspot_on
exit
fi
if grep -E '^wifiOrhotspot' /boot/wificfg.txt
then
hotspot_off
sleep 20
if ! wpa_cli -i wlan0 status | grep 'ip_address' >/dev/null 2>&1
then
hotspot_on
fi
exit
fi
if grep -E '^wifi' /boot/wificfg.txt
then
hotspot_off
exit
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment