#!/usr/bin/python

import serial
import time
import sys
import os
import stat
from common import getname

cpufreqpath = '/sys/devices/system/cpu/cpu0/cpufreq'
targetLMP = 4000
def adjust_frequency(lmp):
	minf = int(open('%s/cpuinfo_min_freq' % cpufreqpath, 'r').read())
	maxf = int(open('%s/cpuinfo_max_freq' % cpufreqpath, 'r').read())
	curf = int(open('%s/cpuinfo_cur_freq' % cpufreqpath, 'r').read())
	if lmp > targetLMP:
		# price is high, slow down
		target = minf
	else:
		target = maxf

	print "lmp %d old speed %d new target %d" % (lmp, curf, target)
	open('%s/scaling_setspeed' % cpufreqpath, 'w').write('%d\n' % target)

	return target

clear = 0

# For now, assume /dev/ttyUSB0 is the wattsUP? meter. Later we should do things
# like grovel through /sys/class/tty/ttyUSB0 for devices that match the USB ID codes
# for the meter
ser = serial.Serial('/dev/ttyUSB0', 115200, timeout=2)

f = open(getname(), 'a')

#version
ser.write('#V,R,0;')
f.write(ser.readline())

ser.write('#F,R,0;')
f.write(ser.readline())

if clear:
	#clear memory
	ser.write('#R,W,0;')
	f.write(ser.readline())

LMPlog = '/var/www/mrtg/lmp.log'
CurPwr = '/var/www/meter/data/CurPwr'

ser.write('#L,W,3,E,0,1;')  

lastlog = 0

new = []

while True:
	if (getname() != f.name):
		f.close()
		f = open(getname(), 'a')
		f.write('# wattsup.py %s\n' % f.name)
	line = ser.readline()
	f.write(line)
	if (len(line) > 3 and line[0:4] == '#d,-'):
		new.append(int(line.split(',')[3]))
	# adjust power if needed
	s = os.stat(LMPlog)
	if s[stat.ST_MTIME] > lastlog:
		print lastlog, s[stat.ST_MTIME]
		lastlog = s[stat.ST_MTIME]
		lmpf = open(LMPlog, 'r')
		r = adjust_frequency(int(lmpf.readline().split()[1]))
		lmpf.close()
		avg = 0
		if len(new) > 0:
			avg = float(sum(new))/len(new)/10
		new = []
		f.write('!F,%d,%f;\n' % (r, avg))
		open(CurPwr, 'w').write("%f\n%d\n" % (avg*10000, r))


	f.flush()

