class Plug(): def __init__(self, plug_ip): # Init plug self.plug = SmartPlug(plug_ip) # -- def info(self): print(' -- Plug Info -- ') print('Name: %s' % self.plug.name) print('Model: %s' % self.plug.model) print('Mac: %s' % self.plug.mac) print('Time: %s' % self.plug.time) print('Is on: %s' % self.plug.is_on) print('Nightmode: %s' % (not self.plug.led)) print('RSSI: %s' % self.plug.rssi) # -- def plug_on(self): time.sleep(1) if not self.plug.is_on: self.plug.turn_on() print('Plug turned on') # -- def plug_off(self): time.sleep(1) if self.plug.is_on: self.plug.turn_off() print('Plug turned off')
def __init__(self, id, host, port=9999, timeout=5): """ constructor . str id: the id for the device . str host: host name or ip address on which the device listens . int port: port on which the device listens (default: 9999) . int timeout: socket timeout (default: 5) """ self.id = id self.smartPlug = SmartPlug(host, port, timeout)
def bruteSearchPresa(): baseIp = getConfigurazione()['baseIp'] for x in range(100, 120): try: plug = SmartPlug(baseIp + str(x)) plug.name return plug, (baseIp + str(x)) except: continue
def getPresa(): #return bruteSearchPresa() # Recupero l'ultimo ip utilizato dalla presa vecchioIp = recuperaUltimoIpConosciutoPresa() if ("192" in vecchioIp): try: plug = SmartPlug(vecchioIp) # Provo ad accede al nome. Va in eccezione se non è la presa plug.name return plug, vecchioIp except: # Ha cambiato ip return bruteSearchPresa() else: # Non riesce a trovare l'ip nel file return bruteSearchPresa()
def main_loop(): # init inv = Inverter(0x1, '/dev/ttyUSB0') inv.version() if OWMKey: owm = Weather(OWMKey, OWMLat, OWMLon) owm.fresh = False else: owm = False pvo = PVOutputAPI(APIKEY, SYSTEMID) fan = SmartPlug(FAN_IP_ADDR) # Loop until end of universe while True: if owm: try: owm.get() owm.fresh = True except Exception as e: print('Error getting weather: {}'.format(e)) owm.fresh = False # get readings from inverter, if success send to pvoutput inv.read_inputs() if inv.status != -1: if inv.temp >= 30: fan.turn_on() else: fan.turn_off() temp = owm.temperature if owm and owm.fresh else None pvo.send_status(date=inv.date, energy_gen=inv.wh_today, power_gen=inv.ac_power, vdc=inv.pv_volts, vac=inv.ac_volts, temp=temp, temp_inv=inv.temp, energy_life=inv.wh_total, power_vdc=inv.pv_power) # sleep until next multiple of 5 minutes min = 5 - localnow().minute % 5 sleep(min * 60 - localnow().second) else: # some error sleep(60) # 1 minute before try again
raise Exception( f"INFLUXDB_PASSWORD can't be empty, value={config['influxdb']['password']}" ) if config["delay"] < 10 or config["delay"] > 3600: raise Exception( f"DELAY must be in range [10, 3600], value={config['delay']}") if config["nb_smartplug"] < 1: raise Exception( f"NB_SMARTPLUG must be superior or equal to 1, value={config['nb_smartplug']}" ) except Exception as error: sys_exit(f'{error}') for i in range(0, config["nb_smartplug"]): ip_smartplug = str(ipaddressIPv4(config["smartplugs"][i])) smartplugs.append(SmartPlug(ip_smartplug)) while True: for smartplug in smartplugs: try: data = "" smartplug_data = smartplug.info smartplug_data.update(smartplug.emeter_stats()) data = f'hs110 mac="{smartplug_data["mac"]}",version="{smartplug_data["sw_ver"]}",name="{smartplug_data["alias"]}",state={smartplug_data["relay_state"]},voltage_mv={smartplug_data["voltage_mv"]},current_ma={smartplug_data["current_ma"]},power_mw={smartplug_data["power_mw"]},total_wh={smartplug_data["total_wh"]}\n' r = requests_post(config["influxdb"]["url"] + '/write', data=data, params={ 'db': config["influxdb"]["database"], 'u': config["influxdb"]["username"], 'p': config["influxdb"]["password"] })
def startplug(plugnumber): global plug1 global plug2 global plug3 global last_plug1 global last_plug2 global last_plug3 global leaf1 global leaf2 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #help(SmartPlug) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logging.getLogger("pycarwings2").setLevel(logging.ERROR) logging.getLogger("urllib3").setLevel(logging.ERROR) parser = ConfigParser() candidates = ['config.ini', 'my_config.ini'] found = parser.read(candidates) bot_token = parser.get('get-leaf-info', 'bot_token') print("bot_token", bot_token) bot_chatID = parser.get('get-leaf-info', 'bot_chatID') print("bot_chatID", bot_chatID) test = telegram_bot_sendtext("Starting ....", bot_token, bot_chatID) while (1): print("\n\n\n\n\n\nAnother loop\n\n\n\n") found = parser.read(candidates) plug1address = parser.get('get-leaf-info', 'plug1address') plug2address = parser.get('get-leaf-info', 'plug2address') plug3address = parser.get('get-leaf-info', 'plug3address') current_date_and_time = datetime.datetime.now() current_hour = current_date_and_time.hour plug1 = SmartPlug(plug1address) emeterinfo1 = infoEnchufe(plug1, "First car plug") plug2 = SmartPlug(plug2address) emeterinfo2 = infoEnchufe(plug2, "Second car plug") plug3 = SmartPlug(plug3address) emeterinfo3 = infoEnchufe(plug3, "Water warmer plug") if (write_thingsboard): print(config_tb.telemetry_address) print(config_tb.telemetry_address2) unixtime = int(time.mktime(plug1.time.timetuple()) * 1000) unixtime2 = int(time.mktime(plug2.time.timetuple()) * 1000) category = "plug1" pload = { 'ts': unixtime, "values": { category + '_is_on': plug1.is_on, category + '_rssi': plug1.rssi, category + '_current_ma': emeterinfo1['current_ma'], category + '_power_mw': emeterinfo1['power_mw'], } } print(pload) print("========") r = requests.post(config_tb.telemetry_address, json=pload) print(r.status_code) category = "plug2" pload = { 'ts': unixtime, "values": { category + '_is_on': plug2.is_on, category + '_rssi': plug2.rssi, category + '_current_ma': emeterinfo2['current_ma'], category + '_power_mw': emeterinfo2['power_mw'], } } print(pload) print("========") r = requests.post(config_tb.telemetry_address2, json=pload) print(r.status_code) category = "plug3" pload = { 'ts': unixtime, "values": { category + '_is_on': plug3.is_on, category + '_rssi': plug3.rssi, category + '_current_ma': emeterinfo3['current_ma'], category + '_power_mw': emeterinfo3['power_mw'], } } print(pload) print("========") r = requests.post(config_tb.telemetry_address3, json=pload) print(r.status_code) if plugnumber == 1: turn_1_on() else: if plugnumber == 2: car2present = turn_2_on() else: turn_off() print('Plug 1 Is on: %s' % plug1.is_on) print('Plug 2 Is on: %s' % plug2.is_on) print('Plug 3 Is on: %s' % plug3.is_on) if (last_plug1 != plug1.is_on): test = telegram_bot_sendtext('Leaf 1 %s' % plug1.is_on, bot_token, bot_chatID) if (last_plug2 != plug2.is_on): test = telegram_bot_sendtext('Leaf 2 %s' % plug2.is_on, bot_token, bot_chatID) if (last_plug3 != plug3.is_on): test = telegram_bot_sendtext('Other3 %s' % plug3.is_on, bot_token, bot_chatID) last_plug1 = plug1.is_on last_plug2 = plug2.is_on last_plug3 = plug3.is_on
import sys sys.path.append('../') from tplink_smartplug import SmartPlug plug = SmartPlug('192.168.xxx.xxx') print('Name: %s' % plug.name) print('Model: %s' % plug.model) print('Mac: %s' % plug.mac) print('Time: %s' % plug.time) print('') print('Is on: %s' % plug.is_on) print('Nightmode: %s' % (not plug.led)) print('RSSI: %s' % plug.rssi)
def main(panel_ip='192.168.1.161/meters.xml', socket_ip='192.168.1.61', threshold=0.7, interval=30, single_shot=False, max_tries=None, log_file='C:\\Users\\eugen\\plugger\\log.csv', test_plug=False, daily_log_dir='C:\\Users\\eugen\\plugger\\daily_logs\\', timed_log_when='midnight', timed_log_interval=None, days_to_log=28): """ Do iterations over a loop which tests the power output at panel_ip, and manages the state of a plug at socket_ip, according to the threshold power output level. If pass single_shot=True, will do one test and exit, after making max_tries number of attempts to make a successful read and switch Otherwise will operate continuously. Interrupt with ctrl-c To test: pass socket_ip=None and test_plug=True to simulate the plug pass a test xml page on localserver as panel_ip, eg: <line1>x</line1> <OutputPower>99</OutputPower> <line3>x</line3> .. and serve the page the project folder with: $ python -m http.server (can edit and save this file on the fly to simulate panel output) """ # make a daily logging directory if doesn't exist if not os.path.exists(daily_log_dir): os.mkdir(daily_log_dir) # set up logging formatter = logging.Formatter('%(asctime)-15s %(msg)-10s') # formatter.datefmt = ('%d/%m/%y %H:%M:%S') file_path = os.path.join(daily_log_dir, 'log') print('made a folder for logs: {file_path}') if timed_log_interval is None: handler = TimedRotatingFileHandler(file_path, when=timed_log_when, backupCount=days_to_log) else: handler = TimedRotatingFileHandler(file_path, when=timed_log_when, interval=timed_log_interval, backupCount=days_to_log) handler.setLevel(logging.INFO) handler.setFormatter(formatter) log = logging.getLogger() log.setLevel(logging.INFO) log.addHandler(handler) # initial entry log.info('') log.info('*' * 50) log.info('') if single_shot: log.info('[main 0.01] Calling main, mode=single') else: log.info('[main 0.02] Calling main, mode=cont') # create a plug instance if socket_ip is not None: try: plug = SmartPlug(socket_ip) log.info('[main 0.05] initial plug found') except: print('Could not find a plug at', socket_ip) log.info('[main 0.10] initial plug NOT FOUND') return 1 elif test_plug: plug = TestPlug() log.info('[main 0.20] using test plug') else: print('need either a socket_ip or pass test_plug=True') log.info('[main 0.30] exiting as no plug') return 1 interval_by_min = f'{str(interval // 60)} min, {str(interval % 60)} sec' splash_width = 60 info = plug.info print('') print('*' * 12, 'PLUGGER ENERGY MANAGEMENT SYSTEM', '*' * 12) print('') print('version'.ljust(pads[0]), '0.1') print('') print('Plug IP address:'.ljust(pads[0]), socket_ip) print('Plug name'.ljust(pads[0]), info['alias']) print('Plug model'.ljust(pads[0]), info['model']) print('Initial plug state:'.ljust(pads[0]), "ON" if plug.is_on else "OFF") print('') print('Panel IP address:'.ljust(pads[0]), panel_ip) print('Panel power output threshold:'.ljust(pads[0]), threshold) print('') print('Test interval:'.ljust(pads[0]), interval_by_min) print('Testing mode:'.ljust(pads[0]), 'single shot' if single_shot else 'continuous') print('Max attempts (if single shot):'.ljust(pads[0]), max_tries if single_shot else 'n/a') print('') print('*' * 59) print('') time.sleep(1) # initialise the log file if reqd if not os.path.exists(log_file): with open(log_file, 'a', newline="") as f: writer = csv.writer(f, delimiter=",") writer.writerow(CSV_COLUMNS) tries = 0 # main loop while True: log.info('[main 0.40] entering main loop') ts = time.strftime('%d/%m/%y %H:%M:%S') log_list = [ts, 'single' if single_shot else 'cont'] if single_shot: print(ts, f'[{tries + 1}/{max_tries}]'.ljust(7), end=" ") else: print(ts, end=" ") # try to read the panel's current output log.info('[main 0.50] ready to read panel') success, panel_output = get_panel_output(panel_ip=panel_ip, target='OutputPower', log=log) log.info(f'[main 0.60] panel read: success={success}') log.info(f'[main 0.60] panel read: output={panel_output}') if not success: print(f'failed to get panel output, error: {panel_output}') if single_shot: tries += 1 if tries == max_tries: log.info('[main 0.70] reached max tries, exiting') return 0 time.sleep(interval) continue log_list.extend([success, panel_output]) print('panel reading: ' + str(panel_output).ljust(pads[1]), end=' ') try: socket_state = plug.is_on log.info(f'[main 0.80] read plug state: {socket_state}') except: print('cannot find plug') log.info(f'[main 0.90] cannot read plug') if single_shot: tries += 1 if tries == max_tries: log.info('[main 1.00] reached max tries, exiting') return 0 time.sleep(interval) continue log_list.append(socket_state) if panel_output >= threshold: if socket_state: log_list.append('leave on') log.info(f'[main 1.10] output over threshold, leaving on') print('leave on') else: try: plug.turn_on() log.info(f'[main 1.20] *** turned plug ON ***') except: print('cannot turn on plug') log.info(f'[main 1.30] cannot turn on plug') if single_shot: tries += 1 if tries == max_tries: log.info('[main 1.40] reached max tries, exiting') return 0 time.sleep(interval) continue print('** TURN ON **') log_list.append('activate') elif panel_output < threshold: if socket_state: try: plug.turn_off() log.info(f'[main 1.50] *** turned plug OFF ***') except: print('cannot find plug') log.info(f'[main 1.60] cannot turn off plug') if single_shot: tries += 1 if tries == max_tries: log.info('[main 1.70] reached max tries, exiting') return 0 time.sleep(interval) continue print('** TURN OFF **') log_list.append('deactivate') else: log_list.append('leave off') print('leave off') # log a plug reading after any changes try: socket_state = plug.is_on log.info( f'[main 1.80] got plug reading after changes: {socket_state}') except: print('cannot find plug') log.info(f'[main 1.90] cannot read plug after changes') socket_state = 'not found after changes' continue log_list.append(socket_state) # write out log with open(log_file, 'a', newline="") as f: writer = csv.writer(f, delimiter=",") writer.writerow(log_list) # exit loop if only a single shot required if single_shot: return 0 log.info(f'[main 2.00] reached end of main loop') time.sleep(interval)
import sys sys.path.append('../') from tplink_smartplug import SmartPlug plug = SmartPlug('192.168.xxx.xxx') print('Get Daily Statistic for October 2019: %s' % plug.emeter_stats(month=10, year=2019)) print('Get Montly Statistic for 2019: %s' % plug.emeter_stats(year=2019)) print('Get Realtime Current and Voltage Reading: %s' % plug.emeter_stats())
class Hs1xxSmartPlug(): """ Implements direct interface to Kasa HS1xx SmartPlug the class is depended on the SmartPlug API by https://github.com/vrachieru/tplink-smartplug-api """ def __init__(self, id, host, port=9999, timeout=5): """ constructor . str id: the id for the device . str host: host name or ip address on which the device listens . int port: port on which the device listens (default: 9999) . int timeout: socket timeout (default: 5) """ self.id = id self.smartPlug = SmartPlug(host, port, timeout) def get(self, node, dataId, args): """ get data from the smart plug . str node: one of ['system', 'time', 'emeter'] . str dataId: the data ID of the node . dict args: key-value for get emeter returns a tuple (statusCode, dict) where the dict contains response or data items """ sysinfo = {} nodeLowercase = node.lower() if len(nodeLowercase) == 0 or nodeLowercase == 'system': sysinfo = self.smartPlug.command(('system', 'get_sysinfo')) if len(dataId) == 0: sysinfo['ipaddress'] = self.smartPlug.host + ':' + str( self.smartPlug.port) return (200, sysinfo) if dataId.lower() in sysinfo: return (200, {dataId: sysinfo[dataId]}) else: return (400, {KeyResponse: 'InvalidDataId'}) elif nodeLowercase == 'time': if len(dataId) == 0: return (200, { 'time': self.smartPlug.time, 'timezone': self.smartPlug.timezone }) if dataId.lower() == 'time': return (200, {'time': self.smartPlug.time}) if dataId.lower() == 'timezone': return (200, {'timezone': self.smartPlug.timezone}) else: return (400, {KeyResponse: 'InvalidDataId'}) elif nodeLowercase == 'emeter': if 'month' in args and 'year' in args: return (200, { 'daystat': self.smartPlug.command(('emeter', 'get_daystat', { 'month': args['month'], 'year': args['year'] })) }) elif 'year' in args: return (200, { 'monthstat': self.smartPlug.command(('emeter', 'get_monthstat', { 'year': args['year'] })) }) else: return (200, { 'realtime': self.smartPlug.command(('emeter', 'get_realtime')) }) else: return (400, {KeyResponse: 'InvalidNodeId'}) def post(self, node, dataId, args): """ post data or cmd to the smart plug . str node: one of ['system', 'cmd'] . str dataId: the data ID of the node . dict args: key-value to update data property returns a tuple (statusCode, dict) where the dict contains response or data items """ # post is only valid for node in ['system', 'cmd'] # valid post to 'cmd': reboot, reset # valid post to 'system' with dataId: ['deviceId', 'hwId', 'mac', 'alias', 'led_off', 'relay_state', 'latitude_i', 'longitude_i'] statusCode = 200 response = {} nodeLowercase = node.lower() if nodeLowercase == 'system': errorCount = 0 validDataIds = { 'deviceId': 'set_device_id', 'hwId': 'set_hw_id', 'mac': 'set_mac_addr', 'alias': 'set_dev_alias' } #validDataIds2 = {'led_off': 'set_led_off', 'relay_state': 'set_relay_state'} for key, value in args.items(): if key in validDataIds: cmd = validDataIds[key] self.smartPlug.command(('system', cmd, {key: value})) timePrint('%s %s: %s' % (self.id, cmd, str(value))) response[key] = value elif key == 'led_off': self.smartPlug.command(('system', 'set_led_off', { 'off': int(value) })) timePrint('%s set_led_off: %s' % (self.id, str(value))) response[key] = int(value) elif key == 'relay_state': self.smartPlug.command(('system', 'set_relay_state', { 'state': int(value) })) timePrint('%s set_relay_state: %s' % (self.id, str(value))) response[key] = int(value) else: errorCount = +1 if errorCount > 0: if len(response) > 0: statusCode = 206 else: statusCode = 400 response[KeyResponse] = 'NoValidDataId' elif nodeLowercase == 'cmd': delay = 1 if 'delay' in args: delay = args['delay'] if dataId == 'reset': self.smartPlug.command(('system', 'reset', { 'delay': int(delay) })) timePrint('%s reset: %s' % (self.id, str(delay))) elif dataId == 'reboot': self.smartPlug.command(('system', 'reboot', { 'delay': int(delay) })) timePrint('%s reboot: %s' % (self.id, str(delay))) else: statusCode = 400 response[KeyResponse] = 'InvalidCommand' else: statusCode = 400 response[KeyResponse] = 'InvalidNodeId' return (statusCode, response)
from tplink_smartplug import SmartPlug plug = SmartPlug('192.168.1.9') print('Name: %s' % plug.name) print('Model: %s' % plug.model) print('Mac: %s' % plug.mac) print('Time: %s' % plug.time) print('Is on: %s' % plug.is_on) print('Nightmode: %s' % (not plug.led)) print('RSSI: %s' % plug.rssi)
import sys sys.path.append('../') from tplink_smartplug import SmartPlug plug = SmartPlug('192.168.xxx.xxx') if plug.is_on: plug.turn_off() print('Plug turned off') else: plug.turn_on() print('Plug turned on')
def __init__(self, plug_ip): # Init plug self.plug = SmartPlug(plug_ip)
#git clone https://github.com/vrachieru/tplink-smartplug-api.git #pip3 install ./tplink-smartplug-api from tplink_smartplug import SmartPlug plug = SmartPlug('192.168.1.9') if plug.is_on: plug.turn_off() print('Plug turned off') else: plug.turn_on() print('Plug turned on')
def working_session(): global plug1 global plug2 global plug3 global last_plug1 global last_plug2 global last_plug3 global leaf1 global leaf2 locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') #help(SmartPlug) logging.basicConfig(stream=sys.stdout, level=logging.DEBUG) logging.getLogger("pycarwings2").setLevel(logging.ERROR) logging.getLogger("urllib3").setLevel(logging.ERROR) parser = ConfigParser() candidates = ['config.ini', 'my_config.ini'] found = parser.read(candidates) bot_token = parser.get('get-leaf-info', 'bot_token') print("bot_token", bot_token) bot_chatID = parser.get('get-leaf-info', 'bot_chatID') print("bot_chatID", bot_chatID) test = telegram_bot_sendtext("Starting ....", bot_token, bot_chatID) while (1): print("\n\n\n\n\n\nAnother loop\n\n\n\n") found = parser.read(candidates) username = parser.get('get-leaf-info', 'username') password = parser.get('get-leaf-info', 'password') username2 = parser.get('get-leaf-info', 'username2') password2 = parser.get('get-leaf-info', 'password2') region = parser.get('get-leaf-info', 'region') plug1address = parser.get('get-leaf-info', 'plug1address') plug2address = parser.get('get-leaf-info', 'plug2address') plug3address = parser.get('get-leaf-info', 'plug3address') useweekday = ("True" == parser.get('get-leaf-info', 'cfg_use_weekday')) start_minimum_price = int( parser.get('get-leaf-info', 'start_minimum_price')) end_minimum_price = int( parser.get('get-leaf-info', 'end_minimum_price')) start_maximum_price = int( parser.get('get-leaf-info', 'start_maximum_price')) end_maximum_price = int( parser.get('get-leaf-info', 'end_maximum_price')) current_date_and_time = datetime.datetime.now() current_hour = current_date_and_time.hour if (current_hour >= start_minimum_price) and (current_hour < end_minimum_price): print("Time slot: Minimum price") charge_min = True charge_tgt = True charge_max = True charge_min_prio = True charge_tgt_prio = True charge_max_prio = True else: if (current_hour >= start_maximum_price) and (current_hour < end_maximum_price): print("Time slot: Maximum price") charge_min = False charge_tgt = False charge_max = False charge_min_prio = False charge_tgt_prio = False charge_max_prio = False else: print("Time slot: Normal price") charge_min = True charge_tgt = False charge_max = False charge_min_prio = True charge_tgt_prio = True charge_max_prio = False print("Using weekday?", useweekday) if not (useweekday): todaypriority = int(parser.get('Normal', 'todaypriority')) leaf1min = int(parser.get('Normal', 'leaf1min')) leaf2min = int(parser.get('Normal', 'leaf2min')) leaf1tgt = int(parser.get('Normal', 'leaf1tgt')) leaf2tgt = int(parser.get('Normal', 'leaf2tgt')) leaf1max = int(parser.get('Normal', 'leaf1max')) leaf2max = int(parser.get('Normal', 'leaf2max')) else: advancehours = int(parser.get('get-leaf-info', 'advancehours')) hours_added = datetime.timedelta(hours=advancehours) future_date_and_time = current_date_and_time + hours_added weekday = calendar.day_name[future_date_and_time.weekday()] print("Weekday:", weekday) todaypriority = int(parser.get(weekday, 'todaypriority')) leaf1min = int(parser.get(weekday, 'leaf1min')) leaf2min = int(parser.get(weekday, 'leaf2min')) leaf1tgt = int(parser.get(weekday, 'leaf1tgt')) leaf2tgt = int(parser.get(weekday, 'leaf2tgt')) leaf1max = int(parser.get(weekday, 'leaf1max')) leaf2max = int(parser.get(weekday, 'leaf2max')) plug1 = SmartPlug(plug1address) emeterinfo1 = infoEnchufe(plug1, "First car plug") plug2 = SmartPlug(plug2address) emeterinfo2 = infoEnchufe(plug2, "Second car plug") plug3 = SmartPlug(plug3address) emeterinfo3 = infoEnchufe(plug3, "Water warmer plug") if (write_thingsboard): print(config_tb.telemetry_address) print(config_tb.telemetry_address2) unixtime = int(time.mktime(plug1.time.timetuple()) * 1000) unixtime2 = int(time.mktime(plug2.time.timetuple()) * 1000) category = "plug1" pload = { 'ts': unixtime, "values": { category + '_is_on': plug1.is_on, category + '_rssi': plug1.rssi, category + '_current_ma': emeterinfo1['current_ma'], category + '_power_mw': emeterinfo1['power_mw'], } } print(pload) print("========") r = requests.post(config_tb.telemetry_address, json=pload) print(r.status_code) category = "plug2" pload = { 'ts': unixtime, "values": { category + '_is_on': plug2.is_on, category + '_rssi': plug2.rssi, category + '_current_ma': emeterinfo2['current_ma'], category + '_power_mw': emeterinfo2['power_mw'], } } print(pload) print("========") r = requests.post(config_tb.telemetry_address2, json=pload) print(r.status_code) category = "plug3" pload = { 'ts': unixtime, "values": { category + '_is_on': plug3.is_on, category + '_rssi': plug3.rssi, category + '_current_ma': emeterinfo3['current_ma'], category + '_power_mw': emeterinfo3['power_mw'], } } print(pload) print("========") r = requests.post(config_tb.telemetry_address3, json=pload) print(r.status_code) sleepsecs = 10 # Time to wait before polling Nissan servers for update sleepsecs2 = 10 # Time to wait before polling Nissan servers for update # Main program #logging.debug("login = %s, password = %s, region = %s" % (username, password, region)) #logging.debug("login2 = %s, password2 = %s, region = %s" % (username2, password2, region)) print("Prepare Session 1") s = pycarwings2.Session(username, password, region) print("Login...1") leaf1 = s.get_leaf() print("Prepare Session 2") s2 = pycarwings2.Session(username2, password2, region) print("Login...2") leaf2 = s2.get_leaf() # Give the nissan servers a bit of a delay so that we don't get stale data' time.sleep(1) print("********** First Car Last Status ************") print("get_latest_battery_status from servers") try: leaf1_info = leaf1.get_latest_battery_status() #start_date = leaf1_info.answer["BatteryStatusRecords"]["OperationDateAndTime"] #print("start_date=", start_date) print_info(leaf1_info) bat1 = leaf1_info.battery_percent except: print("No hubo suerte con el leaf1") bat1 = 0 print("request an update from the car itself") key = leaf1.request_update() print("********** Second Car Last Status ************") print("get_latest_battery_status from servers") try: leaf2_info = leaf2.get_latest_battery_status() #start_date = leaf2_info.answer["BatteryStatusRecords"]["OperationDateAndTime"] #print("start_date=", start_date) print_info(leaf2_info) bat2 = leaf2_info.battery_percent except: print("No hubo suerte con el leaf2") bat2 = 0 print("request an update from the car itself") key2 = leaf2.request_update() # Give the nissan servers a bit of a delay so that we don't get stale data time.sleep(1) print("***** Waiting for status update *****") print("... First car") update_status = wait_update_battery_status(leaf1, key, sleepsecs, 5, 5) print("... Second car") update_status2 = wait_update_battery_status(leaf2, key2, sleepsecs2, 5, 5) print("********** First Car Current Status************") if (update_status is not None): print("OK: >>>>", update_status.answer['status']) try: latest_leaf_info = leaf1.get_latest_battery_status() #latest_date = latest_leaf_info.answer["BatteryStatusRecords"]["OperationDateAndTime"] #print("latest_date=", latest_date) print_info(latest_leaf_info) print("llegue aqui!") bat1 = latest_leaf_info.battery_percent conn1 = latest_leaf_info.is_connected print("llegue aqui B!") print(latest_leaf_info.answer["BatteryStatusRecords"] ["OperationDateAndTime"]) print("llegue aqui B2!") locale.setlocale(locale.LC_ALL, 'es_ES.UTF-8') print(latest_leaf_info.answer["BatteryStatusRecords"] ["OperationDateAndTime"]) date_time_obj = datetime.datetime.strptime( latest_leaf_info.answer["BatteryStatusRecords"] ["OperationDateAndTime"], '%d-%b-%Y %H:%M') print("llegue aqui C!") unixtime = int( (time.mktime(date_time_obj.timetuple()) - 3600) * 1000) print("llegue aqui D!") remainingtime = latest_leaf_info.time_to_full_l2.total_seconds( ) print("pero si fue bien!") except: print("No hay informacion actualizada para leaf1") conn1 = True try: print("Vamos con la subida de datos") category = "car1" pload = { 'ts': unixtime, "values": { category + '_bat': bat1, category + '_conn': conn1, category + '_time2full': remainingtime } } print(pload) print("========") r = requests.post(config_tb.telemetry_address, json=pload) print(r.status_code) except: print("No se pudo subir la información de leaf1 al panel") else: print("ERROR: >>>> status could not be retrieved") conn1 = True print("********** Second Car Current Status************") if (update_status2 is not None): print("OK: >>>>", update_status2.answer['status']) try: latest_leaf_info2 = leaf2.get_latest_battery_status() #latest_date2 = latest_leaf_info2.answer["BatteryStatusRecords"]["OperationDateAndTime"] #print("latest_date2=", latest_date2) print_info(latest_leaf_info2) print("llegue aqui 2") bat2 = latest_leaf_info2.battery_percent conn2 = latest_leaf_info2.is_connected date_time_obj = datetime.datetime.strptime( latest_leaf_info2.answer["BatteryStatusRecords"] ["OperationDateAndTime"], '%d-%b-%Y %H:%M') unixtime = int( (time.mktime(date_time_obj.timetuple()) - 3600) * 1000) remainingtime = latest_leaf_info2.time_to_full_l2.total_seconds( ) print("incluso acabe") except: print("No hay informacion actualizada para leaf2") conn2 = True try: print("intentamos subir al panel del coche 2") category = "car2" pload = { 'ts': unixtime, "values": { category + '_bat': bat2, category + '_conn': conn2, category + '_time2full': remainingtime } } print(pload) print("========") r = requests.post(config_tb.telemetry_address2, json=pload) print(r.status_code) print("acabe con el panel2") except: print("No se pudo subir la información de leaf2 al panel") else: print("ERROR: >>>> status could not be retrieved") conn2 = True locale.setlocale(locale.LC_ALL, 'en_US.UTF-8') if (todaypriority == 1): charge_leaf1_min = charge_min_prio charge_leaf2_min = charge_min charge_leaf1_tgt = charge_tgt_prio charge_leaf2_tgt = charge_tgt charge_leaf1_max = charge_max_prio charge_leaf2_max = charge_max else: charge_leaf2_min = charge_min_prio charge_leaf1_min = charge_min charge_leaf2_tgt = charge_tgt_prio charge_leaf1_tgt = charge_tgt charge_leaf2_max = charge_max_prio charge_leaf1_max = charge_max charge_leaf1 = 0 charge_leaf2 = 0 print("charge_leaf1_min", charge_leaf1_min) print("charge_leaf2_min", charge_leaf2_min) if (bat1 < leaf1min): print("leaf1 < min") if charge_leaf1_min: charge_leaf1 = 10 else: if (bat1 < leaf1tgt): print("leaf1 < tgt") if charge_leaf1_tgt: charge_leaf1 = 5 else: if (bat1 < leaf1max): print("leaf1 < max") if charge_leaf1_max: charge_leaf1 = 1 else: print("leaf1 >= max") if (bat2 < leaf2min): print("leaf2 < min") if charge_leaf2_min: charge_leaf2 = 10 else: if (bat2 < leaf2tgt): print("leaf2 < tgt") if charge_leaf2_tgt: charge_leaf2 = 5 else: if (bat2 < leaf2max): print("leaf2 < max") if charge_leaf2_max: charge_leaf2 = 1 else: print("leaf2 >= max") if todaypriority == 1: if (charge_leaf1 > 0): charge_leaf1 += 1 else: if (charge_leaf2 > 0): charge_leaf2 += 1 print("charge points 1", charge_leaf1) print("charge points 2", charge_leaf2) if not (conn1): charge_leaf1 = 0 print("charge points 1", charge_leaf1) print("charge points 2", charge_leaf2) if charge_leaf1 > charge_leaf2: turn_1_on() else: if charge_leaf1 < charge_leaf2: car2present = turn_2_on() if not car2present: print("Let's proceed to the next in the queue") if (charge_leaf1 > 0): turn_1_on() else: turn_off() else: turn_off() print('Plug 1 Is on: %s' % plug1.is_on) print('Plug 2 Is on: %s' % plug2.is_on) print('Plug 3 Is on: %s' % plug3.is_on) if (last_plug1 != plug1.is_on): test = telegram_bot_sendtext('Leaf 1 %s' % plug1.is_on, bot_token, bot_chatID) if (last_plug2 != plug2.is_on): test = telegram_bot_sendtext('Leaf 2 %s' % plug2.is_on, bot_token, bot_chatID) if (last_plug3 != plug3.is_on): test = telegram_bot_sendtext('Other3 %s' % plug3.is_on, bot_token, bot_chatID) last_plug1 = plug1.is_on last_plug2 = plug2.is_on last_plug3 = plug3.is_on print('Sleeping for 5 minutes') time.sleep(300)