OpenLEADR/openleadr-python

on_event handler encountered an error

chandank21 opened this issue · 2 comments

except Exception as err:
logger.error("Your on_event handler encountered an error. Will Opt Out of the event. "
f"The error was {err.class.name}: {str(err)}")
results = ['optOut'] * len(events)

Your on_event handler encountered an error. Will Opt Out of the event. The error was TypeError: string indices must be integers
Your on_event handler encountered an error. Will Opt Out of the event. The error was KeyError: '8f2594c0-47bc-49df-9d60-74193fd72997'

I cannot help you without some more information. Can you show me your VEN and VTN code please?

VTN CODE..

async def on_create_party_registration(registration_info):
    """
    Inspect the registration info and return a ven_id and registration_id.
    """
    """Inspect the registration info and return registration_id and ven_id"""
    ven_list = ['SGCC_ven1']
    if registration_info['ven_name'] in ven_list:
        ven_id = registration_info['ven_name'] + "@97"
        registration_id = "reg_" + ven_id
        return ven_id, registration_id
    else:
        return False

async def send_events(server):
    await asyncio.sleep(120)
    global EVENT_DICT
    EVENT_DICT = await make_events.create_test_event()
    event_date = EVENT_DICT['DATE']
    if isinstance(event_date,(date)):
        pass
    elif isinstance(event_date,(datetime)):
        event_date = event_date.date()
    else:
        print('convert event date in datetime or date ')

    if isinstance(event_date,(date)):
        if EVENT_DICT and event_date == date.today():
            # EVENT_DICT['TEST_EVENT'] is list.
            for event in EVENT_DICT['TEST_EVENT']:
                server.add_event(ven_id=event['ven_id'],
                                signal_name=event['signal_name'],
                                signal_type=event['signal_type'],
                                intervals=event['intervals'],
                                target=event['target'],
                                callback=event_response_callback)
                await asyncio.sleep(60)
server = OpenADRServer(vtn_id='SG_CENTER_vtn',http_port=8080,http_host='127.0.0.1')
server.add_handler('on_create_party_registration', on_create_party_registration)
loop = asyncio.get_event_loop()
loop.create_task(server.run())
loop.create_task(send_events(server))
loop.run_forever()

async def create_test_event():
    await read_set_load_scheduling()
    global loads
    start = datetime.combine(date.today(), time(hour=0))
    event_time = [start+timedelta(hours=i) for i in range(24)]
    test_event=[]
    for load in loads:
        event_dict={'ven_id':load['ven_id'],
        'signal_type':'level',
        'signal_name':'simple',
        'intervals':[{'dtstart':event_time[i].replace(tzinfo=zoneinfo.ZoneInfo("Asia/Kolkata")),
                      'duration':timedelta(hours=1),
                      'signal_payload':int(load['scheduling'][i])} for i in range(24)],
        'target':{'resource_id': load['name']}
        }
        test_event.append(event_dict)
    EVENT_DICT={'DATE':date.today(),
                'TEST_EVENT':test_event}

    return EVENT_DICT

VEN CODE....

smart_plug_status = {"AC": None,
                     "EV": None,
                     "WashingMachine": None}

async def collect_report_value(device,measurement):
    try:
        value = None
        with open(r'meter_data.json', 'r', ) as json_file:
            data = json.load(json_file)
            value = data[device][measurement]
        if value is None:
            return 0
        return value
    except Exception as err:
        print(err)
    return -1

async def device_measure(device, measurement):
    pass

async def change_status(payload, device):
             pass
async def control_TB_load(demand_limit,duration,device):
             pass
 
async def control_smart_plug(payload,device,delay,duration):
    if delay>0:
        await asyncio.sleep(delay)

    await change_status(payload,device)
    if device in ['AC','Fridge'] and payload > 0:
        # paylaod for temperature based laods are power cossumptiuon limit
        await control_TB_load(payload, duration, device)

async def handle_event(event):
    print(event)
    signal = event['event_signals'][0]
    devices = event['targets'][0]

    intervals = signal['intervals']
    signal_name = signal['signal_name']
    signal_type = signal['signal_type']
    Even_disciption = {'DATE': date.today(),
                       'event_signals': signal,
                       'event_targets': devices}

    def json_serial(obj):
        if isinstance(obj, (datetime, date)):
            return obj.isoformat()
        if isinstance(obj, (timedelta)):
            return obj.seconds
        raise TypeError("Type %s not serializable" % type(obj))
    for device in devices:
        load_name = device['resource_id']
        print(load_name)
        path = f"{load_name}"+'_scheduling.json'
        print(path)
        try:
            with open(path, 'w') as fp:
                json.dump(Even_disciption, fp, indent=6, default=json_serial)
        except Exception as err:
            print(err)
    loop = asyncio.get_event_loop()
    if signal_name == 'simple' and signal_type == 'level':
        for interval in intervals:
            now = datetime.now(timezone.utc)
            start = interval['dtstart']
            delay = (start - now).total_seconds()
            value = interval['signal_payload']
            if delay > 0:
                for device in devices:
                loop.create_task(control_smart_plug(payload=value,device=device['resource_id'],delay=delay,duration=interval['duration']))
    return 'optIn'

client = OpenADRClient(ven_name='SGCC_ven1',
                       vtn_url='http://127.0.0.1:8080/OpenADR2/Simple/2.0b')
client.add_report(callback=partial(collect_report_value,'node8','power'),
                  resource_id='AC',
                  measurement='RealPower',
                  report_duration= timedelta(minutes=1),
                  power_ac=True, power_hertz=50, power_voltage=230,
                  unit='W',
                  sampling_rate=timedelta(minutes=1))
client.add_handler('on_event', handle_event)
loop = asyncio.get_event_loop()
loop.create_task(client.run())
loop.run_forever()