教大家如何在树莓派上自己动手做一个天气预报。此次教程需要大家有一定的python 基础,没有也没关系,文末我会放出我已写好的代码供大家下载。

首先在开始之前 需要申请高德地图API,去高德地图官网注册一下,然后创建一个天气应用(免费的),得到一个免费key。然后开始撸码了 (说一下,我用的是python 3)

 

1.下面给出调用高德地图API,获取天气数据的方法。将申请的key替换进url中,再将你的城市代码(网上可查,可以具体到区)替换下即可。

  1. def GetWeatherInfo():
  2. url = "http://restapi.amap.com/v3/weather/weatherInfo?key=xxxxxxxxxxxxx&city=420115&extensions=all" #将xxxxxx替换为你申请的key,city代码替换为你的城市代码
  3. try:
  4. html = requests.get(url)
  5. data = json.loads(html.text)
  6. # #将JSON编码的字符串转换回Python数据结构
  7. # output result of json
  8. # print(data)
  9. return data
  10. except:
  11. return None

2.系统信息及配置

  1. # coding = utf-8
  2. import subprocess
  3. import time
  4. import os
  5. #device :eth0,wlan0
  6. def get_ip(device):
  7. ip = subprocess.check_output("ip -4 addr show " + device + " | grep inet | awk '{print $2}' | cut -d/ -f1", shell = True).strip()
  8. return ip
  9. # Return % of CPU used by user as a character string
  10. #def getCPUuse():
  11. # return(str(os.popen("top -n1 | awk '/Cpu\(s\):/ {print $2}'").readline().strip()))
  12. def getCPUuse():
  13. #calculate CPU with two short time, time2 - time1
  14. time1 = os.popen('cat /proc/stat').readline().split()[1:5]
  15. time.sleep(0.2)
  16. time2 = os.popen('cat /proc/stat').readline().split()[1:5]
  17. deltaUsed = int(time2[0])-int(time1[0])+int(time2[2])-int(time1[2])
  18. deltaTotal = deltaUsed + int(time2[3])-int(time1[3])
  19. cpuUsage = float(deltaUsed)/float(deltaTotal)*100
  20. return cpuUsage
  21.  
  22. def net_stat():
  23. net = []
  24. f = open("/proc/net/dev")
  25. lines = f.readlines()
  26. f.close()
  27. for line in lines[2:]:
  28. con = line.split()
  29. """
  30. intf = {}
  31. intf['interface'] = con[0].lstrip(":")
  32. intf['ReceiveBytes'] = int(con[1])
  33. intf['ReceivePackets'] = int(con[2])
  34. intf['ReceiveErrs'] = int(con[3])
  35. intf['ReceiveDrop'] = int(con[4])
  36. intf['ReceiveFifo'] = int(con[5])
  37. intf['ReceiveFrames'] = int(con[6])
  38. intf['ReceiveCompressed'] = int(con[7])
  39. intf['ReceiveMulticast'] = int(con[8])
  40. intf['TransmitBytes'] = int(con[9])
  41. intf['TransmitPackets'] = int(con[10])
  42. intf['TransmitErrs'] = int(con[11])
  43. intf['TransmitDrop'] = int(con[12])
  44. intf['TransmitFifo'] = int(con[13])
  45. intf['TransmitFrames'] = int(con[14])
  46. intf['TransmitCompressed'] = int(con[15])
  47. intf['TransmitMulticast'] = int(con[16])
  48. """
  49. intf = dict(
  50. zip(
  51. ( 'interface','ReceiveBytes','ReceivePackets',
  52. 'ReceiveErrs','ReceiveDrop','ReceiveFifo',
  53. 'ReceiveFrames','ReceiveCompressed','ReceiveMulticast',
  54. 'TransmitBytes','TransmitPackets','TransmitErrs',
  55. 'TransmitDrop', 'TransmitFifo','TransmitFrames',
  56. 'TransmitCompressed','TransmitMulticast' ),
  57. ( con[0].rstrip(":"),int(con[1]),int(con[2]),
  58. int(con[3]),int(con[4]),int(con[5]),
  59. int(con[6]),int(con[7]),int(con[8]),
  60. int(con[9]),int(con[10]),int(con[11]),
  61. int(con[12]),int(con[13]),int(con[14]),
  62. int(con[15]),int(con[16]), )
  63. )
  64. )
  65.  
  66. net.append(intf)
  67. return net

3.主程序。执行文件

  1. #encoding: utf-8
  2. import pygame
  3. import time
  4. import weatherAPI
  5. import SystemInfo
  6. from datetime import datetime
  7.  
  8. # 显示图片函数
  9. def ShowPicture(picturepath,x0,y0):
  10. background=pygame.image.load(picturepath)
  11. background.convert_alpha()
  12. window.blit(background,(x0,y0))
  13. return
  14. def ShowCircle():
  15. pygame.draw.circle(window,pygame.Color(255,255,255),(width/2,height/2),radius,fill)
  16. return
  17. # 划线函数,起始坐标,终点坐标
  18. def ShowLine(x0,y0,x1,y1):
  19. pygame.draw.line(window,pygame.Color(255,255,255),(x0,y0),(x1,y1),fill)
  20. return
  21. Yellow=(255,255,0)
  22. Red=(255,0,0)
  23. LightBlue=(190,190,255)
  24. Green=(0,255,0)
  25. Black=(0,0,0)
  26. White=(255,255,255)
  27. # 画框函数
  28. def ShowRec(x0,y0,x1,y1,color,fill):
  29. pygame.draw.rect(window,color,(x0,y0,x1,y1),fill)
  30. return
  31. # 字符串显示函数
  32. def ShowStr(mystring,x0,y0,size):
  33. font=pygame.font.Font('gkai00mp.ttf',size,bold=1)
  34. textSuface=font.render(mystring,1,pygame.Color(255,255,255))
  35. window.blit(textSuface,(x0,y0))
  36. return
  37.  
  38. def ShowStr2(mystring,x0,y0,size):
  39. font=pygame.font.Font('gkai00mp.ttf',size,bold=1)
  40. textSuface=font.render(mystring,1,pygame.Color(255,255,0))
  41. window.blit(textSuface,(x0,y0))
  42. return
  43. def ShowStr3(mystring,x0,y0,size):
  44. font=pygame.font.Font('gkai00mp.ttf',size,bold=1)
  45. textSuface=font.render(mystring,1,pygame.Color(0,255,0))
  46. window.blit(textSuface,(x0,y0))
  47. return
  48. #背景参数设置
  49. width=1280
  50. height=800
  51. fill=1
  52. #初始化背景
  53. pygame.init()
  54. window=pygame.display.set_mode((width,height),pygame.FULLSCREEN)#全屏
  55. # window=pygame.display.set_mode((width,height))#不全屏
  56. window.fill(pygame.Color(0,0,0))
  57. # back=pygame.image.load(r"/home/pi/ccj/c.jpg") #图片位置
  58.  
  59. loop=0
  60. last_ip = ip = ''
  61. updatingtime=""
  62. Title_X=width
  63. WeatherValidation=False
  64. while True:
  65. # window.blit(back,(0,0)) #对齐的坐标
  66. window.fill(pygame.Color(0,0,0)) #背景色0为黑
  67. # ShowPicture("a_3.gif",20,450)
  68. #draw grids
  69. #ShowStr(u"时间",10,20,80)
  70. ShowRec(10,10,width-20,height-80,White,1) #画一个大框
  71. ShowLine(10,height/5,width-10,height/5)
  72. ShowLine(10,height/5*3,width-10,height/5*3)
  73. ShowLine(width/2,height/5,width/2,height-70)
  74. ShowLine(width/4,height/5*3,width/4,height-70)
  75. ShowLine(width/4*3,height/5*3,width/4*3,height-70)
  76.  
  77. #time show
  78. mylocaltime=time.localtime()
  79. myclock=time.strftime("%H:%M:%S",mylocaltime)#13:15:03 2017-04-21
  80. ShowStr(myclock,0,0,180)
  81. mydate=time.strftime("%Y-%m-%d",mylocaltime)#2017-04-21
  82. ShowStr(mydate,810,5,90)
  83. mytime=time.strftime("%A",mylocaltime)#Thursday
  84. ShowStr(mytime,830,90,85)
  85.  
  86. name = "自动化实验室欢迎您"
  87. ShowStr2(name,width/2+10,height/5*2-140,52)
  88. ip = SystemInfo.get_ip('wlan0')
  89. # ip = SystemInfo.get_ip('eth0')
  90. cpu_usage =SystemInfo.getCPUuse()
  91. ShowStr(ip,width/2+100,height/5*2-90,48)
  92. ShowStr("ip:",width/2+10,height/5*2-90,52)
  93.  
  94. #netspeed show
  95. NetInfoOld=SystemInfo.net_stat()
  96. time.sleep(1)
  97. NetInfoNew=SystemInfo.net_stat()
  98. DownloadSpeed=(NetInfoNew[0]["ReceiveBytes"]-NetInfoOld[0]["ReceiveBytes"])/1048576 #last second total flow -current second total flow
  99. UploadSpeed=(NetInfoNew[0]["TransmitBytes"]-NetInfoOld[0]["TransmitBytes"])/1048576
  100. ShowRec(width/2+20,height/5*2-40,DownloadSpeed/10*600+20,48,Green,0)
  101. ShowRec(width/2+20,height/5*2+10,UploadSpeed/10*600+20,48,LightBlue,0)
  102. ShowStr("↓:"+str("%3.2f"%(DownloadSpeed))+"MB/s",width/2+20,height/5*2-40,48)
  103. ShowStr("↑:"+str("%3.2f"%(UploadSpeed))+"MB/s",width/2+20,height/5*2+10,48)
  104.  
  105. #cpu_usage show
  106. ShowRec(width/2+20,height/5*2+60,cpu_usage/100*600+60,48,Yellow,0)
  107. ShowStr("CPU usage:"+str("%2d"%cpu_usage)+"%",width/2+20,height/5*2+110,48)
  108.  
  109. if loop % 60==0 :
  110. future = datetime.strptime('2019-1-1 00:00:00','%Y-%m-%d %H:%M:%S')
  111. #当前时间
  112. now = datetime.now()
  113. #求时间差
  114. delta = future - now
  115. hour = delta.seconds/60/60
  116. minute = delta.seconds/60
  117. seconds = delta.seconds - hour*60*60 - minute*60
  118. # print_now=now.strftime('%Y-%m-%d %H:%M:%S')
  119. # print("今天是:",print_now)
  120. # print("距离 2019-02-01 \"work\" 还剩下:%d天"%delta.days)
  121. # print(delta.days,hour, minute, seconds)
  122.  
  123. ShowStr2("倒计时:%dH (%dMin)"%(hour,minute),width/4*2+width/32+20,height/5*3+height/30+235,45)
  124.  
  125. # #########################本地信息获取完成#######################################
  126. # print ("↓:"+str("%3.1f"%(DownloadSpeed))+"MB/s")
  127. # print ("↑:"+str("%3.1f"%(UploadSpeed))+"MB/s")
  128.  
  129. #print("CPU usage:"+str("%2d"%cpu_usage)+"%")
  130.  
  131. # ########weather show####################################
  132. if loop % 10800==0 : #update per 3 hours
  133. jsonArr=weatherAPI.GetWeatherInfo()
  134. if jsonArr!=None : #记录请求数据时间
  135. updatingtime=time.strftime("%H:%M:%S",mylocaltime)
  136. if jsonArr["status"]!="":
  137. print (jsonArr["msg"])
  138. WeatherValidation=False
  139. else:
  140. result=jsonArr["forecasts"][0]
  141. WeatherValidation=True
  142. #print (result["city"],result["weather"],result["temp"],result["temphigh"],result["templow"])
  143. if WeatherValidation==True:
  144. # AQI=result["aqi"]
  145. # index=result["index"]
  146. # index0=index[0]
  147. # daily=result["daily"]
  148. # day1=daily[1]#明天天气预报
  149. # day2=daily[2]#明天天气预报
  150. # day3=daily[3]#明天天气预报
  151. # day4=daily[4]#明天天气预报
  152. # ## #室外温湿度
  153. # ShowPicture("pictures/"+result["img"]+".png",width/16,height/5+150)
  154. ShowStr("武汉市",width/32,height/5+10,60)
  155. ShowStr(result["city"],width/32,height/5+80,60)
  156. ShowStr(result["casts"][0]["dayweather"],width/32-25,height/5*2+50,120)
  157. ShowStr(result["casts"][0]["daytemp"]+"℃",width/4,height/5,160)
  158.  
  159. ShowStr("气温最低:"+result["casts"][0]["nighttemp"] +"℃",width/4-10,height/5*2-20,48)
  160. ShowStr("接下来转:"+result["casts"][0]["nightweather"],width/4-10,height/5*2+50,48)
  161. # ShowStr("zhesgii",width/2+20,height/5+10,120)
  162. ShowStr("风力:"+result["casts"][0]["daypower"]+"级",width/4-10,height/5*2+110,48)
  163. # ## #空气质量
  164. # ShowStr("PM2.5:",width/2+280,height/5+120,32)
  165. # ShowStr(AQI["pm2_5"],width/2+400,height/5-20,200)
  166. # ShowStr("空气质量:"+AQI["quality"],width/2+240,height/5*2-40,32)
  167. ShowPicture("pictures/"+result["casts"][0]["dayweather"]+".png",width/32+60,height/5+145)
  168. # if Title_X<=-100:
  169. # Title_X=width
  170. # else:
  171. # Title_X=Title_X-40
  172. # ShowStr(index0["detail"],Title_X,height-50,40)
  173. # #未来几天天气预报
  174. ShowStr("明天:"+result["casts"][1]["date"],width/32,height/5*3+height/30-10,30)
  175. ShowStr(result["casts"][1]["dayweather"],width/32,height/5*3+height/30+30,50)
  176. ShowStr(result["casts"][2]["daytemp"]+"℃",width/32,height/5*3+height/30+80,70)
  177. ShowStr("气温Min:"+result["casts"][1]["nighttemp"] +"℃",width/32-10,height/5*3+height/30+140,45)
  178. ShowStr("未来转:"+result["casts"][1]["nightweather"],width/32-10,height/5*3+height/30+180,45)
  179. ShowPicture("pictures/"+result["casts"][1]["dayweather"]+".png",width/32+170,height/5*3+height/30+45)
  180. # ShowPicture("pictures/"+day1["day"]["img"]+".png",width/32,height/5*3+height/10)
  181. # ##
  182. ShowStr("后天:"+result["casts"][2]["date"],width/4+width/32,height/5*3+height/30-10,30)
  183. ShowStr(result["casts"][2]["dayweather"],width/4+width/32,height/5*3+height/30+30,50)
  184. ShowStr(result["casts"][2]["daytemp"]+"℃",width/4+width/32,height/5*3+height/30+80,70)
  185. ShowStr("气温Min:"+result["casts"][2]["nighttemp"] +"℃",width/4+width/32-10,height/5*3+height/30+140,45)
  186. ShowStr("未来转:"+result["casts"][2]["nightweather"],width/4+width/32-10,height/5*3+height/30+180,45)
  187. ShowPicture("pictures/"+result["casts"][2]["dayweather"]+".png",width/4+width/32+170,height/5*3+height/30+45)
  188. # ShowStr(day2["day"]["weather"],width/4+width/32,height/5*3+height/5-40,100)
  189. # ShowStr(day2["day"]["windpower"],width/4+width/32+70,height/5*3+height/10,64)
  190. # ShowStr(day2["night"]["templow"]+"~"+day2["day"]["temphigh"]+"℃",width/4+width/32,height-130,64)
  191. # ShowPicture("pictures/"+day2["day"]["img"]+".png",width/4+width/32,height/5*3+height/10)
  192. # ##
  193. ShowStr("大后天:"+result["casts"][3]["date"],width/4*2+width/32-25,height/5*3+height/30-10,30)
  194. ShowStr(result["casts"][3]["dayweather"],width/4*2+width/32-25,height/5*3+height/30+30,50)
  195. ShowStr(result["casts"][3]["daytemp"]+"℃",width/4*2+width/32-25,height/5*3+height/30+80,70)
  196. ShowStr("气温Min:"+result["casts"][3]["nighttemp"] +"℃",width/4*2+width/32-25,height/5*3+height/30+140,45)
  197. ShowStr("未来转:"+result["casts"][3]["nightweather"],width/4*2+width/32-25,height/5*3+height/30+180,45)
  198. ShowPicture("pictures/"+result["casts"][3]["dayweather"]+".png",width/4*2+width/32-25+170,height/5*3+height/30+45)
  199. # ShowStr(day3["day"]["weather"],width/4*2+width/32,height/5*3+height/5-40,100)
  200. # ShowStr(day3["day"]["windpower"],width/4*2+width/32+70,height/5*3+height/10,64)
  201. # ShowStr(day3["night"]["templow"]+"~"+day2["day"]["temphigh"]+"℃",width/4*2+width/32,height-130,64)
  202. # ShowPicture("pictures/"+day3["day"]["img"]+".png",width/4*2+width/32,height/5*3+height/10)
  203. # ##
  204.  
  205. ShowPicture("pictures/cj.png",width/4*3+width/32,height/5*3+height/30-15)
  206. # ShowStr(day4["day"]["weather"],width/4*3+width/32,height/5*3+height/5-40,100)
  207. # ShowStr(day4["day"]["windpower"],width/4*3+width/32+70,height/5*3+height/10,64)
  208. # ShowStr(day4["night"]["templow"]+"~"+day2["day"]["temphigh"]+"℃",width/4*3+width/32,height-130,64)
  209. # ShowPicture("pictures/"+day4["day"]["img"]+".png",width/4*3+width/32,height/5*3+height/10)
  210. # #记录请求数据时间
  211. ShowStr3("Last update:"+updatingtime,width/4*3+15,height/5*3,30)
  212. ShowStr2("这里是滚动字幕显示区,加循环可实现动态效果",width/32-25,height/5*3+height/30+235,45)
  213. #update
  214.  
  215. pygame.display.update()
  216.  
  217. loop +=1
  218. #全屏
  219. #for event in pygame.event.get():
  220. # if event.type==pygame.KEYDOWN:
  221. # running=False
  222. pygame.quit()

公众号回复 “树莓派天气”  即可下载我为大家打包好的文件。下载好文件以后,解压文件会得到如下文件:1,天气图标文件夹pictures,2,字体文件gkai00mp.ttf,3,系统配置文件SystemInfo.py,4,获取天气数据文件weatherAPI.py,5,主程序pyMain.py 。将这些文件放在同一文件夹下,复制拷贝到树莓派上,为文件夹赋予权限,命令sudo chmod 777 文件夹名。最后终端执行命令运行主程序(sudo python3 pyMain.py)。此时应该就可以看到预报的画面。能看懂代码的人可自行修改 具体显示的背景、颜色、大小、布局、位置 、显示字体大小等。

关注一下,更多精彩,不容错过!

在树莓派上用 python 做一个炫酷的天气预报的更多相关文章

  1. canvas的进阶 - 学习利用canvas做一个炫酷的倒计时功能

    先给大家贴一张图片,因为我不会上传视频( ̄□ ̄||) ,请大家谅解了~  如果有知道怎么上传视频的大神还请指点指点 ^_^ ~ 然后看一下代码: html部分 :  <!DOCTYPE html ...

  2. 用Python做一个知乎沙雕问题总结

    用Python做一个知乎沙雕问题总结 松鼠爱吃饼干2020-04-01 13:40 前言 本文的文字及图片来源于网络,仅供学习.交流使用,不具有任何商业用途,版权归原作者所有,如有问题请及时联系我们以 ...

  3. 使用python做一个IRC在线下载器

    使用python做一个IRC在线下载器 1.开发流程 2.软件流程 3.开始 3.0 准备工作 3.1寻找API接口 3.2 文件模块 3.2.1 选择文件弹窗 3.2.2 提取文件名 3.2.2.1 ...

  4. 百度前端技术学院2018笔记 之 利用 CSS animation 制作一个炫酷的 Slider

    前言 题目地址 利用 CSS animation 制作一个炫酷的 Slider 思路整理 首先页面包含三种东西 一个是type为radio的input其实就是单选框 二是每个单选框对应的label 三 ...

  5. 一个炫酷的Actionbar效果

    今天在网上看到一个炫酷的Actionbar效果,一个老外做的DEMO,目前很多流行的app已经加入了这个效果. 当用户初始进入该界面的时候,为一个透明的 ActiionBar ,这样利用充分的空间显示 ...

  6. 2019基于Hexo快速搭建个人博客,打造一个炫酷博客(1)-奥怪的小栈

    本文转载于:奥怪的小栈 这篇文章告诉你如何在2019快速上手搭建一个像我一样的博客:基于HEXO+Github搭建.并完成SEO优化,打造一个炫酷博客. 本站基于HEXO+Github搭建.所以你需要 ...

  7. 教你用canvas打造一个炫酷的碎片切图效果

    前言 今天分享一个炫酷的碎片式切图效果,这个其实在自己的之前的博客上有实现过,本人觉得这个效果还是挺炫酷的,这次还是用我们的canvas来实现,代码量不多,但有些地方还是需要花点时间去理解的,需要点数 ...

  8. 一个炫酷的flash网站模板

    这是一个炫酷的flash欧美网站模板,它包括首页,公司简介,留言等五个页面,界面转换非常的炫酷!他还有时间.全屏.背景音乐开关的功能!有兴趣的朋友可以看看!贴几张网站图片给大家看看! 下载后直接找到s ...

  9. Android一个炫酷的树状图组织架构图开源控件实现过程

    Android一个炫酷的树状图组织架构图开源控件 文章目录 [1 简介] [2 效果展示] [3 使用步骤] [4 实现基本布局流程] [5 实现自由放缩及拖动] [6 实现添加删除及节点动画] [7 ...

随机推荐

  1. 在IDEA中设置方法自动注释(带参数和返回值)

    第一部分 设置 打开设置面板 新建 在线模板 新建自动添加规则,注意 这里触发的字符 不能随便写 必须为 * Template text 区域 看上去有点乱,但是是为了显示时的对齐,该区域的内容如下( ...

  2. 使用POI解析Excel时,出现org.xml.sax.SAXParseException: duplicate attribute 'o:relid'的解决办法

    1.使用org.apache.poi解析excle,.xlsx类型文件InputStream is = new FileInputStream(strFileName);XSSFWorkbook wb ...

  3. 如何避免在EF自动生成的model中的DataAnnotation被覆盖掉

    摘自ASP.NET MVC 5 网站开发之美 6.4 Metadata与数据验证 如果使用Database-First方式生成*.edms,那么所生成的类文件会在*.tt文件的层级之下,扩展名tt是一 ...

  4. Linux->Ubuntu下配置telnet环境

    1.首先查看telnet运行状态 netstat -a | grep telnet 输出为空,表示没有开启该服务 2.安装openbsd-inetd apt-get install openbsd-i ...

  5. eclipse tomcat jdk 版本引用

    今日遇到一个问题,因为比较难找,所以记录下来,方便日后查阅,也许也可以帮助同行. 一个Java project工程,使用了solr6.2,所以需要引用jdk8才可以正常使用. 代码编写好了,已经提交s ...

  6. wcf 访问控制

    public class PasswordDigestChannelFactory<TPortTypeClient, TPlugin> where TPortTypeClient : Cl ...

  7. ZT linux 线程私有数据之 一键多值技术

    这个原作者的这个地方写错了 且他举的例子非常不好.最后有我的修正版本 pthread_setspecific(key, (void *)&my_errno); linux 线程私有数据之一键多 ...

  8. 清除IE下input的叉叉

    很多时候,我们在开发过程中,设计师会在输入框后加上定制的清除图标,但是在IE下有IE自带的清除图标,肯定是不美观的. <style> ::-ms-clear, ::-ms-reveal{d ...

  9. JDBC(3)ResultSet

    ResultSet 在执行查询(select)时候使用 这是一个结果对象,该对象包含结果的方法但指针定位到一行时 调用Statement 对象的 executeQuery(sql)可以得到结果集 可以 ...

  10. 如何指定安装webpack

    在此我要推荐webpack简易学习教程:https://www.runoob.com/w3cnote/webpack-tutorial.html 大家可以参考这个菜鸟教程,但是这个菜鸟教程有其局限性, ...