I'm working on a project where a mobile app can find and pair with a headless raspberry pi running Pi OS (Debian Buster Port) over bluetooth, send it an ssid and password and it'll create and hop on the wifi network. Everything is working but I really don't like this code that creates the wifi connection. I need the delays in there because there's no callback that I know of for the os commands and even after they finish there is some hardware delay. Just throwing out to the hive mind if there is a better way:
os.system("nmcli connection delete {}".format(ssid))
time.sleep(2)
os.system("nmcli r wifi off")
time.sleep(2)
os.system("nmcli r wifi on")
time.sleep(5)
os.system("nmcli dev wifi rescan")
time.sleep(5)
os.system("nmcli d wifi connect \"{}\" password \"{}\"".format(ssid, pw))
using the nmcli (Network Manager Command Line Interface).
Sleep seconds are guestimates - I'm looking for a way to get a callback
1 Answer 1
Here's the solution. It's important to know that you can use raspi-config
without the interface on the command line but it's not well documented so you have to look at the source code to figure some things out.
There are also several issues with using nmcli
to do this. First needing to purge any lingering wifi connections like this if any were added before using it:
nmcli --fields UUID,TIMESTAMP-REAL con show | grep never | awk '{print 1ドル}' | while read line; do sudo nmcli con delete uuid $line; done
But also it doesn't set the country code correctly on the PI which raspi-config
will do. The country code is stored in several places on the pi and can even be overwritten if manually edited.
Last part was to just read up on how to wait for a command to complete in python where in my case, I was getting the ssid and password from an app connected over bluetooth.
Run a command in python and wait for it to complete:
def runAndWait(command):
process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
process.wait()
var = process.returncode
print(var)
add wifi:
runAndWait("ifconfig wlan0 up")
runAndWait("raspi-config nonint do_wifi_country {}".format(XX))
runAndWait("raspi-config nonint do_wifi_ssid_passphrase {} {}".format(ssid, pw))
runAndWait("ifconfig wlan0 up")
replace XX with the wlan country code e.g US, GB, AU
-
+1 It's good to see people that can answer their own non-trivial questions. Welcome!Seamus– Seamus2023年09月29日 23:48:15 +00:00Commented Sep 29, 2023 at 23:48
nmcli
docs about status reporting?sudo raspi-config nonint do_wifi_ssid_passphrase <ssid> <passphrase> [hidden] [plain]
so if that works i'll update the questioncan't stand code like this
... give an explanation instead ... maybe something likeevent driven code would be less prone to errors