标签:tput cleanup span cat oca method ret mil sys
首先是源码:
1 # -*- utf-8 -*- 2 #env !/usr/bin/python 3 4 import RPi.GPIO as GPIO 5 import time 6 import json 7 import datetime 8 import requests 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 def getCPUTemp(): 17 file = open("/sys/class/thermal/thermal_zone0/temp") 18 cpuTemp=float(file.read())/1000 19 file.close() 20 return cpuTemp 21 22 def getTemp(): 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(‘\n‘) 110 else: 111 # print("wrong") 112 r = "wrong" 113 print("temperature : ", temperature, ", humidity : " , humidity, " check : ", check, " tmp : ", tmp) 114 115 csv.close() 116 117 return r 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 is working. 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 is working. 8 temperature : 16 , humidity : 50 check : 161 tmp : 78 9 xxxxxx.cn request result: wrong 10 sensor is working. 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, in create_connection 19 for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): 20 File "/usr/lib/python3.5/socket.py", line 733, in getaddrinfo 21 for res in _socket.getaddrinfo(host, port, family, type, proto, flags): 22 socket.gaierror: [Errno -3] Temporary failure in name 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, in urlopen 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, in connect 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 in name 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, in send 43 timeout=timeout 44 File "/usr/lib/python3/dist-packages/urllib3/connectionpool.py", line 643, in urlopen 45 _stacktrace=sys.exc_info()[2]) 46 File "/usr/lib/python3/dist-packages/urllib3/util/retry.py", line 363, in increment 47 raise MaxRetryError(_pool, url, error or ResponseError(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, in getTemp 56 r=requests.post(apiurl,headers=apiheaders,data=json.dumps(payload)) 57 File "/usr/lib/python3/dist-packages/requests/api.py", line 110, in post 58 return request(‘post‘, url, data=data, json=json, **kwargs) 59 File "/usr/lib/python3/dist-packages/requests/api.py", line 56, in request 60 return session.request(method=method, url=url, **kwargs) 61 File "/usr/lib/python3/dist-packages/requests/sessions.py", line 488, in request 62 resp = self.send(prep, **send_kwargs) 63 File "/usr/lib/python3/dist-packages/requests/sessions.py", line 609, in send 64 r = adapter.send(request, **kwargs) 65 File "/usr/lib/python3/dist-packages/requests/adapters.py", line 487, in send 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,看后续效果。
标签:tput cleanup span cat oca method ret mil sys
原文地址:https://www.cnblogs.com/keepee/p/9644551.html