Project Icon

ocpp

Python实现开放充电桩通信协议库 支持OCPP 1.6和2.0.1

这是一个基于Python的开放充电桩协议(OCPP)JSON版本实现库,支持OCPP 1.6和2.0.1版本。该库提供构建充电桩和充电站管理系统的基础组件,包含创建OCPP中央系统和充电桩的示例代码。项目使用websockets进行通信,提供详细文档和调试指南,为开发者提供灵活可定制的OCPP实现方案。

.. 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/
项目侧边栏1项目侧边栏2
推荐项目
Project Cover

豆包MarsCode

豆包 MarsCode 是一款革命性的编程助手,通过AI技术提供代码补全、单测生成、代码解释和智能问答等功能,支持100+编程语言,与主流编辑器无缝集成,显著提升开发效率和代码质量。

Project Cover

AI写歌

Suno AI是一个革命性的AI音乐创作平台,能在短短30秒内帮助用户创作出一首完整的歌曲。无论是寻找创作灵感还是需要快速制作音乐,Suno AI都是音乐爱好者和专业人士的理想选择。

Project Cover

白日梦AI

白日梦AI提供专注于AI视频生成的多样化功能,包括文生视频、动态画面和形象生成等,帮助用户快速上手,创造专业级内容。

Project Cover

有言AI

有言平台提供一站式AIGC视频创作解决方案,通过智能技术简化视频制作流程。无论是企业宣传还是个人分享,有言都能帮助用户快速、轻松地制作出专业级别的视频内容。

Project Cover

Kimi

Kimi AI助手提供多语言对话支持,能够阅读和理解用户上传的文件内容,解析网页信息,并结合搜索结果为用户提供详尽的答案。无论是日常咨询还是专业问题,Kimi都能以友好、专业的方式提供帮助。

Project Cover

讯飞绘镜

讯飞绘镜是一个支持从创意到完整视频创作的智能平台,用户可以快速生成视频素材并创作独特的音乐视频和故事。平台提供多样化的主题和精选作品,帮助用户探索创意灵感。

Project Cover

讯飞文书

讯飞文书依托讯飞星火大模型,为文书写作者提供从素材筹备到稿件撰写及审稿的全程支持。通过录音智记和以稿写稿等功能,满足事务性工作的高频需求,帮助撰稿人节省精力,提高效率,优化工作与生活。

Project Cover

阿里绘蛙

绘蛙是阿里巴巴集团推出的革命性AI电商营销平台。利用尖端人工智能技术,为商家提供一键生成商品图和营销文案的服务,显著提升内容创作效率和营销效果。适用于淘宝、天猫等电商平台,让商品第一时间被种草。

Project Cover

AIWritePaper论文写作

AIWritePaper论文写作是一站式AI论文写作辅助工具,简化了选题、文献检索至论文撰写的整个过程。通过简单设定,平台可快速生成高质量论文大纲和全文,配合图表、参考文献等一应俱全,同时提供开题报告和答辩PPT等增值服务,保障数据安全,有效提升写作效率和论文质量。

投诉举报邮箱: service@vectorlightyear.com
@2024 懂AI·鲁ICP备2024100362号-6·鲁公网安备37021002001498号