上次写了Linux上面使用Python进行mqtt与串口互传的代码,后来GeneralZ同学想要把它安装在openWRT上面,在安装python的时候出现空间不足,所以我们一起写了一个使用纯脚本进行mqtt与串口互传的程序。

为了保证试验成功,首先说明本实验的软硬件环境:

硬件环境:树莓派3,外部串口

上次被系统自带串口坑了,不用自带,有兴趣可以尝试

软件环境:2016-05-27-raspbian-jessie openWRT 也测试成功

软件依赖:mosquitto-clients

其实脚本是两个程序,一个负责发送一个负责接收。

mqttRecv.sh:

#!/bin/bash
#mosquitto-clients receive messages from server then send these massages to ttyUSB0
#you can modify ttyUSB0 to your Serialport device.eg:ttyAMA0

#setup serialport parameter Baud:9600
stty -F /dev/ttyUSB0 raw speed 9600 min 0 time 1  
echo "Starting mqtt client..."  
#Receive message from host then send to /dev/ttyUSB0
mosquitto_sub -h localhost -t x > /dev/ttyUSB0  
mqttSend.sh

#!/bin/bash
#cat data from ttyUSB0 if not null send it to mqtt topic

#setup serialport parameter Baud:9600 time out 1s
stty -F /dev/ttyUSB0 raw speed 9600 min 0 time 1

while true  
do  
    serialMsg=`cat /dev/ttyUSB0`
    msgLen=`echo $serialMsg | wc -L`
        if [ $msgLen -ne 0 ]
        then
            echo "Received message form serial.." 
            mosquitto_pub -h localhost -t x -m $serialMsg
        fi
done  

下面就是要解决开机自启动的问题,mqtt是依赖网络环境的应用,所以必须网络成功启动之后才能运行脚本,所以我写了一个脚本,当开机的时候一直ping baidu.com,一旦执行成功,说明网络连接成功,此时就可以开始执行我们的脚本啦。

#!/bin/bash

while true  
do ping -c 3 www.baidu.com  
    if [ $? -eq 0 ] ;
    then
        echo "Host network is up."
        sh ./mqttRecv.sh &
        sh ./mqttSend.sh &
        #!!Attention please modify this path to adapt your env
        exit 0  
    else
        echo "Host network is down."
    fi
done  

只把mqttNettest.sh加入到开机自启中就好啦,在/etc/init.d/目录下新建mqtt-serial

#!/bin/bash
# /etc/init.d/mqtt-serial

### BEGIN INIT INFO
# Provides: mqtt-Send
# Required-Start: $remote_fs $syslog
# Required-Stop: $remote_fs $syslog
# Default-Start: 2 3 4 5
# Default-Stop: 0 1 6
# Short-Description: mqtt-serial transport
# Description: This service is used to send massage between serial & mqtt
### END INIT INFO

case "$1" in  
    start)
         echo "Starting NetWorkTest..."
         /root/mqttNettest.sh &
    ;;
    stop)
         echo "Stopping NetWorkTest..."
         kill $(ps aux | grep -m 1 '/root/mqttNettest.sh' | awk '{ print $2 }')
    ;;
    *)
         echo "Usage: service mqtt-serial start|stop"
         exit 1
    ;;
esac  
exit 0  

给予执行权限,并且更新服务

sudo chmod 755 mqtt-serial  
sudo update-rc.d mqtt-serial defaults