首页 编程教程正文

每天早上让树莓派叫你起床

piaodoo 编程教程 2020-02-22 22:15:29 1247 0 python教程

本文来源吾爱破解论坛

楼主于最近入手了一块树莓派,想着用它做一些比较有意思的事情。那么,先来做一个语音闹钟好了-先来码一波代码
[Python] 纯文本查看 复制代码

#!/usr/bin/env python
# -*- coding:utf-8

import urllib
import urllib2
import json
import os

WEATHER_CODE = {"00":"晴","01":"多云","02":"阴","03":"阵雨","04":"雷阵雨","05":"雷阵雨伴有冰雹","06":"雨夹雪","07":"小雨","08":"中雨","09":"大雨","10":"暴雨","11":"大暴雨","12":"特大暴雨","13":"阵雪","14":"小雪","15":"中雪","16":"大雪","17":"暴雪","18":"雾","19":"冻雨","20":"沙尘暴","21":"小到中雨","22":"中到大雨","23":"大到暴雨","24":"暴雨到大暴雨","25":"大暴雨到特大暴雨","26":"小到中雪","27":"中到大雪","28":"大到暴雪","29":"浮尘","30":"扬沙","31":"强沙尘暴","53":"霾","99":""}

def get_weather():
    url = 'https://weatherapi.market.xiaomi.com/wtr-v3/weather/all?latitude=110&longitude=112&isLocated=true&locationKey=weathercn%3A101270106&days=1&appKey=weather20151024&sign=zUFJoAR2ZVrDy1vF3D07&romVersion=7.2.16&appVersion=87&alpha=false&isGlobal=false&device=cancro&modDevice=&locale=zh_cn'
    json_data = urllib2.urlopen(url).read()
    parsed_weather = json.loads(json_data)
    temperature = parsed_weather['current']['temperature']['value']
    humidity = parsed_weather['current']['humidity']['value']
    today_forecast = parsed_weather['forecastDaily']['weather']['value'][0]
    weather_from = '%02d' % (int(today_forecast['from']))
    weather_from = WEATHER_CODE[weather_from]
    weather_to = '%02d' % (int(today_forecast['to']))
    weather_to = WEATHER_CODE[weather_to]
    temperature_from = parsed_weather['forecastDaily']['temperature']['value'][0]['from']
    temperature_to = parsed_weather['forecastDaily']['temperature']['value'][0]['to']
    #print temperature,humidity
    weather_detail = "这里是树莓派天气预报播报台,现在温度{0}度,相对湿度{1}%,今天天气{2}转{3},温度{4}度到{5}度".format(temperature, humidity, weather_from, weather_to, temperature_from, temperature_to)
    audio_url = 'http://tsn.baidu.com/text2audio?lan=zh&ctp=1&cuid=mypi&tok=需要从百度申请token&tex=%s&vol=9&per=1' % urllib.quote(weather_detail)
    audio_cmd = "mplayer \"%s\"" % audio_url
    os.system(audio_cmd)
    return weather_detail

if __name__ == "__main__":
    get_weather()


取得天气数据是用的小米的接口,合成语音是使用的百度语音合成接口,系统调用mplayer播放声音即可。
代码编写完毕后,编辑crontab,设定一个时间,每天早上就可以树莓派就会用天气预报叫你起床了。
[Shell] 纯文本查看 复制代码
0 8 * * * /home/pi/SmartHome/Alarm.py

我这里设置的每天8点运行此脚本。

版权声明:

本站所有资源均为站长或网友整理自互联网或站长购买自互联网,站长无法分辨资源版权出自何处,所以不承担任何版权以及其他问题带来的法律责任,如有侵权或者其他问题请联系站长删除!站长QQ754403226 谢谢。

有关影视版权:本站只供百度云网盘资源,版权均属于影片公司所有,请在下载后24小时删除,切勿用于商业用途。本站所有资源信息均从互联网搜索而来,本站不对显示的内容承担责任,如您认为本站页面信息侵犯了您的权益,请附上版权证明邮件告知【754403226@qq.com】,在收到邮件后72小时内删除。本文链接:https://www.piaodoo.com/8004.html

搜索