Skip to content

Commit

Permalink
Merge pull request #14 from simat/testing
Browse files Browse the repository at this point in the history
Testing
  • Loading branch information
simat authored May 1, 2018
2 parents dfdf4ee + 9c5ee9a commit a6d965f
Show file tree
Hide file tree
Showing 14 changed files with 938 additions and 200 deletions.
46 changes: 46 additions & 0 deletions ads1115.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/usr/bin/python
# *****BatteryMonitor Getdata from battery cells getdata.py*****
# Copyright (C) 2017 Simon Richard Matthews
# Project loaction https://github.com/simat/BatteryMonitor
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


from config import config
#import smbus
#from Adafruit_I2C import Adafruit_I2C
import Adafruit_ADS1x15 as AtoD
for i in config['AtoDs']:
exec(i + '=' + config['AtoDs'][i])

class Rawdat:
# compile analog capture code to save CPU time
vin = []
for i in sorted(config['VChannels']):
vin = vin + [compile(config['VChannels'][i], '<string>', 'eval')]
# vin = vin + [config['VChannels'][i]]
#for i in config['IChannels']:
# config['IChannels'][i] = compile(config['IChannels'][i], '<string>', 'eval')
iin = []
for i in sorted(config['IChannels']):
iin = iin + [compile(config['IChannels'][i], '<string>', 'eval')]

rawi = [0.0 for i in iin]
rawv = [ 0.0 for i in range(len(vin)+1)]

def getdata(self):
""" Get data for A/Ds, calibrate, covert and place in list variables"""

for i in range(len(self.vin)):
self.rawv[i+1] = eval(self.vin[i])/1000 # A to D 1 to 4 in volts
for i in range(len(self.iin)):
self.rawi[i] = eval(self.iin[i])
85 changes: 85 additions & 0 deletions alarmspip.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
# *****BatteryMonitor main file batteries.py*****
# Copyright (C) 2014 Simon Richard Matthews
# Project loaction https://github.com/simat/BatteryMonitor
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


#!/usr/bin/python
import sys

import serial
import binascii
from config import config
numcells = config['battery']['numcells']

class Alarms:
# Initialise and compile alarms
def __init__(self):
self.overvflg=False
for i in config['alarms']:
exec(config['alarms'][i][0])
config['alarms'][i][1] = compile(config['alarms'][i][1], '<string>', 'exec')
config['alarms'][i][2] = compile(config['alarms'][i][2], '<string>', 'exec')
config['alarms'][i][3] = compile(config['alarms'][i][3], '<string>', 'exec')
config['alarms'][i][4] = compile(config['alarms'][i][4], '<string>', 'exec')
def crccalc(self,command):
"""returns crc as integer from binary string command"""

crc=binascii.crc_hqx(command,0)
crchi=crc>>8
crclo=crc&255

if crchi == 0x28 or crchi==0x0d or crchi==0x0a:
crc+=256

if crclo == 0x28 or crclo==0x0d or crclo==0x0a:
crc+=1
return crc


def scanalarms(self,batdata):
for i in config['alarms']:
exec(config['alarms'][i][1])
if self.test:
# sys.stderr.write('Alarm 1 triggered')
exec(config['alarms'][i][2])
exec(config['alarms'][i][3])
if self.test:
exec(config['alarms'][i][4])

def sendcmd(self,command,replylen):
"""send command/query to Pip4048, return reply"""
port = serial.Serial(config['files']['pipport'],baudrate=2400) # open serial port
port.timeout = 3

for i in range(5):
try:
command=command.encode('ascii','strict')
crc=self.crccalc(command)
command=command+crc.to_bytes(2, byteorder='big')+b'\r'
port.write(command)
reply = port.read(replylen)
if self.crccalc(reply[0:-3]) != int.from_bytes(reply[-3:-1],byteorder='big'):
raise IOError("CRC error in Pip4048 return string")
break
except IOError as err:
print(err.args)
if i==4:
raise
port.close()
return reply

def setparam(self,command,replylen):
reply=self.sendcmd(command,replylen)
if reply[1:4]!=b'ACK':
raise IOError('Bad Parameters')
246 changes: 120 additions & 126 deletions batteries.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,21 +23,10 @@
from config import loadconfig, config
from configparser import SafeConfigParser
numcells = config['battery']['numcells']

import logging
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
errfile=logging.FileHandler(config['files']['errfile'])
#errfile.setLevel(logging.DEBUG)

# create formatter
formatter = logging.Formatter(config['loggers']['format'])

# add formatter to ch
errfile.setFormatter(formatter)

# add ch to logger
logger.addHandler(errfile)
import logger
log = logger.logging.getLogger(__name__)
log.setLevel(logger.logging.DEBUG)
log.addHandler(logger.errfile)

from getdata import Readings
exec(config['files']['alarms']) # import alarm code
Expand All @@ -46,119 +35,124 @@

def deamon(soc=-1):
""" Main loop, gets battery data, gets summary.py to do logging"""
import summary
logsummary = summary.Summary()
summary = logsummary.summary
printtime = time.strftime("%Y%m%d%H%M%S ", time.localtime())
while int(printtime) <= int(summary['current']['timestamp']):
print(printtime,summary['current']['timestamp'])
print ("Error: Current time before last sample time")
time.sleep(30)
printtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
batdata = Readings() # initialise batdata after we have valid sys time
alarms = Alarms() # initialise alarms

logger.debug(printtime)
print (str(printtime))
filecopy(config['files']['summaryfile'],config['files']['summaryfile']+"R" + str(int(printtime)))
if soc > config['battery']['capacity']:
print ("Battery DOD must be less than Battery Capacity")
else:
if soc < 0:
batdata.soc = summary['current']['ah'][0]
batdata.socadj = summary['current']['dod'][0]

try:
import summary
logsummary = summary.Summary()
summary = logsummary.summary
printtime = time.strftime("%Y%m%d%H%M%S ", time.localtime())
while int(printtime) <= int(summary['current']['timestamp']):
print(printtime,summary['current']['timestamp'])
print ("Error: Current time before last sample time")
time.sleep(30)
printtime = time.strftime("%Y%m%d%H%M%S", time.localtime())
batdata = Readings() # initialise batdata after we have valid sys time
alarms = Alarms() # initialise alarms

print (str(printtime))
filecopy(config['files']['summaryfile'],config['files']['summaryfile']+"R" + str(int(printtime)))
if soc > config['battery']['capacity']:
print ("Battery DOD must be less than Battery Capacity")

else:
batdata.soc = soc
batdata.socadj = soc
summary['current']['dod'][3] = 0
summary['current']['dod'][3] = -100 # flag don't adjust leakage current
prevtime = logsummary.currenttime
prevbatvoltage = batdata.batvoltsav[numcells]
# logsummary.startday(summary)
# logsummary.starthour(summary)


while True:
try:
for i in range(config['sampling']['samplesav']):
# printvoltage = ''
# for i in range(numcells+1):
# printvoltage = printvoltage + str(round(batdata.batvolts[i],3)).ljust(5,'0') + ' '
# print (printvoltage)
batdata.getraw()

# if batdata.batvoltsav[numcells] >= 55.2 and prevbatvoltage < 55.2: # reset SOC counter?
# print batdata.socadj/(float(summary['current']['dod'][3])*24.0)
if batdata.batvoltsav[numcells] < config['battery']['vreset'] \
and prevbatvoltage >= config['battery']['vreset'] \
and summary['current']['dod'][3] != 0 \
and -batdata.currentav[0] < config['battery']['ireset']: # reset SOC counter?

if summary['current']['dod'][3] <= 0 :
socerr=0
if soc < 0:
batdata.soc = summary['current']['ah'][0]
batdata.socadj = summary['current']['dod'][0]
else:
batdata.soc = soc
batdata.socadj = soc
summary['current']['dod'][3] = 0
summary['current']['dod'][3] = -100 # flag don't adjust leakage current
prevtime = logsummary.currenttime
prevbatvoltage = batdata.batvoltsav[numcells]
# logsummary.startday(summary)
# logsummary.starthour(summary)


while True:
try:
for i in range(config['sampling']['samplesav']):
# printvoltage = ''
# for i in range(numcells+1):
# printvoltage = printvoltage + str(round(batdata.batvolts[i],3)).ljust(5,'0') + ' '
# print (printvoltage)
batdata.getraw()

# if batdata.batvoltsav[numcells] >= 55.2 and prevbatvoltage < 55.2: # reset SOC counter?
# print batdata.socadj/(float(summary['current']['dod'][3])*24.0)
if batdata.batvoltsav[numcells] < config['battery']['vreset'] \
and prevbatvoltage >= config['battery']['vreset'] \
and summary['current']['dod'][3] != 0 \
and -batdata.currentav[0] < config['battery']['ireset']: # reset SOC counter?

if summary['current']['dod'][3] <= 0 :
socerr=0
else:
socerr=batdata.socadj/(float(summary['current']['dod'][3])*24.0)
socerr=max(socerr,-0.01)
socerr=min(socerr,0.01)
config['battery']['ahloss']=config['battery']['ahloss']-socerr/2
batconfigdata=SafeConfigParser()
batconfigdata.read('battery.cfg')
batconfigdata.set('battery','ahloss',str(config['battery']['ahloss']))
with open('battery.cfg', 'w') as batconfig:
batconfigdata.write(batconfig)
batconfig.closed

batdata.soc = 0.0
batdata.socadj = 0.0
summary['current']['dod'][3] = 0
else:
socerr=batdata.socadj/(float(summary['current']['dod'][3])*24.0)
socerr=max(socerr,-0.01)
socerr=min(socerr,0.01)
config['battery']['ahloss']=config['battery']['ahloss']-socerr/2
batconfigdata=SafeConfigParser()
batconfigdata.read('battery.cfg')
batconfigdata.set('battery','ahloss',str(config['battery']['ahloss']))
with open('battery.cfg', 'w') as batconfig:
batconfigdata.write(batconfig)
batconfig.closed

batdata.soc = 0.0
batdata.socadj = 0.0
summary['current']['dod'][3] = 0
else:
batdata.soc = batdata.soc + batdata.batah
batdata.socadj = batdata.socadj +batdata.batahadj
batdata.ah = batdata.ah + batdata.batah
batdata.inahtot = batdata.inahtot + batdata.inah
batdata.pwrbattot = batdata.pwrbattot + batdata.pwrbat
batdata.pwrintot = batdata.pwrintot + batdata.pwrin
prevbatvoltage = batdata.batvoltsav[numcells]
# check alarms
alarms.scanalarms(batdata)
# update summaries
logsummary.update(summary, batdata)
if logsummary.currenttime[4] != logsummary.prevtime[4]: # new minute
loadconfig()
logsummary.updatesection(summary, 'hour', 'current')
logsummary.updatesection(summary, 'alltime','current')
logsummary.updatesection(summary, 'currentday','current')
logsummary.updatesection(summary, 'monthtodate', 'current')
logsummary.updatesection(summary, 'yeartodate', 'current')
logsummary.writesummary()
batdata.ah = 0.0
batdata.ahadj = 0.0
batdata.inahtot = 0.0
batdata.pwrbattot = 0.0
batdata.pwrintot = 0.0
for i in range(batdata.numiins):
batdata.kWhin[i] = 0.0
batdata.kWhout[i] = 0.0



if logsummary.currenttime[3] != logsummary.prevtime[3]: # new hour
logsummary.starthour(summary)

if logsummary.currenttime[3] < logsummary.prevtime[3]: # newday
logsummary.startday(summary)

if logsummary.currenttime[1] != logsummary.prevtime[1]: # new month
logsummary.startmonth(summary)

if logsummary.currenttime[0] != logsummary.prevtime[0]: # new year
logsummary.startyear(summary)

except KeyboardInterrupt:
sys.stdout.write('\n')
logsummary.close()
sys.exit(9)
break
batdata.soc = batdata.soc + batdata.batah
batdata.socadj = batdata.socadj +batdata.batahadj
batdata.ah = batdata.ah + batdata.batah
batdata.inahtot = batdata.inahtot + batdata.inah
batdata.pwrbattot = batdata.pwrbattot + batdata.pwrbat
batdata.pwrintot = batdata.pwrintot + batdata.pwrin
prevbatvoltage = batdata.batvoltsav[numcells]
# check alarms
alarms.scanalarms(batdata)
# update summaries
logsummary.update(summary, batdata)
if logsummary.currenttime[4] != logsummary.prevtime[4]: # new minute
loadconfig()
logsummary.updatesection(summary, 'hour', 'current')
logsummary.updatesection(summary, 'alltime','current')
logsummary.updatesection(summary, 'currentday','current')
logsummary.updatesection(summary, 'monthtodate', 'current')
logsummary.updatesection(summary, 'yeartodate', 'current')
logsummary.writesummary()
batdata.ah = 0.0
batdata.ahadj = 0.0
batdata.inahtot = 0.0
batdata.pwrbattot = 0.0
batdata.pwrintot = 0.0
for i in range(batdata.numiins):
batdata.kWhin[i] = 0.0
batdata.kWhout[i] = 0.0



if logsummary.currenttime[3] != logsummary.prevtime[3]: # new hour
logsummary.starthour(summary)

if logsummary.currenttime[3] < logsummary.prevtime[3]: # newday
logsummary.startday(summary)

if logsummary.currenttime[1] != logsummary.prevtime[1]: # new month
logsummary.startmonth(summary)

if logsummary.currenttime[0] != logsummary.prevtime[0]: # new year
logsummary.startyear(summary)

except KeyboardInterrupt:
sys.stdout.write('\n')
logsummary.close()
sys.exit(9)
break
except Exception as err:
log.critical(err)
raise

if __name__ == "__main__":
print (sys.argv)
Expand Down
Loading

0 comments on commit a6d965f

Please sign in to comment.