ocpp


Nameocpp JSON
Version 1.0.0 PyPI version JSON
download
home_pagehttps://github.com/mobilityhouse/ocpp
SummaryPython package implementing the JSON version of the Open Charge Point Protocol (OCPP).
upload_time2024-05-14 14:34:22
maintainerNone
docs_urlNone
authorAndré Duarte
requires_python<4.0,>=3.8
licenseMIT
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI No Travis.
coveralls test coverage No coveralls.
            .. image:: https://github.com/mobilityhouse/ocpp/actions/workflows/pull-request.yml/badge.svg?style=svg
   :target: https://github.com/mobilityhouse/ocpp/actions/workflows/pull-request.yml

.. image:: https://img.shields.io/pypi/pyversions/ocpp.svg
   :target: https://pypi.org/project/ocpp/

.. image:: https://img.shields.io/readthedocs/ocpp.svg
   :target: https://ocpp.readthedocs.io/en/latest/

OCPP
----

Python package implementing the JSON version of the Open Charge Point Protocol
(OCPP). Currently OCPP 1.6 (errata v4), OCPP 2.0.1 (Edition 2 FINAL, 2022-12-15)
are supported.

You can find the documentation on `rtd`_.

The purpose of this library is to provide the building blocks to construct a
charging station/charge point and/or charging station management system
(CSMS)/central system. The library does not provide a completed solution, as any
implementation is specific for its intended use. The documents in this library
should be inspected, as these documents provided guidance on how best to
build a complete solution.

Note: "OCPP 2.0.1 contains fixes for all the known issues, to date, not only
the fixes to the messages. This version replaces OCPP 2.0. OCA advises
implementers of OCPP to no longer implement OCPP 2.0 and only use version
2.0.1 going forward."

Installation
------------

You can either the project install from Pypi:

.. code-block:: bash

   $ pip install ocpp

Or clone the project and install it manually using:

.. code-block:: bash

   $ pip install .

Quick start
-----------

Below you can find examples on how to create a simple OCPP 1.6 or 2.0.1 Central
System/CSMS as well as the respective OCPP 1.6 or 2.0.1
Charging Station/Charge Point.

.. note::

   To run these examples the dependency websockets_ is required! Install it by running:

   .. code-block:: bash

      $ pip install websockets

Charging Station Management System (CSMS) / Central System
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

The code snippet below creates a simple OCPP 2.0.1 CSMS which
is able to handle BootNotification calls. You can find a detailed explanation of the
code in the `Central System documentation`_.


.. code-block:: python

    import asyncio
    import logging
    import websockets
    from datetime import datetime

    from ocpp.routing import on
    from ocpp.v201 import ChargePoint as cp
    from ocpp.v201 import call_result
    from ocpp.v201.enums import RegistrationStatusType

    logging.basicConfig(level=logging.INFO)


    class ChargePoint(cp):
        @on('BootNotification')
        async def on_boot_notification(self, charging_station, reason, **kwargs):
            return call_result.BootNotificationPayload(
                current_time=datetime.utcnow().isoformat(),
                interval=10,
                status=RegistrationStatusType.accepted
            )


    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.info("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',
            9000,
            subprotocols=['ocpp2.0.1']
        )
        logging.info("WebSocket Server Started")
        await server.wait_closed()

    if __name__ == '__main__':
        asyncio.run(main())

Charging Station / Charge point
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

.. code-block:: python

    import asyncio

    from ocpp.v201.enums import RegistrationStatusType
    import logging
    import websockets

    from ocpp.v201 import call
    from ocpp.v201 import ChargePoint as cp

    logging.basicConfig(level=logging.INFO)


    class ChargePoint(cp):

        async def send_boot_notification(self):
            request = call.BootNotificationPayload(
                charging_station={
                    'model': 'Wallbox XYZ',
                    'vendor_name': 'anewone'
                },
                reason="PowerUp"
            )
            response = await self.call(request)

            if response.status == RegistrationStatusType.accepted:
                print("Connected to central system.")


    async def main():
        async with websockets.connect(
                'ws://localhost:9000/CP_1',
                subprotocols=['ocpp2.0.1']
        ) as ws:
            cp = ChargePoint('CP_1', ws)

            await asyncio.gather(cp.start(), cp.send_boot_notification())


    if __name__ == '__main__':
        asyncio.run(main())

Debugging
---------

Python's default log level is `logging.WARNING`. As result most of the logs
generated by this package are discarded. To see the log output of this package
lower the log level to `logging.DEBUG`.

.. code-block:: python

  import logging
  logging.basicConfig(level=logging.DEBUG)

However, this approach defines the log level for the complete logging system.
In other words: the log level of all dependencies is set to `logging.DEBUG`.

To lower the logs for this package only use the following code:

.. code-block:: python

  import logging
  logging.getLogger('ocpp').setLevel(level=logging.DEBUG)
  logging.getLogger('ocpp').addHandler(logging.StreamHandler())

License
-------

Except from the documents in `docs/v16` and `docs/v201` everything is licensed under MIT_.
© `The Mobility House`_

The documents in `docs/v16` and `docs/v201` are licensed under Creative Commons
Attribution-NoDerivatives 4.0 International Public License.

.. _Central System documentation: https://ocpp.readthedocs.io/en/latest/central_system.html
.. _MIT: https://github.com/mobilityhouse/ocpp/blob/master/LICENSE
.. _rtd: https://ocpp.readthedocs.io/en/latest/index.html
.. _The Mobility House: https://www.mobilityhouse.com/int_en/
.. _websockets: https://pypi.org/project/websockets/

            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/mobilityhouse/ocpp",
    "name": "ocpp",
    "maintainer": null,
    "docs_url": null,
    "requires_python": "<4.0,>=3.8",
    "maintainer_email": null,
    "keywords": null,
    "author": "Andr\u00e9 Duarte",
    "author_email": "andre15x@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/61/35/25374c1e67510a7e936d94e60070db53617c335c6c5ce97d8069b327b389/ocpp-1.0.0.tar.gz",
    "platform": null,
    "description": ".. image:: https://github.com/mobilityhouse/ocpp/actions/workflows/pull-request.yml/badge.svg?style=svg\n   :target: https://github.com/mobilityhouse/ocpp/actions/workflows/pull-request.yml\n\n.. image:: https://img.shields.io/pypi/pyversions/ocpp.svg\n   :target: https://pypi.org/project/ocpp/\n\n.. image:: https://img.shields.io/readthedocs/ocpp.svg\n   :target: https://ocpp.readthedocs.io/en/latest/\n\nOCPP\n----\n\nPython package implementing the JSON version of the Open Charge Point Protocol\n(OCPP). Currently OCPP 1.6 (errata v4), OCPP 2.0.1 (Edition 2 FINAL, 2022-12-15)\nare supported.\n\nYou can find the documentation on `rtd`_.\n\nThe purpose of this library is to provide the building blocks to construct a\ncharging station/charge point and/or charging station management system\n(CSMS)/central system. The library does not provide a completed solution, as any\nimplementation is specific for its intended use. The documents in this library\nshould be inspected, as these documents provided guidance on how best to\nbuild a complete solution.\n\nNote: \"OCPP 2.0.1 contains fixes for all the known issues, to date, not only\nthe fixes to the messages. This version replaces OCPP 2.0. OCA advises\nimplementers of OCPP to no longer implement OCPP 2.0 and only use version\n2.0.1 going forward.\"\n\nInstallation\n------------\n\nYou can either the project install from Pypi:\n\n.. code-block:: bash\n\n   $ pip install ocpp\n\nOr clone the project and install it manually using:\n\n.. code-block:: bash\n\n   $ pip install .\n\nQuick start\n-----------\n\nBelow you can find examples on how to create a simple OCPP 1.6 or 2.0.1 Central\nSystem/CSMS as well as the respective OCPP 1.6 or 2.0.1\nCharging Station/Charge Point.\n\n.. note::\n\n   To run these examples the dependency websockets_ is required! Install it by running:\n\n   .. code-block:: bash\n\n      $ pip install websockets\n\nCharging Station Management System (CSMS) / Central System\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nThe code snippet below creates a simple OCPP 2.0.1 CSMS which\nis able to handle BootNotification calls. You can find a detailed explanation of the\ncode in the `Central System documentation`_.\n\n\n.. code-block:: python\n\n    import asyncio\n    import logging\n    import websockets\n    from datetime import datetime\n\n    from ocpp.routing import on\n    from ocpp.v201 import ChargePoint as cp\n    from ocpp.v201 import call_result\n    from ocpp.v201.enums import RegistrationStatusType\n\n    logging.basicConfig(level=logging.INFO)\n\n\n    class ChargePoint(cp):\n        @on('BootNotification')\n        async def on_boot_notification(self, charging_station, reason, **kwargs):\n            return call_result.BootNotificationPayload(\n                current_time=datetime.utcnow().isoformat(),\n                interval=10,\n                status=RegistrationStatusType.accepted\n            )\n\n\n    async def on_connect(websocket, path):\n        \"\"\" For every new charge point that connects, create a ChargePoint\n        instance and start listening for messages.\n        \"\"\"\n        try:\n            requested_protocols = websocket.request_headers[\n                'Sec-WebSocket-Protocol']\n        except KeyError:\n            logging.info(\"Client hasn't requested any Subprotocol. \"\n                     \"Closing Connection\")\n            return await websocket.close()\n\n        if websocket.subprotocol:\n            logging.info(\"Protocols Matched: %s\", websocket.subprotocol)\n        else:\n            # In the websockets lib if no subprotocols are supported by the\n            # client and the server, it proceeds without a subprotocol,\n            # so we have to manually close the connection.\n            logging.warning('Protocols Mismatched | Expected Subprotocols: %s,'\n                            ' but client supports  %s | Closing connection',\n                            websocket.available_subprotocols,\n                            requested_protocols)\n            return await websocket.close()\n\n        charge_point_id = path.strip('/')\n        cp = ChargePoint(charge_point_id, websocket)\n\n        await cp.start()\n\n\n    async def main():\n        server = await websockets.serve(\n            on_connect,\n            '0.0.0.0',\n            9000,\n            subprotocols=['ocpp2.0.1']\n        )\n        logging.info(\"WebSocket Server Started\")\n        await server.wait_closed()\n\n    if __name__ == '__main__':\n        asyncio.run(main())\n\nCharging Station / Charge point\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\n.. code-block:: python\n\n    import asyncio\n\n    from ocpp.v201.enums import RegistrationStatusType\n    import logging\n    import websockets\n\n    from ocpp.v201 import call\n    from ocpp.v201 import ChargePoint as cp\n\n    logging.basicConfig(level=logging.INFO)\n\n\n    class ChargePoint(cp):\n\n        async def send_boot_notification(self):\n            request = call.BootNotificationPayload(\n                charging_station={\n                    'model': 'Wallbox XYZ',\n                    'vendor_name': 'anewone'\n                },\n                reason=\"PowerUp\"\n            )\n            response = await self.call(request)\n\n            if response.status == RegistrationStatusType.accepted:\n                print(\"Connected to central system.\")\n\n\n    async def main():\n        async with websockets.connect(\n                'ws://localhost:9000/CP_1',\n                subprotocols=['ocpp2.0.1']\n        ) as ws:\n            cp = ChargePoint('CP_1', ws)\n\n            await asyncio.gather(cp.start(), cp.send_boot_notification())\n\n\n    if __name__ == '__main__':\n        asyncio.run(main())\n\nDebugging\n---------\n\nPython's default log level is `logging.WARNING`. As result most of the logs\ngenerated by this package are discarded. To see the log output of this package\nlower the log level to `logging.DEBUG`.\n\n.. code-block:: python\n\n  import logging\n  logging.basicConfig(level=logging.DEBUG)\n\nHowever, this approach defines the log level for the complete logging system.\nIn other words: the log level of all dependencies is set to `logging.DEBUG`.\n\nTo lower the logs for this package only use the following code:\n\n.. code-block:: python\n\n  import logging\n  logging.getLogger('ocpp').setLevel(level=logging.DEBUG)\n  logging.getLogger('ocpp').addHandler(logging.StreamHandler())\n\nLicense\n-------\n\nExcept from the documents in `docs/v16` and `docs/v201` everything is licensed under MIT_.\n\u00a9 `The Mobility House`_\n\nThe documents in `docs/v16` and `docs/v201` are licensed under Creative Commons\nAttribution-NoDerivatives 4.0 International Public License.\n\n.. _Central System documentation: https://ocpp.readthedocs.io/en/latest/central_system.html\n.. _MIT: https://github.com/mobilityhouse/ocpp/blob/master/LICENSE\n.. _rtd: https://ocpp.readthedocs.io/en/latest/index.html\n.. _The Mobility House: https://www.mobilityhouse.com/int_en/\n.. _websockets: https://pypi.org/project/websockets/\n",
    "bugtrack_url": null,
    "license": "MIT",
    "summary": "Python package implementing the JSON version of the Open Charge Point Protocol (OCPP).",
    "version": "1.0.0",
    "project_urls": {
        "Documentation": "https://ocpp.readthedocs.io/en/latest/",
        "Homepage": "https://github.com/mobilityhouse/ocpp",
        "Repository": "https://github.com/mobilityhouse/ocpp"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "a5665e427455af31dff76929f3f7117cb21a957b19eb6133eb0a50f7a3d1bb78",
                "md5": "61145a119191af54a3e5474634210b9b",
                "sha256": "2f1973337f3c37bdd67fa2fe6b614be53b35f839dddefdc7b94e3469eba0f3e0"
            },
            "downloads": -1,
            "filename": "ocpp-1.0.0-py3-none-any.whl",
            "has_sig": false,
            "md5_digest": "61145a119191af54a3e5474634210b9b",
            "packagetype": "bdist_wheel",
            "python_version": "py3",
            "requires_python": "<4.0,>=3.8",
            "size": 230519,
            "upload_time": "2024-05-14T14:34:19",
            "upload_time_iso_8601": "2024-05-14T14:34:19.209088Z",
            "url": "https://files.pythonhosted.org/packages/a5/66/5e427455af31dff76929f3f7117cb21a957b19eb6133eb0a50f7a3d1bb78/ocpp-1.0.0-py3-none-any.whl",
            "yanked": false,
            "yanked_reason": null
        },
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "613525374c1e67510a7e936d94e60070db53617c335c6c5ce97d8069b327b389",
                "md5": "1d8d0e398884e5d0a9574cbfdbaf7d22",
                "sha256": "d39b9e152d5e4d378f82dd26653ced3aa66038fead496248ebb71aff1c006c70"
            },
            "downloads": -1,
            "filename": "ocpp-1.0.0.tar.gz",
            "has_sig": false,
            "md5_digest": "1d8d0e398884e5d0a9574cbfdbaf7d22",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": "<4.0,>=3.8",
            "size": 106243,
            "upload_time": "2024-05-14T14:34:22",
            "upload_time_iso_8601": "2024-05-14T14:34:22.627468Z",
            "url": "https://files.pythonhosted.org/packages/61/35/25374c1e67510a7e936d94e60070db53617c335c6c5ce97d8069b327b389/ocpp-1.0.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2024-05-14 14:34:22",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "mobilityhouse",
    "github_project": "ocpp",
    "travis_ci": false,
    "coveralls": false,
    "github_actions": true,
    "lcname": "ocpp"
}
        
Elapsed time: 0.27873s