|
即,在M645上面做一个功能,电脑网线连接上M645以后在浏览器里面输入M645的ip地址就可以打开一个配置页面,在这个页面里面可以配置和修改M645的IP地址、网关等参数。
首先,HTML文件是有了,这里要明白一个事情:HTML文件是在浏览器里面被解释和运行的,也就是HTML代码会被发送到浏览器,然后浏览器解析这个HTML代码然后将其以页面的形式呈现出来。
然后,那么这个HTML里面的数据怎么传给我的Linux系统呢?只能以接口的形式来传输了,也就是传统的前端和后端了,HTML相当于前端,需要有一个后端的框架运行在linux上面,这个框架程序负责和前端进行页面进行通信和数据交换,通信方式就是get请求和post请求了。
这里后端的框架选用python的flask框架。
#!/usr/bin/python3
from flask import Flask,request
import _thread
import logging
import socket
import time
import sys
import os
restart_flag = 0
app = Flask(__name__)
# 在web端输入ip+端口后会请求这里,这里将html文件发送至前端显示
@app.route('/')
def hello():
file_html = open("/usr/local/sigma/sigma/net_conf_service/STM32_LWIP_NET_Settings.html", "r", encoding="utf-8")
# 读取文件内容
data = file_html.read()
logging.debug("Send the network configuration file to the front web")
return data
# 在页面上点击提交以后程序会进入到这里,这里提取出前端传过来的ip和网关,存储在文件中
@app.route('/NetSettings.cgi')
def world():
global restart_flag
# print(request.args)
# print(request.args.get('IPAddress'))
f = open("/etc/systemd/network/10-eth0.network", "w+")
f.write("[Match]\n")
f.write("Name=eth0\n")
f.write("[Network]\n")
f.write("DHCP=none\n")
f.write("Address=" + request.args.get('IPAddress') + '\n')
f.write("Gateway=" + request.args.get('DefaultGateway') + '\n')
f.close()
time.sleep(1)
restart_flag = 1
logging.debug("Network parameters configured successfully, ip:%s" % request.args.get('IPAddress'))
return '网络参数配置成功,您的IP地址为:' + request.args.get('IPAddress')
# 这个是前端post请求会进入的地方,暂时未用到
@app.route('/test',methods=['POST'])
def hello_world():
data=request.data
print(data)
return 'ok'
def restart_program():
"""Restarts the current program.
Note: this function does not return. Any cleanup action (like
saving data) must be done before calling this function."""
python = sys.executable
os.execl(python, python, * sys.argv)
# 为线程定义一个函数
def print_time( threadName, delay):
global restart_flag
count = 0
while 1:
time.sleep(1)
# 此时打开的a是一个对象,如果直接打印的话是对象内存地址
a = os.popen('gpioget 0 0')
# 要用read()方法读取后才是文本对象
gpio_value = a.read()
if gpio_value[0] == '0':
count += 1
else:
count = 0
# print("gpio_value s %s" % gpio_value)
# print("count %d" % count)
a.close() # 打印后还需将对象关闭
if count > 5:
f = open("/etc/systemd/network/10-eth0.network", "w+")
f.write("[Match]\n")
f.write("Name=eth0\n")
f.write("[Network]\n")
f.write("DHCP=none\n")
f.write("Address=192.168.1.222\n")
f.write("Gateway=192.168.1.1\n")
f.close()
# os.system("systemctl restart systemd-networkd")
# time.sleep(2)
count = 0
restart_flag = 1
logging.debug("net config reset, ip:192.168.1.222")
if restart_flag == 1:
os.system("systemctl restart systemd-networkd")
restart_flag = 0
logging.debug("restart the net config service")
restart_program()
if __name__ == '__main__':
log_name = '/usr/local/sigma/sigma/net_conf_service/log.log'
logging.basicConfig(filename=log_name, # 日志输出文件
level=logging.DEBUG, # 日志写入级别
datefmt='%Y-%m-%d %H:%M:%S', # 时间级别
format='%(asctime)s %(levelname)s Line:%(lineno)s==>%(message)s') # 日志写入格式
# 创建线程
try:
_thread.start_new_thread(print_time, ("Thread-1", 2,))
except:
logging.debug("Error: 无法启动线程")
# windows下获取本机IP
# ip = socket.gethostbyname(socket.getfqdn(socket.gethostname()))
# linux下获取本机ip,注意外围使用双引号而非单引号,并且假设默认是第一个网卡,特殊环境请适当修改代码
ip = os.popen("ifconfig | grep 'inet addr:' | grep -v '127.0.0.1' | cut -d: -f2 | awk '{print $1}' | head -1").read()
logging.debug('net config service start, ip: %s' % ip)
app.run(host=ip, port=8888)
前端页面中IP修改之后会发送一个get请求到后端,后端收到这个get请求之后,从中提取IP地址,然后将本机的ip地址修改,由于后端所在的Linux修改IP后,它的ip地址已经变了,所以不能再和前端通信了,因为这个iP地址是后端程序在启动时获取的,那么以后在配置的时候咋办?因此在以上程序中添加了一个线程,当检测到IP地址配置了之后便将后台程序重启一下,这样后台框架就可以获取到更改后的IP了,即不会影响下一次IP配置。 |