我想有一个Hammerspoon wifi观察器,它定期检查,如果没有连接将禁用wifi. 以下脚本执行此操作, function checkAndDisableWifi() hs.timer.doAfter(45, function() local current_network = hs.wifi.currentNetwork() if curren
以下脚本执行此操作,
function checkAndDisableWifi() hs.timer.doAfter(45, function() local current_network = hs.wifi.currentNetwork() if current_network == nil then hs.wifi.setPower(false) hs.notify.new({title="Hammerspoon",informativeText="Disabling wifi due to inactivity"}):send() end end) end function wifi_timer_callback() local wifi_state = hs.wifi.interfaceDetails().power if wifi_state then local current_network = hs.wifi.currentNetwork() if current_network == nil then hs.wifi.setPower(false) hs.notify.new({title="Hammerspoon",informativeText="Disabling wifi due to inactivity"}):send() end else hs.wifi.setPower(true) checkAndDisableWifi() end end local wifi_timer = hs.timer.doEvery((10*60), wifi_timer_callback) wifi_timer:start()
在这里,我面临一个问题,比如用户是否已通过LAN连接.在这个时间点我不需要启用这个观察者(以便停止开启和关闭wifi).所以我需要的是,是否有任何API可以告诉我用户是通过局域网连接还是至少连接到互联网?
我清楚了吗?
在发布问题后,我得到了一个类似于@TheFrenchPlays的想法.这是我目前用Hammerspoon扩展这个想法的方法,status, data, headers = hs.http.get("http://google.com")
因此,当您检查状态变量时,如果它处于联机状态,它将给出200,如果它处于脱机状态,则为0.因此,通过检查此变量,我可以解决此问题.
如果没有错,那么如果Hammerspoon暴露一个API,如果它连接或不连接则返回BOOL将是很好的.还可以通过WiFi或LAN.
更新:现在,当系统通过LAN连接时,这种解决方法并不能完全解决问题.由于我不知道它是通过局域网还是WiFi连接,我无法直接关闭WiFi.因此,目前的解决方案似乎很乏味
function checkAndDisableWifi() hs.timer.doAfter(45, function() local current_network = hs.wifi.currentNetwork() if current_network == nil then disableWifi() end end) end function disableWifi() hs.wifi.setPower(false) hs.notify.new({title="Hammerspoon",informativeText="Disabling wifi due to inactivity"}):send() end function wifi_timer_callback() local status, data, headers = hs.http.get("http://google.com") local wifi_state = hs.wifi.interfaceDetails().power local current_network = hs.wifi.currentNetwork() if not status == 200 then -- user is offline mean not connected to LAN. So do WiFi check if wifi_state and current_network == nil then disableWifi() else hs.wifi.setPower(true) checkAndDisableWifi() end else --[[ since user is connected to online, check whether user is connected through wifi or not. If wifi is on and not connected to any network then disable wifi --]] if wifi_state and current_network == nil then disableWifi() end end end local wifi_timer = hs.timer.doEvery((10*60), wifi_timer_callback) wifi_timer:start()
更新2:
看起来Hammerspoon(0.9.47)有解决方案.使用Chris提供的解决方案更新代码,
if hs.network.interfaceDetails(v4) then if hs.network.interfaceDetails(v4)["AirPort"] then print("on wifi") else print("on Lan") end else print("not connected to internet") end