gpt4 book ai didi

python - 如果我有 PPP 连接,如何通过 python 脚本识别,如果有,打开 LED?

转载 作者:行者123 更新时间:2023-12-04 18:45:20 31 4
gpt4 key购买 nike

我使用的是 Orange Pi 2g IoT 板,没有图形界面和发行版 Ubuntu 16.04。该板有一个 2G 调制解调器,可以通过 Python 脚本向我的 Firebase 应用程序发送 URL,但有时无法建立连接。它是通过 wvdial 的 pppd 连接。如果我的调制解调器 2G 已连接,我想了解硬件(avulse LED 开/关)。

谁能帮我解决这个问题?

非常感谢!

最佳答案

如果可以使用外部 python 包:pip install netifaces。

有了这个包,你可以测试接口(interface)是否存在,然后测试能不能上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 接口(interface)存在的方法。
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()

关于python - 如果我有 PPP 连接,如何通过 python 脚本识别,如果有,打开 LED?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46673178/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com