ocpp icon indicating copy to clipboard operation
ocpp copied to clipboard

Connecting ArduinoOCPP - MeteringValue issue with string

Open tollanes opened this issue 5 years ago • 3 comments

Hi, I'm testing out this library with an ArduinoOCPP device and is trying to setup metering, but I am running into some issues. It happens when I close the transaction. From the error it looks like the json does not like that the metervalue is an integer/float. Is this something that needs fixing on this server or the ArduinoOCPP client?

Code:

import asyncio
import logging
from datetime import datetime

try:
    import websockets
except ModuleNotFoundError:
    print("This example relies on the 'websockets' package.")
    print("Please install it by running: ")
    print()
    print(" $ pip install websockets")
    import sys
    sys.exit(1)

from ocpp.routing import on
from ocpp.v16 import ChargePoint as cp
from ocpp.v16.enums import Action, RegistrationStatus
from ocpp.v16 import call_result

logging.basicConfig(level=logging.DEBUG)


class ChargePoint(cp):
    @on(Action.BootNotification)
    def on_boot_notification(self, charge_point_vendor: str, charge_point_model: str, **kwargs):
        return call_result.BootNotificationPayload(
            current_time=datetime.utcnow().isoformat(),
            interval=10,
            status=RegistrationStatus.accepted
        )

    @on(Action.Authorize)
    def on_authorize(self, id_tag: str):
        return call_result.AuthorizePayload(
            id_tag_info={"status": 'Accepted'},
        )

    @on(Action.StatusNotification)
    def on_status_notification(self, connector_id: str, error_code: str, status: str, timestamp: str):        
        return call_result.StatusNotificationPayload()

    @on(Action.MeterValues)
    def on_meter_value(self):
        return call_result.MeterValuesPayload()

    @on(Action.StartTransaction)
    def on_start_transaction(self, connector_id, id_tag, timestamp, meter_start):
        return call_result.StartTransactionPayload(
            id_tag_info={
                "status": 'Accepted'
            },
            transaction_id=int(1)
        )

    @on(Action.StopTransaction)
    def on_stop_transaction(self, transaction_id, timestamp, meter_stop):
        return call_result.StopTransactionPayload()


async def on_connect(websocket, path):
    """ For every new charge point that connects, create a ChargePoint
    instance and start listening for messages.
    """
    try:
        requested_protocols = websocket.request_headers[
            'Sec-WebSocket-Protocol']
    except KeyError:
        logging.error(
            "Client hasn't requested any Subprotocol. Closing Connection"
        )
        return await websocket.close()
    if websocket.subprotocol:
        logging.info("Protocols Matched: %s", websocket.subprotocol)
    else:
        # In the websockets lib if no subprotocols are supported by the
        # client and the server, it proceeds without a subprotocol,
        # so we have to manually close the connection.
        logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'
                        ' but client supports  %s | Closing connection',
                        websocket.available_subprotocols,
                        requested_protocols)
        return await websocket.close()

    charge_point_id = path.strip('/')
    cp = ChargePoint(charge_point_id, websocket)

    await cp.start()


async def main():
    server = await websockets.serve(
        on_connect,
        '0.0.0.0',
        8834,
        subprotocols=['ocpp1.6']
    )

    logging.info("Server Started listening to new connections...")
    await server.wait_closed()


if __name__ == '__main__':
    try:
        # asyncio.run() is used when running this example with Python 3.7 and
        # higher.
        asyncio.run(main())
    except AttributeError:
        # For Python 3.6 a bit more code is required to run the main() task on
        # an event loop.
        loop = asyncio.get_event_loop()
        loop.run_until_complete(main())
        loop.close()

Log:

ERROR:websockets.server:Error in connection handler
Traceback (most recent call last):
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\ocpp\messages.py", line 240, in validate_payload
    validator.validate(message.payload)
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\jsonschema\validators.py", line 353, in validate
    raise error
jsonschema.exceptions.ValidationError: 22 is not of type 'string'

Failed validating 'type' in schema['properties']['meterValue']['items']['properties']['sampledValue']['items']['properties']['value']:
    {'type': 'string'}

On instance['meterValue'][0]['sampledValue'][0]['value']:
    22

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\websockets\legacy\server.py", line 293, in handler
    await self.ws_handler(self, path)
  File "C:\Users\Andreas\Documents\Programming\OCPP-Python\server.py", line 87, in on_connect
    await cp.start()
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\ocpp\charge_point.py", line 126, in start
    await self.route_message(message)
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\ocpp\charge_point.py", line 144, in route_message
    await self._handle_call(msg)
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\ocpp\charge_point.py", line 168, in _handle_call
    validate_payload(msg, self._ocpp_version)
  File "C:\Users\Andreas\AppData\Local\Programs\Python\Python39\lib\site-packages\ocpp\messages.py", line 242, in validate_payload
    raise ValidationError(f"Payload '{message.payload} for action "
ocpp.exceptions.ValidationError: Payload '{'connectorId': 1, 'meterValue': [{'timestamp': '2021-08-26T07:16:53.000Z', 'sampledValue': [{'value': 22, 'measurand': 'Power.Active.Import', 'unit': 'W'}]}]} for action 'MeterValues' is not valid: 22 is not of type 'string'

Failed validating 'type' in schema['properties']['meterValue']['items']['properties']['sampledValue']['items']['properties']['value']:
    {'type': 'string'}

On instance['meterValue'][0]['sampledValue'][0]['value']:
    22
DEBUG:websockets.protocol:server ! failing OPEN WebSocket connection with code 1011
DEBUG:websockets.protocol:server - state = CLOSING
DEBUG:websockets.protocol:server > Frame(fin=True, opcode=<Opcode.CLOSE: 8>, data=b'\x03\xf3', rsv1=False, rsv2=False, rsv3=False)
DEBUG:websockets.protocol:server x half-closing TCP connection
DEBUG:websockets.protocol:server - event = connection_lost(None)
DEBUG:websockets.protocol:server - state = CLOSED
DEBUG:websockets.protocol:server x code = 1006, reason = [no reason]
DEBUG:websockets.protocol:server - state = CONNECTING
DEBUG:websockets.protocol:server - event = connection_made(<_ProactorSocketTransport fd=332>)
DEBUG:websockets.protocol:server - event = data_received(<255 bytes>)
DEBUG:websockets.server:server < GET 10.0.0.34/ocpp/ HTTP/1.1
DEBUG:websockets.server:server < Headers([('Host', '10.0.0.34:8834'), ('Connection', 'Upgrade'), ('Upgrade', 'websocket'), ('Sec-WebSocket-Version', '13'), ('Sec-WebSocket-Key', 'Rq68r58+KtJL9Upwn+u3fg=='), ('Sec-WebSocket-Protocol', 'ocpp1.6'), ('Origin', 'file://'), ('User-Agent', 'arduino-WebSocket-Client')])
DEBUG:websockets.server:server > HTTP/1.1 101 Switching Protocols
DEBUG:websockets.server:server > Headers([('Upgrade', 'websocket'), ('Connection', 'Upgrade'), ('Sec-WebSocket-Accept', 'ey7vBmaO0+pVnH2bUXGfSy2j4A8='), ('Sec-WebSocket-Protocol', 'ocpp1.6'), ('Date', 'Thu, 26 Aug 2021 07:17:06 GMT'), ('Server', 'Python/3.9 websockets/9.1')])
DEBUG:websockets.protocol:server - state = OPEN
INFO:root:Protocols Matched: ocpp1.6
DEBUG:websockets.protocol:server - event = data_received(<186 bytes>)

tollanes avatar Aug 26 '21 07:08 tollanes

jsonschema.exceptions.ValidationError: 22 is not of type 'string'

The chargepoint is sending json which does not follow the JSON schema. You can ignore this by adding skip_schema_validation=False in the on handler, but the bug lies in the chargepoint...

lucvht avatar Aug 26 '21 14:08 lucvht

yeah, this is about right. Can you try out @fanzypantz?

laysauchoa avatar Aug 29 '21 07:08 laysauchoa

Yeah, that does "solve it". Should look at the ArduionoOCPP part then to fix this.

tollanes avatar Aug 30 '21 12:08 tollanes