树莓派上传数据错误一例

摘要:
首先是源码:1#-*-utf-8-*-2#env!

首先是源码:

1 #-*- utf-8 -*-
2 #env !/usr/bin/python
3 
4 importRPi.GPIO as GPIO
5 importtime
6 importjson
7 importdatetime
8 importrequests
9 
10 requests.adapters.DEFAULT_RETRIES = 5
11 #s = requests.session()
12 #s.keep_alive = False
13 apiurl = 'https://xxxxxx.cn/api/TmpApi'
14 apiheaders = {'Content-Type': 'application/json','Connection': 'close'}
15 
16 defgetCPUTemp():
17     file = open("/sys/class/thermal/thermal_zone0/temp")
18     cpuTemp=float(file.read())/1000
19 file.close()
20     returncpuTemp
21 
22 defgetTemp():
23     channel = 17
24     data =[]
25     j =0
26 
27 GPIO.setmode(GPIO.BCM)
28 
29     time.sleep(1)
30 
31 GPIO.setup(channel, GPIO.OUT)
32 
33 GPIO.output(channel, GPIO.LOW)
34     time.sleep(0.02)
35 GPIO.output(channel, GPIO.HIGH)
36 
37 GPIO.setup(channel, GPIO.IN)
38 
39     while GPIO.input(channel) ==GPIO.LOW:
40         continue
41 
42     while GPIO.input(channel) ==GPIO.HIGH:
43         continue
44 
45     while j < 40:
46         k =0
47         while GPIO.input(channel) ==GPIO.LOW:
48             continue
49     
50         while GPIO.input(channel) ==GPIO.HIGH:
51             k += 1
52             if k > 100:
53                 break
54     
55         if k < 8:
56 data.append(0)
57         else:
58             data.append(1)
59 
60         j += 1
61 
62     print("sensor is working.")
63     #print(data)
64 
65     humidity_bit = data[0:8]
66     humidity_point_bit = data[8:16]
67     temperature_bit = data[16:24]
68     temperature_point_bit = data[24:32]
69     check_bit = data[32:40]
70 
71     humidity =0
72     humidity_point =0
73     temperature =0
74     temperature_point =0
75     check =0
76     
77     cpu_temperature =0
78 
79     for i in range(8):
80         humidity += humidity_bit[i] * 2 ** (7 -i)
81         humidity_point += humidity_point_bit[i] * 2 ** (7 -i)
82         temperature += temperature_bit[i] * 2 ** (7 -i)
83         temperature_point += temperature_point_bit[i] * 2 ** (7 -i)
84         check += check_bit[i] * 2 ** (7 -i)
85 
86     tmp = humidity + humidity_point + temperature +temperature_point
87 
88     csv=open('/home/pi/Desktop/Projects/DHT11/log.csv', 'a+')
89     if humidity>99:
90         return "Wrong data"
91     if check ==tmp:
92         print("temperature : ", temperature, ", humidity : ", humidity)
93         cpu_temperature =getCPUTemp()
94         print("CPU Temperature : ", cpu_temperature)
95 
96         CurTime =datetime.datetime.now()
97         payload = {'DeviceName':"DHT11a",'Temp':temperature,'Humidity':humidity,'AcquisitionTime':CurTime.isoformat(), 'Memo': 'cpu:%.3f' %cpu_temperature}
98         print("Current time: %s" %CurTime.isoformat())
99         print("Upload Temperature: %.3f" % temperature,"Humdity: %.3f" %humidity)
100 
101         jdata =json.dumps(payload)
102 
103         r=requests.post(apiurl,headers=apiheaders,data=json.dumps(payload))
104 
105         csv.write(time.strftime("%Y/%m/%d %H:%M:%S",time.localtime()) + ",")
106 csv.write(str(temperature))
107         csv.write(',')
108 csv.write(str(humidity))
109         csv.write('')
110     else:
111         #print("wrong")
112         r = "wrong"
113         print("temperature : ", temperature, ", humidity : " , humidity, "check : ", check, "tmp : ", tmp)
114 
115 csv.close()
116 
117     returnr
118 
119 if __name__ == "__main__":
120     try:
121         while 1:
122             resp =getTemp()
123             print("xxxxxx.cn request result:  %s" %resp)
124             time.sleep(60)
125     finally:
126         GPIO.cleanup()

错误故障:

1 sensor isworking.
2 temperature :  24 , humidity :  44
3 CPU Temperature :  47.236
4 Current time: 2018-09-14T04:37:06.303399
5 Upload Temperature: 24.000 Humdity: 44.000
6 xxxxxx.cn request result:  <Response [201]>
7 sensor isworking.
8 temperature :  16 , humidity :  50  check :  161  tmp :  78
9 xxxxxx.cn request result:  wrong
10 sensor isworking.
11 temperature :  24 , humidity :  55
12 CPU Temperature :  46.698
13 Current time: 2018-09-14T04:39:08.722444
14 Upload Temperature: 24.000 Humdity: 55.000
15 Traceback (most recent call last):
16   File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 138, in_new_conn
17     (self.host, self.port), self.timeout, **extra_kw)
18   File "/usr/lib/python3/dist-packages/urllib3/util/connection.py", line 75, increate_connection
19     for res insocket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
20   File "/usr/lib/python3.5/socket.py", line 733, ingetaddrinfo
21     for res in_socket.getaddrinfo(host, port, family, type, proto, flags):
22 socket.gaierror: [Errno -3] Temporary failure inname resolution
23 
24 During handling of the above exception, another exception occurred:
25 
26 Traceback (most recent call last):
27   File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 594, inurlopen
28     chunked=chunked)
29   File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 350, in_make_request
30 self._validate_conn(conn)
31   File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 837, in_validate_conn
32 conn.connect()
33   File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 281, inconnect
34     conn =self._new_conn()
35   File "/usr/lib/python3/dist-packages/urllib3/connection.py", line 147, in_new_conn
36     self, "Failed to establish a new connection: %s" %e)
37 requests.packages.urllib3.exceptions.NewConnectionError: <requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x75aa01b0>: Failed to establish a new connection: [Errno -3] Temporary failure inname resolution
38 
39 During handling of the above exception, another exception occurred:
40 
41 Traceback (most recent call last):
42   File "/usr/lib/python3/dist-packages/requests/adapters.py", line 423, insend
43     timeout=timeout
44   File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 643, inurlopen
45     _stacktrace=sys.exc_info()[2])
46   File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 363, inincrement
47     raise MaxRetryError(_pool, url, error orResponseError(cause))
48 requests.packages.urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='xxxxxx.cn', port=443): Max retries exceeded with url: /api/TmpApi (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x75aa01b0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',))
49 
50 During handling of the above exception, another exception occurred:
51 
52 Traceback (most recent call last):
53   File "dht11GV.py", line 121, in <module>
54     resp =getTemp()
55   File "dht11GV.py", line 102, ingetTemp
56     r=requests.post(apiurl,headers=apiheaders,data=json.dumps(payload))
57   File "/usr/lib/python3/dist-packages/requests/api.py", line 110, inpost
58     return request('post', url, data=data, json=json, **kwargs)
59   File "/usr/lib/python3/dist-packages/requests/api.py", line 56, inrequest
60     return session.request(method=method, url=url, **kwargs)
61   File "/usr/lib/python3/dist-packages/requests/sessions.py", line 488, inrequest
62     resp = self.send(prep, **send_kwargs)
63   File "/usr/lib/python3/dist-packages/requests/sessions.py", line 609, insend
64     r = adapter.send(request, **kwargs)
65   File "/usr/lib/python3/dist-packages/requests/adapters.py", line 487, insend
66     raise ConnectionError(e, request=request)
67 requests.exceptions.ConnectionError: HTTPSConnectionPool(host='xxxxxx.cn', port=443): Max retries exceeded with url: /api/TmpApi (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x75aa01b0>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution',))

根据错误提示

Max retries exceeded with url: /api/TmpApi (Caused by NewConnectionError('<requests.packages.urllib3.connection.VerifiedHTTPSConnection object at 0x75aa01b0>: 
Failed to establish a new connection: [Errno -3] Temporary failure in name resolution

在网上找到以下几个点:

1. requests模块太老,须升级:

pip install --upgrade requests

2.连接数太多,没有释放:

解决办法:

1、增加重试连接次数

  requests.adapters.DEFAULT_RETRIES = 5

2、关闭多余的连接

requests使用了urllib3库,默认的http connection是keep-alive的,requests设置False关闭。

操作方法

s = requests.session()
  s.keep_alive = False

3.加代理服务器:

http://obroll.com/max-retries-exceeded-for-url-in-requests-module-python-solved/ 
A: 
Python代码 
proxy = {'http': '33.33.33.10:8118'}  
result = requests.get(url, proxies=proxy)  

B: 
Java代码
proxy = '33.33.33.11:8118'  
result = requests.get(url, proxies={'http': proxy})  

分析:

因为是自建的网站,所以排除封锁IP的可能,所以代理服务器方法不用尝试。

尝试方法1和2,看后续效果。

免责声明:文章转载自《树莓派上传数据错误一例》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Spring中日志的使用(log4j)02_iOS 沙盒及各个目录详解下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

PCI规范学习笔记

以前看过一段时间Cyclone FPGA控制PEX8111的程序,没看懂,最近又结合PCI规范重新看了一下。 PCI Speci rev2.3    FRAME# is driven by the master to indicate the beginning and end of a transaction.   IRDY# is driven by...

Python3 中 configparser 使用注意事项

在使用configparser时候应注意: ①配置文件(ini文件)的存放位置:配置文件和调用文件放在同一个文件包下面。 使用read()函数读取并解析配置文件时,直接写配置文件(ini文件)的文件名即可。 例如: cf=ConfigParser() #实例化cf.read("PageElementLocator.ini...

python3中的编码与解码原理

先看代码 >>> a = '中文' >>>a '中文' >>> print(a) 中文 >>> b = 'English' >>>b 'English' >>> print(b) English 解释编码和解码的过程 >...

AVR单片机教程——示波器

本文隶属于AVR单片机教程系列。   在用DAC做了一个稍大的项目之后,我们来拿ADC开开刀。在本讲中,我们将了解0.96寸OLED屏,移植著名的U8g2库到我们的开发板上,学习在屏幕上画直线的算法,编写一个示波器程序,使用EEPROM加入人性化功能,最后利用示波器观察555定时器、放大电路、波形变换电路的各种波形。 本讲所需的资料可以在这里下载:提取码6...

高通Android Camera Bring up

高通Android Camera的移植 注:此文档以在高通8916平台移植OV5648为例,给大家讲解Android SOC的底层Camera。 Reference: https://blog.csdn.net/weijory/article/details/53811140 https://www.jianshu.com/p/70bdb79e5026...

STM32学习笔记——USART串口(向原子哥和火哥学习)

一、USART简介 通用同步异步收发器(USART)提供了一种灵活的方法与使用工业标准NRZ异步串行数据格式的外部设备之间进行全双工数据交换。USART利用分数波特率发生器提供宽范围的波特率选择。 STM32 的串口资源相当丰富的,功能也相当强劲。STM32F103ZET6 最多可提供 5 路串口,有分数波特率发生器,支持同步单向通信和半双工单线通信,支持...