This works when personal hotspot has been enabled on my iPhone (manually via settings or control center), but not when i haven't. I'd love to find a solution that works even when personal hotspot is disabled on the iPhone - when doing it manually via the Mac wifi menu it works and personal hotspot doesn't have to be enabled first on the iPhone.
Try turning on "Allow others to Join" for your phone's Personal Hotspot -- you should then be able to use the networksetup command above with the password listed on your phone.
If you don't want to turn that on I think you're going to have to actually use the menu -- you could minimise the disruption of popping the menu every 15 seconds by testing for a connection and cancelling the macro if there is one.
But if you are willing to put up with your work being interrupted after every disconnection while things get automatically clicked, try starting with the following AppleScript -- written out long-form so you can easily see how the UI elements nest and what you might need to change:
tell application "System Events"
tell process "Control Centre"
tell menu bar 1
tell item 1 of (get every menu bar item whose value of attribute "AXIdentifier" is "com.apple.menuextra.wifi")
-- this should open the menu
click
end tell
end tell
-- opening the menu creates a window, not a menu!
tell window 1
tell group 1
tell scroll area 1
tell UI element 1
tell checkbox 1
click
end tell
end tell
end tell
end tell
end tell
end tell
end tell
This works for me with a menu like this:
You may have to poke around to find the right target.
Another option would be to use KM's "Click at Found Image" -- you'll probably have to include the icons either side of the wireless menu bar icon to get good detection:
I think the "Allow others to join" gets toggled off by itself sometimes (so save battery? I don't know). So I'd like to find a solution that doesn't rely on this option being turned on.
The AppleScript didn't work right away - and I'm not in the mood to figure out why
So I ended up going down the "Click at Found Image" route as you suggested.
For triggers I added:
"At system wake"
"At login"
"When the Mac is unlocked"
a hotkey
status menu item.
I deleted the periodic "every 15 seconds" trigger because I'm afraid it'll run down the battery. If I notice it disconnected, I'll just press the keyboard shortcut.
It seems like there should be a more elegant programmatic solution (without using the GUI) but this will do for the time being
Yeah I played around with it. I think it doesn't apply to my use case because it only triggers the moment the connection is lost. So if I take my phone out of range, then come back after some minutes, it won't trigger. For that case, I've set the keyboard shortcut.