3

用树苺派播报天气

 3 years ago
source link: https://houye.xyz/2017-12/repweather/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

生成当前时间的文字

现在要解决的如何生成文本,下面的shell脚本生成了当前时间的文字。

shell脚本内容

#!/bin/bash
num2cn=(零 一 二 三 四 五 六 七 八 九 十)
hour=`date +%H`
if [ $(( $hour/10 )) -ge 2 ];then
    echo -e ${num2cn[${hour}/10]}"${num2cn[10]}\c"
elif [ $(( $hour/10 )) -eq 1 ];then
    echo -e ${num2cn[10]}"\c"
fi
if [ $(( $hour%10 )) -ne 0 ];then
echo -e ${num2cn[${hour}%10]}"\c"
fi
echo -e "点 \c"

min=`date +%M`
if [ $(( $min/10 )) -ge 2 ];then
    echo -e ${num2cn[${min}/10]}"${num2cn[10]}\c"
elif [ $(( $min/10 )) -eq 1 ];then
    echo -e ${num2cn[10]}"\c"
fi
if [ $(( $min%10 )) -ne 0 ];then
echo -e ${num2cn[${min}%10]}"\c"
fi
echo -e "分,\c"

得到当天天气

获取天气json

免费的天气预报api ,用curl命令可以得到想要的天气信息,因为接口的调用有一些限制,所以我设置了时间间隔。下面代码以杭州为例子,得到的信息为json格式,存入本地文本weather.txt。

ret=`curl -o weather.txt -s -w %{http_code} http://www.sojson.com/open/api/weather/json.shtml?city=%E6%9D%AD%E5%B7%9E`
if [ $ret -ne 200 ];then
sleep 6
ret=`curl -o weather.txt -s -w %{http_code} http://www.sojson.com/open/api/weather/json.shtml?city=%E6%9D%AD%E5%B7%9E`
fi

用jq取得需要的内容

得到了json信息,我们需要取出我们想要的信息,这里用到了jq命令 ,可以很方便的解析json格式的文本。下面的代码,取出当日的的天气提示信息并储存到变量notice中。

notice=`cat wether.txt | jq '.data.forecast[0]' | jq '.notice' | tr -d '"'`
echo -e "$notice \c"

脚本首先生成需要的天气预报文本信息,调用科大迅飞的接口生成语音文件,然后用linux系统的播放命令播放语音文件。通过以上内容,就可以完成这样一个脚本,最后在linux系统crontab设置定时运行,就大工告成了。

10 7 * * 1-5 /home/pi/demo/start.sh

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK