我正在使用Orange Pi 2g物联网板,没有图形界面和发行版Ubuntu 16.04。该主板有一个调制解调器2G,通常可以通过Python脚本将URL发送到我的Firebase应用程序,但有时连接不会建立。它是通过wvdial的pppd连接。如果我的调制解调器2G已连接,我想知道硬件(脉冲LED开/关)。
有人可以帮我解决这个问题吗?
非常感谢!
答案 0 :(得分:0)
我不知道这方面的python功能。但我建议您使用python(如果必须)使用一个系统实用程序来分叉进程,该实用程序为您提供网络设备的当前状态。你可以按照这一行:Calling an external command in Python并调用例如“ifconfig”。你的ppp设备应该出现在那里。
答案 1 :(得分:0)
如果你可以使用外部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
<强>更新强>
您可以使用
将ifconfig的输出记录到文本文件中os.system('ifconfig > name_of_file.txt')
然后你可以随意解析这个。这是检查以确保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()