Skip to content

Instantly share code, notes, and snippets.

@kjmkznr
Created May 2, 2011 14:38
Show Gist options
  • Save kjmkznr/951695 to your computer and use it in GitHub Desktop.
Save kjmkznr/951695 to your computer and use it in GitHub Desktop.
ThinkPad でピークシフト機能を使うスクリプト
#!/usr/bin/python
import sys
import os
import syslog
from datetime import datetime
import urllib
import json
def get_forecast(num=6):
params = urllib.urlencode({
'appid': 'HZOLGtKxg64J5ff8Oj7fmfNpXGJmYWJEL.xD38B4QsMiWgbOdn76MdfHTslUFA--',
'output': 'json',
'area': 'tokyo',
'results': num
})
forecast_uri = "http://setsuden.yahooapis.jp/v1/Setsuden/electricPowerForecast?%s"
ret = urllib.urlopen(forecast_uri % params)
forecast = json.loads(ret.read())['ElectricPowerForecasts']['Forecast']
# Sample result:
# {
# u'Usage': {
# u'$': u'29430000',
# u'@unit': u'kW'
# },
# u'Date': u'2011-05-02',
# u'Capacity': {
# u'$': u'34500000',
# u'@unit': u'kW'
# },
# u'Hour': u'15',
# u'Area': u'tokyo'
# }
percent = []
now = datetime.today()
for f in forecast:
date = "%s %s" % (f['Date'], f['Hour'])
usage = float(f['Usage']['$'])
capacity = float(f['Capacity']['$'])
d = datetime.strptime(date, "%Y-%m-%d %H")
if d > now:
percent.append(usage / capacity * 100)
return percent
class SMAPI:
def __init__(self):
self.smapi_path = "/sys/devices/platform/smapi"
# check load smapi
if not os.path.exists(self.smapi_path):
raise Exception('Can not access to SMAPI.')
# check ac connect
if self.__sysfs_read(self.smapi_path + "/ac_connected") == '0':
raise Exception('Not connect AC Adapter.')
# check installed battery
self.battery = ["BAT0", "BAT1"]
for bat in self.battery:
if self.get_value("installed", bat) == '0':
self.battery.remove(bat)
def __sysfs_write(self, path, value):
with open(path, 'w') as f:
f.write(value)
def __sysfs_read(self, path):
with open(path, 'r') as f:
retval = f.read()
return retval.rstrip('\n')
def set_value(self, attr, value):
path = self.smapi_path + "/%s/%s"
for bat in self.battery:
self.__sysfs_write(path % (bat, attr), value)
def get_value(self, attr, bat="BAT0"):
return self.__sysfs_read("%s/%s/%s" % (self.smapi_path, bat, attr))
if __name__ == "__main__":
syslog.syslog('tp_peakshift.py started')
try:
smapi = SMAPI()
except Exception, msg:
syslog.syslog(syslog.LOG_ERR, "error: %s" % msg)
sys.exit(1)
percent = get_forecast()
threshold = 80
syslog.syslog("electric power forecast: %s %%" % percent[0])
if percent[0] >= threshold or percent[1] >= threshold:
if percent[0] > percent[1]:
# Force discharge
smapi.set_value("force_discharge", "1")
syslog.syslog("Switch to discharge mode.")
elif percent[0] <= percent[1]:
# pending charge
smapi.set_value("inhibit_charge_minutes", 60)
syslog.syslog( "Stop battery charge.")
else:
smapi.set_value('force_discharge', '0')
smapi.set_value('inhibit_charge_minutes', '0')
syslog.syslog( "Do not need powersave.")
syslog.syslog("tp_peakshift.py stoped")
sys.exit(0)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment