如何通过python脚本识别我是否有PPP连接,如果有,请打开LED指示灯?
我使用的是橙色Pi 2g IoT板,没有图形界面和发行版Ubuntu 16.04。该主板有一个调制解调器2G,通常可以很好地通过Python脚本将URL发送到我的Firebase应用程序,但有时连接不会建立。这是一个通过wvdial的pppd连接。如果我的调制解调器2G连接或没有连接,我希望在硬件(脉冲LED开/关)方面有所了解。如何通过python脚本识别我是否有PPP连接,如果有,请打开LED指示灯?
任何人都可以帮我解决这个问题吗?
非常感谢!
我不知道这方面的python功能。但我建议你使用python(如果必须的话)用一个系统实用程序来分配一个进程,这个系统实用程序会给你提供网络设备的当前状态。你可以按照下面这一行:Calling an external command in Python并调用例如“ifconfig”。你的PPP设备应该显示在那里。
感谢您的输入Matthias。可以在Python中调用外部命令。我通过使用import os库并在代码中写入OS.System('mycommand')来完成此操作。我可以写例如“ifconfig”。但问题是我如何解析它,所以我可以在这个输出中识别一个ppp连接? –
您可以通过为设备“拼凑”而逃脱。 – Matthias
如果您可以使用外部python软件包:pip install netifaces。
使用此软件包,您可以测试该接口是否存在,然后测试您是否可以访问Google。这段代码没有经过测试,但应该让你非常接近。
import netifaces
import requests
ppp_exists = False
try:
netifaces.ifaddresses('ppp0') # this assumes that you only have one ppp instance running
ppp_exists = True
except:
ppp_exists = False
# you have an interface, now test if you have a connection
has_internet = False
if ppp_exists == True:
try:
r = requests.get('http://www.google.com', timeout=10) # timeout is necessary if you can't access the internet
if r.status_code == requests.codes.ok:
has_internet = True
else:
has_internet = False
except requests.exceptions.Timeout:
has_internet = False
if ppp_exists == True and has_internet == True:
# turn on LED with GPIO
pass
else:
# turn off LED with GPIO
pass
UPDATE
可以使用
os.system('ifconfig > name_of_file.txt')
然后可以解析这个反正你喜欢使用ifconfig的输出记录到一个文本文件中。以下是一种确认ppp接口是否存在的方法。
import os
import netifaces
THE_FILE = './ifconfig.txt'
class pppParser(object):
"""
gets the details of the ifconfig command for ppp interface
"""
def __init__(self, the_file=THE_FILE, new_file=False):
"""
the_file is the path to the output of the ifconfig command
new_file is a boolean whether to run the os.system('ifconfig') command
"""
self.ppp_exists = False
try:
netifaces.ifaddresses('ppp0') # this assumes that you only have one ppp instance running
self.ppp_exists = True
except:
self.ppp_exists = False
if new_file:
open(the_file, 'w').close() # clears the contents of the file
os.system('sudo ifconfig > '+the_file)
self.ifconfig_text = ''
self.rx_bytes = 0
with open(the_file, 'rb') as in_file:
for x in in_file:
self.ifconfig_text += x
def get_rx_bytes(self):
"""
very basic text parser to gather the PPP interface data.
Assumption is that there is only one PPP interface
"""
if not self.ppp_exists:
return self.rx_bytes
ppp_text = self.ifconfig_text.split('ppp')[1]
self.rx_bytes = ppp_text.split('RX bytes:')[1].split(' ')[0]
return self.rx_bytes
只需拨打pppParser()。get_rx_bytes()
感谢您的意见,马特!其实我的数据消费有限。例如,我的设备每隔几分钟尝试一次请求都不可行。这会危害我的产品。我想通过一种方法来分析'ifconfig'输出并解析是否有RX(xx.xx)数据发送。你认为这是可能的吗? –
是的,这是可能的。我用一个简单的文本解析器方法更新了答案。 –
有一个广泛的,在Python包指数Python包的(https://pypi.python.org/pypi?%3Aaction=search&term=覆盆子&提交=搜索)与覆盆子pi有关。也许你找到适合你需要的东西? – Matthias