ARM40-A5应用——ARM40网络应用场景2
2018.9.15
本文接《ARM40-A5应用——ARM40网络应用场景1》。
六、应用场景4——有线无线自动切换
有线eth0 和无线ppp0之间自动切换,流程较复杂,详见代码和图示。
建立 /etc/network/if-auto-switch.sh 文件:
touch /etc/network/if-auto-switch.sh
chmod 755 /etc/network/if-auto-switch.sh
其内容为:
#!/bin/sh
#automatically switch between eth0 and ppp0 network
dns1="223.5.5.5" #aliyun dns
dns2="223.6.6.6" #aliyun dns
echo "NULL" > /var/log/if-channel-live
#if [ $(cat /sys/class/net/eth0/carrier) -eq 1 ]; then #eth0 is link up
# /etc/init.d/S40network route #set eth0 iproute
#fi
while true
do
if [ $(cat /sys/class/net/eth0/carrier) -eq 1 ]; then #eth0 is link up
ping -c 2 -w 10 -I eth0 $dns1 >/dev/null #ping dns1,2 count,timeout is 10s
if [ $? -ne 0 ]; then #ping request timed out
ping -c 2 -w 10 -I eth0 $dns2 >/dev/null #ping dns2,2 count,timeout is 10s
if [ $? -ne 0 ]; then #ping request timed out
procnum=`ps -ef|grep "pon-M26-auto.sh"|grep -v grep|wc -l`
if [ $procnum -eq 0 ]; then #pon-M26-auto.sh isn't exist
/etc/ppp/pon-M26-auto.sh & #if success, echo "PPP0" > /var/log/if-channel-live
else #pon-M26-auto.sh is exist
#wc -l /var/log/pppd-recall.log #good for test print
pingnum=`cat /var/log/pppd-recall.log|wc -l` #ping ppp0, 5 times unconnected
if [ $pingnum -ge 5 ]; then #unconnected 5 times
killall pon-M26-auto.sh
killall pppd
/etc/init.d/S40network route #set eth0 iproute
fi
fi
else #dns2有线通
echo "ETH0" > /var/log/if-channel-live
fi
else #dns1有线通
echo "ETH0" > /var/log/if-channel-live
fi
else
procnum=`ps -ef|grep "pon-M26-auto.sh"|grep -v grep|wc -l`
if [ $procnum -eq 0 ]; then
/etc/ppp/pon-M26-auto.sh & #if success, echo "PPP0" > /var/log/if-channel-live
fi
fi
sleep 60
done
ppp连接建立后,会设定 /var/log/if-channel-live 为"PPP0"。
eth0连接建立后,会设定 /var/log/if-channel-live 为"ETH0"。
ppp连接失败,会设定 /var/log/if-channel-live 为"NULL"。
其他应用程序可以通过访问if-channel-live,来获取设备目前联网的方式:PPP0、ETH0、NULL(未联网)。
cat /var/log/if-channel-live
代码注释:
(1)如果eth0上有网线,并且读取到ppp0超过5次没连上,则切换到eth0。
切换到eth0后,如果通,则杀死ppp0. 如果不通,什么也不干。
(2)如果eth0上无网线,切换至 ppp0.
请根据上图,分析如下场景:
(a)配置为有线,无网线; 配置为无线,无网线:——>使用无线;
可能的情况有:左右(使用ppp0);左左(切换至ppp0);
(b)配置为有线,有网线: ——>使用有线,或者切换到无线;
首次连接的情况有:右右(OK);右左右(OK);右左左左(切换至ppp0);
后续连接的情况有:右左左右(使用ppp0);
(c)配置为无线,有网线:——>有线无线自动切换;
首次连接的情况有:右左左右(OK);右左左右(切换至eth0);右左左左(切换至ppp0);
后续连接的情况有:右右(OK);右左右(OK);右左左左(切换至ppp0);右左左右(OK);右左左右(切换至eth0);
测试示例:
本文应用场景4中,有个缺陷,例如:正在使用无线,此时发生外部干涉(如在界面切换了S40network route 或者S41network route),有线就通了,但是应用场景4的程序仍旧会使用无线,而不会切换到有线。
若要有线通了后,能及时切换到有线,需不断监控每个网路的情况,见《ARM40-A5应用——ARM40网络应用场景2》。
七、上电自动运行
若要上电自启动 /etc/network/if-auto-switch.sh,则修改/etc/profile.local 。
logintty=$(tty|grep -c "console")
if [ $logintty -eq 1 ]; then # ssh,telnet can't get into this line
/etc/network/if-auto-switch.sh &
fi
注意 /etc/profile 文件的最后是:
/etc/profile.local
参考文章:
ARM40-A5应用——GPRS模块ppp拨号上网
ARM40-A5应用——ARM40网络应用场景1
ARM40-A5应用——ARM40网络应用场景3
荟聚计划:共商 共建 共享 Grant