123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292 |
- #!/usr/bin/python3
- #-*- coding: UTF-8 -*-
- import sys
- import smbus
- import requests
- from datetime import datetime
- import time
- import random
- from INA226 import INA226
- from Adafruit_HTU21D.HTU21D import HTU21D
- from bmp180 import bmp180
- import board
- import adafruit_bh1750
- import traceback
- ticks = time.time() #记录运行时间戳
- #print(ticks)
- print (time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
- import os
- #写出程序锁
- lock_file = __file__+".lock"
- if not os.path.exists(lock_file):
- os.mknod(lock_file)
- else:
- print ("[Error]\t存在程序锁:" + lock_file)
- exit()
- if os.path.exists("tmp") == False:
- os.mkdir("tmp")
- if os.path.exists("tmp/data") == False: #放数据 给其他程序读
- os.mkdir("tmp/data")
- import RPi.GPIO as GPIO
- GPIO.setwarnings(False)
- bus = smbus.SMBus(1)
- GPIO.setmode(GPIO.BCM)
- Powpin_INA219 = 27
- Sunpin_INA219 = 22
- Weather_3in1 = 17
- #确保都关闭了 避免数据冲突
- GPIO.setup (Weather_3in1,GPIO.IN)
- GPIO.setup (Powpin_INA219,GPIO.IN)
- GPIO.setup (Sunpin_INA219,GPIO.IN)
- import Config
- api = Config.api
- auth = Config.auth
- class Send:
- def Data(data):
- redata = requests.post(api, data=data, auth=auth, stream=False, timeout=10)
- return redata
-
- def Battery_data():
- data = Get.Power_data(Powpin_INA219, "Battery")
- #response = Send.Data(data)
- print (data)
- #print ("Send_Battery:\t" + str(response))
- def SolarPanels_data():
- data = Get.Power_data(Sunpin_INA219, "SolarPanels", "only")
- #response = Send.Data(data)
- print (data)
- #print ("Send_SolarPanels:\t" + str(response))
- def Weather_data():
- data = Get.Weather_data()
- #response = Send.Data(data)
- print (data)
- #print ("Send_Weather:\t" + str(response))
- def CpuTemp_data():
- data = Get.CpuTemp_data()
- #response = Send.Data(data)
- print (data)
- #print ("Send_CpuTemp:\t" + str(response))
- def All_Date():
- SolarPanels_data = ""
- Battery_data = ""
- Weather_data = ""
- CpuTemp_data = ""
- try:
- Weather_data = Get.Weather_data()
- except Exception as e:
- print("Send_All_Date:Weather_data:except: ",e)
- print(traceback.format_exc())
- try:
- SolarPanels_data = Get.Power_data(Sunpin_INA219, "SolarPanels", "Default")
- except Exception as e:
- print("Send_All_Date:SolarPanels_data:except: ",e)
- print(traceback.format_exc())
- try:
- Battery_data = Get.Power_data(Powpin_INA219, "Battery")
- except Exception as e:
- print("Send_All_Date:Battery_data:except: ",e)
- print(traceback.format_exc())
- try:
- CpuTemp_data = Get.CpuTemp_data()
- except Exception as e:
- print("Send_All_Date:CpuTemp_data:except: ",e)
- print(traceback.format_exc())
- All_Data = SolarPanels_data + Battery_data + Weather_data + CpuTemp_data
- response = Send.Data(All_Data)
- #print (All_Data)
- print ("Send_All:\t" + str(response))
- class Get:
- def Power_data(pin, key, Mode="Default"):
- GPIO.setup (pin,GPIO.OUT,initial=GPIO.HIGH)
- time.sleep(3)
- ina226 = INA226()
- Voltage = ina226.busVoltage()
-
- def get_Current(key):
- global Current
- if (key == "SolarPanels"):
- ii = 4
- elif (key == "Battery"):
- ii = 1
- else:
- raise RuntimeError('[Error]\t提供的key错误:'+key)
- if (Voltage >= 4):
- Current = ina226.shuntCurrent()
- time.sleep(3)
- Current = ina226.shuntCurrent()
-
-
- while (Current <= 0.05 or Current >= 1):
- print ("[info]\t"+key+" 电流异常 " + str(Current))
- time.sleep(3)
- Current = ina226.shuntCurrent()
- print ("[info]\t"+key+" 电流异常重试 " + str(Current))
- ii = ii + 1
- if (ii >= 5):
- print ("[warn]\t"+key+" 电流重试过多 " + str(Current))
- break
- return Current
- else:
- print ("[Error]电压获取错误")
- Current = 0
- return 0
- if (key == "SolarPanels"):
- if (Mode == "Default"):
- if (global_Brightness > 0):
- Current = get_Current(key)
- else:
- print ("[info]电流忽略")
- Current = 0
- elif(Mode == "only"):
- print ("[info]电流独立")
- Current = get_Current(key)
- else:
- Current = get_Current(key)
- watts = Voltage*Current
- GPIO.setup (pin,GPIO.IN)
- time.sleep(2)
- data_t = \
- '''{4},tag=1 Voltage={0:.3f} {3:.0f}
- {4},tag=1 Current={1:.3f} {3:.0f}
- {4},tag=1 watts={2:.3f} {3:.0f}
- '''.format(Voltage, Current, watts, ticks, key)
- data = \
- '''{3},tag=1 Voltage={0:.3f}
- {3},tag=1 Current={1:.3f}
- {3},tag=1 watts={2:.3f}
- '''.format(Voltage, Current, watts, key)
- return data
-
- def Weather_data():
- GPIO.setup (Weather_3in1,GPIO.OUT,initial=GPIO.HIGH)
- time.sleep(2)
- h = HTU21D()
- bmp = bmp180(0x77)
- i2c = board.I2C()
- Brightness_data = adafruit_bh1750.BH1750(i2c)
- Temperature = h.read_temperature()
- Humidity = h.read_humidity()
- dewpoint = h.read_dewpoint()
- Pressure = bmp.get_pressure()/100
- Brightness = Brightness_data.lux
- global global_Brightness
- global_Brightness = Brightness
- GPIO.setup (Powpin_INA219,GPIO.IN)
- time.sleep(2)
- data_t = \
- '''Weather,tag=Temperature Temperature={0:.3f} {5:.0f}
- Weather,tag=Humidity Humidity={1:.3f} {5:.0f}
- Weather,tag=dewpoint dewpoint={2:.3f} {5:.0f}
- Weather,tag=Pressure Pressure={3:.3f} {5:.0f}
- Weather,tag=Brightness Brightness={4:.3f} {5:.0f}
- '''.format(Temperature, Humidity, dewpoint, Pressure, Brightness, ticks)
- data = \
- '''Weather,tag=Temperature Temperature={0:.3f}
- Weather,tag=Humidity Humidity={1:.3f}
- Weather,tag=dewpoint dewpoint={2:.3f}
- Weather,tag=Pressure Pressure={3:.3f}
- Weather,tag=Brightness Brightness={4:.3f}
- '''.format(Temperature, Humidity, dewpoint, Pressure, Brightness)
- try:
- file_name="tmp/data/Brightness" #写亮度到文件
- file = open(file_name,"w")
- file.write(str(round(Brightness)))
- file.close()
- except Exception as e:
- print(e)
- return data
- def CpuTemp_data():
- file = open("/sys/class/thermal/thermal_zone0/temp")
- CpuTemp = float(file.read()) / 1000
- file.close()
- data_t = \
- '''Cpu,tag=Temp Temp={0:.3f} {1:.0f}
- '''.format(CpuTemp, ticks)
- data = \
- '''Cpu,tag=Temp Temp={0:.3f}
- '''.format(CpuTemp)
- return data
- def Record_data():
- pass
- def Except_Status(LogData):
- if LogData.find("Max retries exceeded with url") != -1:
- print("[ERROR] NIC_error: reboot")
- os.system('sudo reboot')
- if __name__ == '__main__':
- if len(sys.argv) > 1:
- Parameters = sys.argv[1]
- else:
- Parameters = "All-In-One"
- if Parameters == "All-In-One":
- try:
- Send.All_Date()
- except Exception as e:
- print(traceback.format_exc())
- Except_Status(str(e))
- elif Parameters == "Battery":
- try:
- Send.Battery_data()
- except Exception as e:
- print(traceback.format_exc())
- elif Parameters == "SolarPanels":
- try:
- Send.SolarPanels_data()
- except Exception as e:
- print(traceback.format_exc())
- elif Parameters == "Weather":
- try:
- Send.Weather_data()
- except Exception as e:
- print(traceback.format_exc())
- elif Parameters == "CpuTemp":
- try:
- Send.CpuTemp_data()
- except Exception as e:
- print(traceback.format_exc())
- os.remove (lock_file) #删除程序锁
|