├── .github └── workflows │ └── stale.yml ├── .gitignore ├── CHANGELOG.md ├── Dockerfile ├── LICENSE ├── README.md ├── bms.py ├── config.yaml ├── constants.py ├── docker-compose.yaml ├── icon.png ├── pace-bms-dev ├── CHANGELOG.md ├── Dockerfile ├── bms.py ├── config.yaml ├── constants.py ├── docker-compose.yaml ├── icon.png ├── requirements.txt └── run.sh ├── pace-bms-ports.png ├── repository.yaml ├── requirements.txt ├── run.sh └── volta-sg1-bms-dev ├── CHANGELOG.md ├── Dockerfile ├── bms.py ├── config.yaml ├── constants.py ├── docker-compose.yaml ├── icon.png ├── requirements.txt └── run.sh /.github/workflows/stale.yml: -------------------------------------------------------------------------------- 1 | # This workflow warns and then closes issues and PRs that have had no activity for a specified amount of time. 2 | # 3 | # You can adjust the behavior by modifying this file. 4 | # For more information, see: 5 | # https://github.com/actions/stale 6 | name: Mark stale issues and pull requests 7 | 8 | on: 9 | schedule: 10 | - cron: '0 20 * * *' 11 | 12 | jobs: 13 | stale: 14 | 15 | runs-on: ubuntu-latest 16 | permissions: 17 | issues: write 18 | pull-requests: write 19 | 20 | steps: 21 | - uses: actions/stale@v8 22 | with: 23 | repo-token: ${{ secrets.GITHUB_TOKEN }} 24 | stale-issue-message: 'This issue is stale because it has been open 45 days with no activity. Remove stale label or comment or this will be closed in 5 days.' 25 | stale-pr-message: 'This PR is stale because it has been open 60 days with no activity. Remove stale label or comment or this will be closed in 10 days.' 26 | close-issue-message: 'This issue was closed because it has been stalled for 5 days with no activity.' 27 | close-pr-message: 'This PR was closed because it has been stalled for 10 days with no activity.' 28 | days-before-issue-stale: 45 29 | days-before-pr-stale: 60 30 | days-before-issue-close: 5 31 | days-before-pr-close: 10 32 | stale-issue-label: 'no-issue-activity' 33 | stale-pr-label: 'no-pr-activity' 34 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | __pycache__/ 2 | venv/ 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | WARNING: Breaking Changes! As of version 2.0.0 each pack (battery) will be pre-fixed with its pack number. 2 |
3 | Use at own risk!! 4 |
5 | This is to support multiple packs. 6 |
7 | Additional data is now being retrieved, including warning, balancing, status indications, etc. 8 |
9 | This script excludes COMMANDS and should only retrieve data. Nonetheless the author accepts no reponsibility whatsoever of your use, in any way, of this script / addon. Again, USE AT OWN RISK! 10 |
11 |

Changelog

12 |

v2.2.0

13 | Added a calculated cell maximum voltage difference (highest cell voltage - smallest cell voltage) 14 | Rewrite Dockerfile to cache library dependencies to speed up future builds. (thanks jpmeijers) 15 | Add docker-compose.yaml to run using docker compose, with auto restarting. (thanks jpmeijers) 16 | Bugfix - Removing any spaces in the serial numbers to prevent HA unique identifiers having spaces 17 |

v2.1.0

18 | Fix for multiple packs not parsed correctly in some instances. 19 | Abbreviated some warning info to help prevent exceeding HAs character limits 20 |

v2.0.4

21 | Balance data should be base 16, not 8. 22 |

v2.0.3

23 | Possible bugfix for larger banks reading incorrect analog data 24 |

v2.0.2

25 | Naming fixes. Possible fix for native and USB serial devices 26 |

v2.0.1

27 | Bug fixs 28 |

v2.0.0

Major rewrite using the official Pace RS232 Protocol Definition. Breaking changes including prefixing most data with its Pack number (to support multiple batteries in parallel). Temperatures values are now retrieved without names, in my case the first 4 values are cell temperatures, temp 5 the MOSFET, and temp 6 is ambient / environment. 29 |

Known / possible issues

30 | The overall Pack data collected under the root MQTT topic seems to follow the data of the first battery in the Pack. -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-alpine 2 | 3 | ENV WORK_DIR=workdir \ 4 | HASSIO_DATA_PATH=/data 5 | 6 | RUN mkdir -p ${WORK_DIR} 7 | WORKDIR /${WORK_DIR} 8 | COPY requirements.txt . 9 | 10 | # install python libraries 11 | RUN pip3 install -r requirements.txt 12 | 13 | # Copy code 14 | COPY bms.py constants.py run.sh ./ 15 | RUN chmod a+x run.sh 16 | 17 | CMD [ "sh", "./run.sh" ] 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # BMS Pace - Python data retrieval 2 | ## NB: This script(s) is no longer actively being developed. Feel free to fork. 3 | Pace Battery Management System 4 | Features: 5 | * Compatible as a Home Assistant Add-on, see https://www.home-assistant.io/common-tasks/os#installing-third-party-add-ons 6 | * Cell voltages 7 | * Temperatures 8 | * State of charge (SOC) 9 | * State of health (SOH) 10 | * Warnings & faults 11 | * State indications 12 | * Cell balancing state 13 | * and many more..... 14 | 15 | ## 1. Important 16 | 17 | This addon comes with absolutely no guarantees whatsoever. Use at own risk. 18 | Feel free to fork and expand! 19 | 20 | ## 2. Confirmed working with 21 | Many brands using the PACE BMS, including: 22 | * Greenrich U-P5000 23 | * Hubble Lithium (AM2, AM4, X-101) 24 | * Revov R100, R9 25 | * SOK 48V (100Ah) 26 | * YouthPower Rack Module 48V 100AH 4U-5U Lifepo4 27 | * Allith 10kW LifePo4 28 | * Joyvoit BW5KW 29 | * etc....... 30 | 31 | If your ports look something like this, its likely a PACE BMS: 32 | 33 | ![PACE BMS Ports](https://github.com/Tertiush/bmspace/blob/main/pace-bms-ports.png?raw=true) 34 | 35 | ## 3. Configuring 36 | **Currently the DEV version is the most capable, and should work for most.** 37 | ### 3.1 Manually 38 | Install the pre-requisites as per requirements.txt. Then edit the config.yaml file to suit your needs and run the script bms.py 39 | NB: Tested with Python 3.9. Should work on later version as well. 40 | 41 | ### 3.2 Home Assistant 42 | All configuration options are available from within Home Assistant. 43 | 44 | ### 3.3 Notes on configuration options 45 | * **debug_output**: Options are 0 for minimal, 1 for minor errors such as checksums, 2-3 for more severe debug logs. 46 | * **force_pack_offset**: This is currently available in the development version. This offset is used to force a defined offset between the data read from **multiple packs**. If you have more than one pack and only the first is read successfully, you can force an offset here to get subsequent packs to read in successfully. Default is 0, multiple of 2 (e.g. 2, 4, 6....) may work. As large as 20 has been used in one instance. 47 | * **zero_pad_number_cells**: Adds leading 0's to the cell voltages, forcing then to display sequential in some dasboarding tools. E.g. setting this to 2 will display voltages as cell_01 rahter than cell_1. 48 | * **zero_pad_number_packs**: Same as for _cells padding above. 49 | 50 | ## 4. RJ11 Interface (Typical, confirm your own model!) 51 | 52 | When viewed into the RJ11 socket, tab to the bottom, pins are ordered: 53 | 1:NC 2:GND 3:BMS_Tx 4:BMS_Rx 5:GND 6:NC 54 | 55 | Either a direct serial interface from your hardware, a USB to serial, or a network connected TCP server device will work. 56 | Note the voltage levels are normal RS232 (and not TTL / 5V or something else). 57 | -------------------------------------------------------------------------------- /bms.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import paho.mqtt.client as mqtt 4 | import socket 5 | import time 6 | import yaml 7 | import os 8 | import json 9 | import serial 10 | import io 11 | import json 12 | import atexit 13 | import sys 14 | import constants 15 | 16 | print("Starting up...") 17 | 18 | config = {} 19 | 20 | if os.path.exists('/data/options.json'): 21 | print("Loading options.json") 22 | with open(r'/data/options.json') as file: 23 | config = json.load(file) 24 | print("Config: " + json.dumps(config)) 25 | 26 | elif os.path.exists('config.yaml'): 27 | print("Loading config.yaml") 28 | with open(r'config.yaml') as file: 29 | config = yaml.load(file, Loader=yaml.FullLoader)['options'] 30 | 31 | else: 32 | sys.exit("No config file found") 33 | 34 | 35 | scan_interval = config['scan_interval'] 36 | connection_type = config['connection_type'] 37 | bms_serial = config['bms_serial'] 38 | ha_discovery_enabled = config['mqtt_ha_discovery'] 39 | code_running = True 40 | bms_connected = False 41 | mqtt_connected = False 42 | print_initial = True 43 | debug_output = config['debug_output'] 44 | disc_payload = {} 45 | repub_discovery = 0 46 | 47 | bms_version = '' 48 | bms_sn = '' 49 | pack_sn = '' 50 | packs = 1 51 | cells = 13 52 | temps = 6 53 | 54 | 55 | print("Connection Type: " + connection_type) 56 | 57 | def on_connect(client, userdata, flags, rc): 58 | print("MQTT connected with result code "+str(rc)) 59 | client.will_set(config['mqtt_base_topic'] + "/availability","offline", qos=0, retain=False) 60 | global mqtt_connected 61 | mqtt_connected = True 62 | 63 | def on_disconnect(client, userdata, rc): 64 | print("MQTT disconnected with result code "+str(rc)) 65 | global mqtt_connected 66 | mqtt_connected = False 67 | 68 | 69 | client = mqtt.Client() 70 | client.on_connect = on_connect 71 | client.on_disconnect = on_disconnect 72 | #client.on_message = on_message 73 | 74 | client.username_pw_set(username=config['mqtt_user'], password=config['mqtt_password']) 75 | client.connect(config['mqtt_host'], config['mqtt_port'], 60) 76 | client.loop_start() 77 | time.sleep(2) 78 | 79 | def exit_handler(): 80 | print("Script exiting") 81 | client.publish(config['mqtt_base_topic'] + "/availability","offline") 82 | return 83 | 84 | atexit.register(exit_handler) 85 | 86 | def bms_connect(address, port): 87 | 88 | if connection_type == "Serial": 89 | 90 | try: 91 | print("trying to connect %s" % bms_serial) 92 | s = serial.Serial(bms_serial,timeout = 1) 93 | print("BMS serial connected") 94 | return s, True 95 | except IOError as msg: 96 | print("BMS serial error connecting: %s" % msg) 97 | return False, False 98 | 99 | else: 100 | 101 | try: 102 | print("trying to connect " + address + ":" + str(port)) 103 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 104 | s.settimeout(2) 105 | s.connect((address, port)) 106 | print("BMS socket connected") 107 | return s, True 108 | except OSError as msg: 109 | print("BMS socket error connecting: %s" % msg) 110 | return False, False 111 | 112 | def bms_sendData(comms,request=''): 113 | 114 | if connection_type == "Serial": 115 | 116 | try: 117 | if len(request) > 0: 118 | comms.write(request) 119 | time.sleep(0.25) 120 | return True 121 | except IOError as e: 122 | print("BMS serial error: %s" % e) 123 | # global bms_connected 124 | return False 125 | 126 | else: 127 | 128 | try: 129 | if len(request) > 0: 130 | comms.send(request) 131 | time.sleep(0.25) 132 | return True 133 | except Exception as e: 134 | print("BMS socket error: %s" % e) 135 | # global bms_connected 136 | return False 137 | 138 | def bms_get_data(comms): 139 | try: 140 | if connection_type == "Serial": 141 | inc_data = comms.readline() 142 | else: 143 | temp = comms.recv(4096) 144 | temp2 = temp.split(b'\r') 145 | # Decide which one to take: 146 | for element in range(0,len(temp2)): 147 | SOI = hex(ord(temp2[element][0:1])) 148 | if SOI == '0x7e': 149 | inc_data = temp2[element] + b'\r' 150 | break 151 | 152 | if (len(temp2) > 2) & (debug_output > 0): 153 | print("Multiple EOIs detected") 154 | print("...for incoming data: " + str(temp) + " |Hex: " + str(temp.hex(' '))) 155 | return inc_data 156 | except Exception as e: 157 | print("BMS socket receive error: %s" % e) 158 | # global bms_connected 159 | return False 160 | 161 | def ha_discovery(): 162 | 163 | global ha_discovery_enabled 164 | global packs 165 | 166 | if ha_discovery_enabled: 167 | 168 | print("Publishing HA Discovery topic...") 169 | 170 | disc_payload['availability_topic'] = config['mqtt_base_topic'] + "/availability" 171 | 172 | device = {} 173 | device['manufacturer'] = "BMS Pace" 174 | device['model'] = "AM-x" 175 | device['identifiers'] = "bmspace_" + bms_sn 176 | device['name'] = "Generic Lithium" 177 | device['sw_version'] = bms_version 178 | disc_payload['device'] = device 179 | 180 | for p in range (1,packs+1): 181 | 182 | for i in range(0,cells): 183 | disc_payload['name'] = "Pack " + str(p) + " Cell " + str(i+1) + " Voltage" 184 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_v_cell_" + str(i+1) 185 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_cells/cell_" + str(i+1) 186 | disc_payload['unit_of_measurement'] = "mV" 187 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 188 | 189 | for i in range(0,temps): 190 | disc_payload['name'] = "Pack " + str(p) + " Temperature " + str(i+1) 191 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_temp_" + str(i+1) 192 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/temps/temp_" + str(i+1) 193 | disc_payload['unit_of_measurement'] = "°C" 194 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 195 | 196 | # disc_payload['name'] = "MOS_Temp" 197 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_t_mos" 198 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/t_mos" 199 | # disc_payload['unit_of_measurement'] = "°C" 200 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'] + "/config",json.dumps(disc_payload),qos=0, retain=True) 201 | 202 | # disc_payload['name'] = "Environmental_Temp" 203 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_t_env" 204 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/t_env" 205 | # disc_payload['unit_of_measurement'] = "°C" 206 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'] + "/config",json.dumps(disc_payload),qos=0, retain=True) 207 | 208 | disc_payload['name'] = "Pack " + str(p) + " Current" 209 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_pack" 210 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_pack" 211 | disc_payload['unit_of_measurement'] = "A" 212 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 213 | 214 | disc_payload['name'] = "Pack " + str(p) + " Voltage" 215 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_v_pack" 216 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_pack" 217 | disc_payload['unit_of_measurement'] = "V" 218 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 219 | 220 | disc_payload['name'] = "Pack " + str(p) + " Remaining Capacity" 221 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_remain_cap" 222 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_remain_cap" 223 | disc_payload['unit_of_measurement'] = "mAh" 224 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 225 | 226 | disc_payload['name'] = "Pack " + str(p) + " State of Health" 227 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_soh" 228 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/soh" 229 | disc_payload['unit_of_measurement'] = "%" 230 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 231 | 232 | disc_payload['name'] = "Pack " + str(p) + " Cycles" 233 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_cycles" 234 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/cycles" 235 | disc_payload['unit_of_measurement'] = "" 236 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 237 | 238 | disc_payload['name'] = "Pack " + str(p) + " Full Capacity" 239 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_full_cap" 240 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_full_cap" 241 | disc_payload['unit_of_measurement'] = "mAh" 242 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 243 | 244 | disc_payload['name'] = "Pack " + str(p) + " Design Capacity" 245 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_design_cap" 246 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_design_cap" 247 | disc_payload['unit_of_measurement'] = "mAh" 248 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 249 | 250 | disc_payload['name'] = "Pack " + str(p) + " State of Charge" 251 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_soc" 252 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/soc" 253 | disc_payload['unit_of_measurement'] = "%" 254 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 255 | 256 | disc_payload['name'] = "Pack " + str(p) + " State of Health" 257 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_soh" 258 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/soh" 259 | disc_payload['unit_of_measurement'] = "%" 260 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 261 | 262 | 263 | disc_payload.pop('unit_of_measurement') 264 | 265 | disc_payload['name'] = "Pack " + str(p) + " Warnings" 266 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_warnings" 267 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/warnings" 268 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 269 | 270 | disc_payload['name'] = "Pack " + str(p) + " Balancing1" 271 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_balancing1" 272 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/balancing1" 273 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 274 | 275 | disc_payload['name'] = "Pack " + str(p) + " Balancing2" 276 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_balancing2" 277 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/balancing2" 278 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 279 | 280 | 281 | # Binary Sensors 282 | disc_payload['name'] = "Pack " + str(p) + " Protection Short Circuit" 283 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_prot_short_circuit" 284 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_short_circuit" 285 | disc_payload['payload_on'] = "1" 286 | disc_payload['payload_off'] = "0" 287 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 288 | 289 | disc_payload['name'] = "Pack " + str(p) + " Protection Discharge Current" 290 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_prot_discharge_current" 291 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_discharge_current" 292 | disc_payload['payload_on'] = "1" 293 | disc_payload['payload_off'] = "0" 294 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 295 | 296 | disc_payload['name'] = "Pack " + str(p) + " Protection Charge Current" 297 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_prot_charge_current" 298 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_charge_current" 299 | disc_payload['payload_on'] = "1" 300 | disc_payload['payload_off'] = "0" 301 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 302 | 303 | disc_payload['name'] = "Pack " + str(p) + " Current Limit" 304 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_current_limit" 305 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/current_limit" 306 | disc_payload['payload_on'] = "1" 307 | disc_payload['payload_off'] = "0" 308 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 309 | 310 | disc_payload['name'] = "Pack " + str(p) + " Charge FET" 311 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_charge_fet" 312 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/charge_fet" 313 | disc_payload['payload_on'] = "1" 314 | disc_payload['payload_off'] = "0" 315 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 316 | 317 | disc_payload['name'] = "Pack " + str(p) + " Discharge FET" 318 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_discharge_fet" 319 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/discharge_fet" 320 | disc_payload['payload_on'] = "1" 321 | disc_payload['payload_off'] = "0" 322 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 323 | 324 | disc_payload['name'] = "Pack " + str(p) + " Pack Indicate" 325 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_pack_indicate" 326 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/pack_indicate" 327 | disc_payload['payload_on'] = "1" 328 | disc_payload['payload_off'] = "0" 329 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 330 | 331 | disc_payload['name'] = "Pack " + str(p) + " Reverse" 332 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_reverse" 333 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/reverse" 334 | disc_payload['payload_on'] = "1" 335 | disc_payload['payload_off'] = "0" 336 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 337 | 338 | disc_payload['name'] = "Pack " + str(p) + " AC In" 339 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_ac_in" 340 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/ac_in" 341 | disc_payload['payload_on'] = "1" 342 | disc_payload['payload_off'] = "0" 343 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 344 | 345 | disc_payload['name'] = "Pack " + str(p) + " Heart" 346 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_heart" 347 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/heart" 348 | disc_payload['payload_on'] = "1" 349 | disc_payload['payload_off'] = "0" 350 | client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 351 | 352 | disc_payload['name'] = "Pack " + str(p) + " Cell Max Volt Diff" 353 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_cells_max_diff_calc" 354 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/cells_max_diff_calc" 355 | disc_payload['unit_of_measurement'] = "mV" 356 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 357 | 358 | # Pack data 359 | disc_payload.pop('payload_on') 360 | disc_payload.pop('payload_off') 361 | 362 | disc_payload['name'] = "Pack Remaining Capacity" 363 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_i_remain_cap" 364 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_remain_cap" 365 | disc_payload['unit_of_measurement'] = "mAh" 366 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 367 | 368 | disc_payload['name'] = "Pack Full Capacity" 369 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_i_full_cap" 370 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_full_cap" 371 | disc_payload['unit_of_measurement'] = "mAh" 372 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 373 | 374 | disc_payload['name'] = "Pack Design Capacity" 375 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_i_design_cap" 376 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_design_cap" 377 | disc_payload['unit_of_measurement'] = "mAh" 378 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 379 | 380 | disc_payload['name'] = "Pack State of Charge" 381 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_soc" 382 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_soc" 383 | disc_payload['unit_of_measurement'] = "%" 384 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 385 | 386 | disc_payload['name'] = "Pack State of Health" 387 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_soh" 388 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_soh" 389 | disc_payload['unit_of_measurement'] = "%" 390 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 391 | 392 | else: 393 | print("HA Discovery Disabled") 394 | 395 | def chksum_calc(data): 396 | 397 | global debug_output 398 | chksum = 0 399 | 400 | try: 401 | 402 | for element in range(1, len(data)): #-5): 403 | chksum += (data[element]) 404 | 405 | chksum = chksum % 65536 406 | chksum = '{0:016b}'.format(chksum) 407 | 408 | flip_bits = '' 409 | for i in chksum: 410 | if i == '0': 411 | flip_bits += '1' 412 | else: 413 | flip_bits += '0' 414 | 415 | chksum = flip_bits 416 | chksum = int(chksum,2)+1 417 | 418 | chksum = format(chksum, 'X') 419 | 420 | except Exception as e: 421 | if debug_output > 0: 422 | print("Error calculating CHKSUM using data: " + data) 423 | print("Error details: ", str(e)) 424 | return(False) 425 | 426 | return(chksum) 427 | 428 | def cid2_rtn(rtn): 429 | 430 | # RTN Reponse codes, looking for errors 431 | if rtn == b'00': 432 | return False, False 433 | elif rtn == b'01': 434 | return True, "RTN Error 01: Undefined RTN error" 435 | elif rtn == b'02': 436 | return True, "RTN Error 02: CHKSUM error" 437 | elif rtn == b'03': 438 | return True, "RTN Error 03: LCHKSUM error" 439 | elif rtn == b'04': 440 | return True, "RTN Error 04: CID2 undefined" 441 | elif rtn == b'05': 442 | return True, "RTN Error 05: Undefined error" 443 | elif rtn == b'06': 444 | return True, "RTN Error 06: Undefined error" 445 | elif rtn == b'09': 446 | return True, "RTN Error 09: Operation or write error" 447 | else: 448 | return False, False 449 | 450 | def bms_parse_data(inc_data): 451 | 452 | global debug_output 453 | 454 | #inc_data = b'~2501460070DC00020D100A0FF40FEA100E10040FF50FFD10010FFD0FE50FF5100A1001060BD20BD20BD40BD40BF80C1AFF7ECFCF258B02271001372710600D0FFA0FFC0FFB0FFC0FFE0FFB0FFA0FFA0FFB0FFD0FFC0FFB0FFB060BEF0BF10BEF0BED0BF70C04FDB1D02E29A9022AF80\r' 455 | 456 | try: 457 | 458 | SOI = hex(ord(inc_data[0:1])) 459 | if SOI != '0x7e': 460 | return(False,"Incorrect starting byte for incoming data") 461 | 462 | if debug_output > 1: 463 | print("SOI: ", SOI) 464 | print("VER: ", inc_data[1:3]) 465 | print("ADR: ", inc_data[3:5]) 466 | print("CID1 (Type): ", inc_data[5:7]) 467 | 468 | RTN = inc_data[7:9] 469 | error, info = cid2_rtn(RTN) 470 | if error: 471 | print(error) 472 | raise Exception(error) 473 | 474 | LCHKSUM = inc_data[9] 475 | 476 | if debug_output > 1: 477 | print("RTN: ", RTN) 478 | print("LENGTH: ", inc_data[9:13]) 479 | print(" - LCHKSUM: ", LCHKSUM) 480 | print(" - LENID: ", inc_data[10:13]) 481 | 482 | LENID = int(inc_data[10:13],16) #amount of bytes, i.e. 2x hex 483 | 484 | calc_LCHKSUM = lchksum_calc(inc_data[10:13]) 485 | if calc_LCHKSUM == False: 486 | return(False,"Error calculating LCHKSUM for incoming data") 487 | 488 | if LCHKSUM != ord(calc_LCHKSUM): 489 | if debug_output > 0: 490 | print("LCHKSUM received: " + str(LCHKSUM) + " does not match calculated: " + str(ord(calc_LCHKSUM))) 491 | return(False,"LCHKSUM received: " + str(LCHKSUM) + " does not match calculated: " + str(ord(calc_LCHKSUM))) 492 | 493 | if debug_output > 1: 494 | print(" - LENID (int): ", LENID) 495 | 496 | INFO = inc_data[13:13+LENID] 497 | 498 | if debug_output > 1: 499 | print("INFO: ", INFO) 500 | 501 | CHKSUM = inc_data[13+LENID:13+LENID+4] 502 | 503 | if debug_output > 1: 504 | print("CHKSUM: ", CHKSUM) 505 | #print("EOI: ", hex(inc_data[13+LENID+4])) 506 | 507 | calc_CHKSUM = chksum_calc(inc_data[:len(inc_data)-5]) 508 | 509 | 510 | if debug_output > 1: 511 | print("Calc CHKSUM: ", calc_CHKSUM) 512 | except Exception as e: 513 | if debug_output > 0: 514 | print("Error1 calculating CHKSUM using data: ", inc_data) 515 | return(False,"Error1 calculating CHKSUM: " + str(e)) 516 | 517 | if calc_CHKSUM == False: 518 | if debug_output > 0: 519 | print("Error2 calculating CHKSUM using data: ", inc_data) 520 | return(False,"Error2 calculating CHKSUM") 521 | 522 | if CHKSUM.decode("ASCII") == calc_CHKSUM: 523 | return(True,INFO) 524 | else: 525 | if debug_output > 0: 526 | print("Received and calculated CHKSUM does not match: Received: " + CHKSUM.decode("ASCII") + ", Calculated: " + calc_CHKSUM) 527 | print("...for incoming data: " + str(inc_data) + " |Hex: " + str(inc_data.hex(' '))) 528 | print("Length of incoming data as measured: " + str(len(inc_data))) 529 | print("SOI: ", SOI) 530 | print("VER: ", inc_data[1:3]) 531 | print("ADR: ", inc_data[3:5]) 532 | print("CID1 (Type): ", inc_data[5:7]) 533 | print("RTN (decode!): ", RTN) 534 | print("LENGTH: ", inc_data[9:13]) 535 | print(" - LCHKSUM: ", inc_data[9]) 536 | print(" - LENID: ", inc_data[10:13]) 537 | print(" - LENID (int): ", int(inc_data[10:13],16)) 538 | print("INFO: ", INFO) 539 | print("CHKSUM: ", CHKSUM) 540 | #print("EOI: ", hex(inc_data[13+LENID+4])) 541 | return(False,"Checksum error") 542 | 543 | def lchksum_calc(lenid): 544 | 545 | chksum = 0 546 | 547 | try: 548 | 549 | # for element in range(1, len(lenid)): #-5): 550 | # chksum += (lenid[element]) 551 | 552 | for element in range(0, len(lenid)): 553 | chksum += int(chr(lenid[element]),16) 554 | 555 | chksum = chksum % 16 556 | chksum = '{0:04b}'.format(chksum) 557 | 558 | flip_bits = '' 559 | for i in chksum: 560 | if i == '0': 561 | flip_bits += '1' 562 | else: 563 | flip_bits += '0' 564 | 565 | chksum = flip_bits 566 | chksum = int(chksum,2) 567 | 568 | chksum += 1 569 | 570 | if chksum > 15: 571 | chksum = 0 572 | 573 | chksum = format(chksum, 'X') 574 | 575 | except: 576 | 577 | print("Error calculating LCHKSUM using LENID: ", lenid) 578 | return(False) 579 | 580 | return(chksum) 581 | 582 | def bms_request(bms, ver=b"\x32\x35",adr=b"\x30\x31",cid1=b"\x34\x36",cid2=b"\x43\x31",info=b"",LENID=False): 583 | 584 | global bms_connected 585 | global debug_output 586 | 587 | request = b'\x7e' 588 | request += ver 589 | request += adr 590 | request += cid1 591 | request += cid2 592 | 593 | if not(LENID): 594 | LENID = len(info) 595 | #print("Length: ", LENID) 596 | LENID = bytes(format(LENID, '03X'), "ASCII") 597 | 598 | #print("LENID: ", LENID) 599 | 600 | if LENID == b'000': 601 | LCHKSUM = '0' 602 | else: 603 | LCHKSUM = lchksum_calc(LENID) 604 | if LCHKSUM == False: 605 | return(False,"Error calculating LCHKSUM)") 606 | #print("LCHKSUM: ", LCHKSUM) 607 | request += bytes(LCHKSUM, "ASCII") 608 | request += LENID 609 | request += info 610 | CHKSUM = bytes(chksum_calc(request), "ASCII") 611 | if CHKSUM == False: 612 | return(False,"Error calculating CHKSUM)") 613 | request += CHKSUM 614 | request += b'\x0d' 615 | 616 | if debug_output > 2: 617 | print("-> Outgoing Data: ", request) 618 | 619 | if not bms_sendData(bms,request): 620 | bms_connected = False 621 | print("Error, connection to BMS lost") 622 | return(False,"Error, connection to BMS lost") 623 | 624 | inc_data = bms_get_data(bms) 625 | 626 | if inc_data == False: 627 | print("Error retrieving data from BMS") 628 | return(False,"Error retrieving data from BMS") 629 | 630 | if debug_output > 2: 631 | print("<- Incoming data: ", inc_data) 632 | 633 | success, INFO = bms_parse_data(inc_data) 634 | 635 | return(success, INFO) 636 | 637 | def bms_getPackNumber(bms): 638 | 639 | success, INFO = bms_request(bms,cid2=constants.cid2PackNumber) 640 | 641 | if success == False: 642 | return(False,INFO) 643 | 644 | try: 645 | packNumber = int(INFO,16) 646 | except: 647 | print("Error extracting total battery count in pack") 648 | return(False,"Error extracting total battery count in pack") 649 | 650 | return(success,packNumber) 651 | 652 | def bms_getVersion(comms): 653 | 654 | global bms_version 655 | 656 | success, INFO = bms_request(bms,cid2=constants.cid2SoftwareVersion) 657 | 658 | if success == False: 659 | return(False,INFO) 660 | 661 | try: 662 | 663 | bms_version = bytes.fromhex(INFO.decode("ascii")).decode("ASCII") 664 | client.publish(config['mqtt_base_topic'] + "/bms_version",bms_version) 665 | print("BMS Version: " + bms_version) 666 | except: 667 | return(False,"Error extracting BMS version") 668 | 669 | return(success,bms_version) 670 | 671 | def bms_getSerial(comms): 672 | 673 | global bms_sn 674 | global pack_sn 675 | 676 | success, INFO = bms_request(bms,cid2=constants.cid2SerialNumber) 677 | 678 | if success == False: 679 | print("Error: " + INFO) 680 | return(False,INFO, False) 681 | 682 | try: 683 | 684 | bms_sn = bytes.fromhex(INFO[0:30].decode("ascii")).decode("ASCII").replace(" ", "") 685 | pack_sn = bytes.fromhex(INFO[40:68].decode("ascii")).decode("ASCII").replace(" ", "") 686 | client.publish(config['mqtt_base_topic'] + "/bms_sn",bms_sn) 687 | client.publish(config['mqtt_base_topic'] + "/pack_sn",pack_sn) 688 | print("BMS Serial Number: " + bms_sn) 689 | print("Pack Serial Number: " + pack_sn) 690 | 691 | except: 692 | return(False,"Error extracting BMS version", False) 693 | 694 | return(success,bms_sn,pack_sn) 695 | 696 | def bms_getAnalogData(bms,batNumber): 697 | 698 | global print_initial 699 | global cells 700 | global temps 701 | global packs 702 | byte_index = 2 703 | i_pack = [] 704 | v_pack = [] 705 | i_remain_cap = [] 706 | i_design_cap = [] 707 | cycles = [] 708 | i_full_cap = [] 709 | soc = [] 710 | soh = [] 711 | 712 | battery = bytes(format(batNumber, '02X'), 'ASCII') 713 | # print("Get analog info for battery: ", battery) 714 | 715 | success, inc_data = bms_request(bms,cid2=constants.cid2PackAnalogData,info=battery) 716 | 717 | if success == False: 718 | return(False,inc_data) 719 | 720 | try: 721 | 722 | packs = int(inc_data[byte_index:byte_index+2],16) 723 | if print_initial: 724 | print("Packs: " + str(packs)) 725 | byte_index += 2 726 | 727 | v_cell = {} 728 | t_cell = {} 729 | 730 | for p in range(1,packs+1): 731 | 732 | if p > 1: 733 | cells_prev = cells 734 | 735 | cells = int(inc_data[byte_index:byte_index+2],16) 736 | 737 | #Possible remove this next test as were now testing for the INFOFLAG at the end 738 | if p > 1: 739 | if cells != cells_prev: 740 | byte_index += 2 741 | cells = int(inc_data[byte_index:byte_index+2],16) 742 | if cells != cells_prev: 743 | print("Error parsing BMS analog data: Cannot read multiple packs") 744 | return(False,"Error parsing BMS analog data: Cannot read multiple packs") 745 | 746 | if print_initial: 747 | print("Pack " + str(p) + ", Total cells: " + str(cells)) 748 | byte_index += 2 749 | 750 | cell_min_volt = 0 751 | cell_max_volt = 0 752 | 753 | for i in range(0,cells): 754 | v_cell[(p-1,i)] = int(inc_data[byte_index:byte_index+4],16) 755 | byte_index += 4 756 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_cells/cell_" + str(i+1) ,str(v_cell[(p-1,i)])) 757 | if print_initial: 758 | print("Pack " + str(p) +", V Cell" + str(i+1) + ": " + str(v_cell[(p-1,i)]) + " mV") 759 | 760 | #Calculate cell max and min volt 761 | if i == 0: 762 | cell_min_volt = v_cell[(p-1,i)] 763 | cell_max_volt = v_cell[(p-1,i)] 764 | else: 765 | if v_cell[(p-1,i)] < cell_min_volt: 766 | cell_min_volt = v_cell[(p-1,i)] 767 | if v_cell[(p-1,i)] > cell_max_volt: 768 | cell_max_volt = v_cell[(p-1,i)] 769 | 770 | #Calculate cells max diff volt 771 | cell_max_diff_volt = cell_max_volt - cell_min_volt 772 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/cells_max_diff_calc" ,str(cell_max_diff_volt)) 773 | if print_initial: 774 | print("Pack " + str(p) +", Cell Max Diff Volt Calc: " + str(cell_max_diff_volt) + " mV") 775 | 776 | temps = int(inc_data[byte_index:byte_index + 2],16) 777 | if print_initial: 778 | print("Pack " + str(p) + ", Total temperature sensors: " + str(temps)) 779 | byte_index += 2 780 | 781 | for i in range(0,temps): #temps-2 782 | t_cell[(p-1,i)] = (int(inc_data[byte_index:byte_index + 4],16)-2730)/10 783 | byte_index += 4 784 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/temps/temp_" + str(i+1) ,str(round(t_cell[(p-1,i)],1))) 785 | if print_initial: 786 | print("Pack " + str(p) + ", Temp" + str(i+1) + ": " + str(round(t_cell[(p-1,i)],1)) + " ℃") 787 | 788 | # t_mos= (int(inc_data[byte_index:byte_index+4],16))/160-273 789 | # client.publish(config['mqtt_base_topic'] + "/t_mos",str(round(t_mos,1))) 790 | # if print_initial: 791 | # print("T Mos: " + str(t_mos) + " Deg") 792 | 793 | # t_env= (int(inc_data[byte_index:byte_index+4],16))/160-273 794 | # client.publish(config['mqtt_base_topic'] + "/t_env",str(round(t_env,1))) 795 | # offset += 7 796 | # if print_initial: 797 | # print("T Env: " + str(t_env) + " Deg") 798 | 799 | i_pack.append(int(inc_data[byte_index:byte_index+4],16)) 800 | byte_index += 4 801 | if i_pack[p-1] >= 32768: 802 | i_pack[p-1] = -1*(65535 - i_pack[p-1]) 803 | i_pack[p-1] = i_pack[p-1]/100 804 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_pack",str(i_pack[p-1])) 805 | if print_initial: 806 | print("Pack " + str(p) + ", I Pack: " + str(i_pack[p-1]) + " A") 807 | 808 | v_pack.append(int(inc_data[byte_index:byte_index+4],16)/1000) 809 | byte_index += 4 810 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_pack",str(v_pack[p-1])) 811 | if print_initial: 812 | print("Pack " + str(p) + ", V Pack: " + str(v_pack[p-1]) + " V") 813 | 814 | i_remain_cap.append(int(inc_data[byte_index:byte_index+4],16)*10) 815 | byte_index += 4 816 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_remain_cap",str(i_remain_cap[p-1])) 817 | if print_initial: 818 | print("Pack " + str(p) + ", I Remaining Capacity: " + str(i_remain_cap[p-1]) + " mAh") 819 | 820 | byte_index += 2 # Manual: Define number P = 3 821 | 822 | i_full_cap.append(int(inc_data[byte_index:byte_index+4],16)*10) 823 | byte_index += 4 824 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_full_cap",str(i_full_cap[p-1])) 825 | if print_initial: 826 | print("Pack " + str(p) + ", I Full Capacity: " + str(i_full_cap[p-1]) + " mAh") 827 | 828 | soc.append(round(i_remain_cap[p-1]/i_full_cap[p-1]*100,2)) 829 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/soc",str(soc[p-1])) 830 | if print_initial: 831 | print("Pack " + str(p) + ", SOC: " + str(soc[p-1]) + " %") 832 | 833 | cycles.append(int(inc_data[byte_index:byte_index+4],16)) 834 | byte_index += 4 835 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/cycles",str(cycles[p-1])) 836 | if print_initial: 837 | print("Pack " + str(p) + ", Cycles: " + str(cycles[p-1])) 838 | 839 | i_design_cap.append(int(inc_data[byte_index:byte_index+4],16)*10) 840 | byte_index += 4 841 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_design_cap",str(i_design_cap[p-1])) 842 | if print_initial: 843 | print("Pack " + str(p) + ", Design Capacity: " + str(i_design_cap[p-1]) + " mAh") 844 | 845 | soh.append(round(i_full_cap[p-1]/i_design_cap[p-1]*100,2)) 846 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/soh",str(soh[p-1])) 847 | if print_initial: 848 | print("Pack " + str(p) + ", SOH: " + str(soh[p-1]) + " %") 849 | 850 | byte_index += 2 851 | 852 | #Test for non signed value (matching cell count), to skip possible INFOFLAG present in data 853 | if (byte_index < len(inc_data)) and (cells != int(inc_data[byte_index:byte_index+2],16)): 854 | byte_index += 2 855 | 856 | except Exception as e: 857 | print("Error parsing BMS analog data: ", str(e)) 858 | return(False,"Error parsing BMS analog data: " + str(e)) 859 | 860 | if print_initial: 861 | print("Script running....") 862 | 863 | return True,True 864 | 865 | def bms_getPackCapacity(bms): 866 | 867 | byte_index = 0 868 | 869 | success, inc_data = bms_request(bms,cid2=constants.cid2PackCapacity) # Seem to always reply with pack 1 data, even with ADR= 0 or FF and INFO= '' or FF 870 | 871 | if success == False: 872 | return(False,inc_data) 873 | 874 | try: 875 | 876 | pack_remain_cap = int(inc_data[byte_index:byte_index+4],16)*10 877 | byte_index += 4 878 | client.publish(config['mqtt_base_topic'] + "/pack_remain_cap",str(pack_remain_cap)) 879 | if print_initial: 880 | print("Pack Remaining Capacity: " + str(pack_remain_cap) + " mAh") 881 | 882 | pack_full_cap = int(inc_data[byte_index:byte_index+4],16)*10 883 | byte_index += 4 884 | client.publish(config['mqtt_base_topic'] + "/pack_full_cap",str(pack_full_cap)) 885 | if print_initial: 886 | print("Pack Full Capacity: " + str(pack_full_cap) + " mAh") 887 | 888 | pack_design_cap = int(inc_data[byte_index:byte_index+4],16)*10 889 | byte_index += 4 890 | client.publish(config['mqtt_base_topic'] + "/pack_design_cap",str(pack_design_cap)) 891 | if print_initial: 892 | print("Pack Design Capacity: " + str(pack_design_cap) + " mAh") 893 | 894 | pack_soc = round(pack_remain_cap/pack_full_cap*100,2) 895 | client.publish(config['mqtt_base_topic'] + "/pack_soc",str(pack_soc)) 896 | if print_initial: 897 | print("Pack SOC: " + str(pack_soc) + " %") 898 | 899 | pack_soh = round(pack_full_cap/pack_design_cap*100,2) 900 | client.publish(config['mqtt_base_topic'] + "/pack_soh",str(pack_soh)) 901 | if print_initial: 902 | print("Pack SOH: " + str(pack_soh) + " %") 903 | 904 | except Exception as e: 905 | print("Error parsing BMS pack capacity data: ", str(e)) 906 | return False, "Error parsing BMS pack capacity data: " + str(e) 907 | 908 | return True,True 909 | 910 | def bms_getWarnInfo(bms): 911 | 912 | byte_index = 2 913 | packsW = 1 914 | warnings = "" 915 | 916 | success, inc_data = bms_request(bms,cid2=constants.cid2WarnInfo,info=b'FF') 917 | 918 | if success == False: 919 | return(False,inc_data) 920 | 921 | #inc_data = b'000210000000000000000000000000000000000600000000000000000000000E0000000000001110000000000000000000000000000000000600000000000000000000000E00000000000000' 922 | 923 | try: 924 | 925 | packsW = int(inc_data[byte_index:byte_index+2],16) 926 | if print_initial: 927 | print("Packs for warnings: " + str(packs)) 928 | byte_index += 2 929 | 930 | for p in range(1,packs+1): 931 | 932 | cellsW = int(inc_data[byte_index:byte_index+2],16) 933 | byte_index += 2 934 | 935 | for c in range(1,cellsW+1): 936 | 937 | if inc_data[byte_index:byte_index+2] != b'00': 938 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 939 | warnings += "cell " + str(c) + " " + warn + ", " 940 | byte_index += 2 941 | 942 | tempsW = int(inc_data[byte_index:byte_index+2],16) 943 | byte_index += 2 944 | 945 | for t in range(1,tempsW+1): 946 | 947 | if inc_data[byte_index:byte_index+2] != b'00': 948 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 949 | warnings += "temp " + str(t) + " " + warn + ", " 950 | byte_index += 2 951 | 952 | if inc_data[byte_index:byte_index+2] != b'00': 953 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 954 | warnings += "charge current " + warn + ", " 955 | byte_index += 2 956 | 957 | if inc_data[byte_index:byte_index+2] != b'00': 958 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 959 | warnings += "total voltage " + warn + ", " 960 | byte_index += 2 961 | 962 | if inc_data[byte_index:byte_index+2] != b'00': 963 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 964 | warnings += "discharge current " + warn + ", " 965 | byte_index += 2 966 | 967 | protectState1 = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 968 | if protectState1 > 0: 969 | warnings += "Protection State 1: " 970 | for x in range(0,8): 971 | if (protectState1 & (1<>6 & 1)) 976 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_discharge_current",str(protectState1>>5 & 1)) 977 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_charge_current",str(protectState1>>4 & 1)) 978 | byte_index += 2 979 | 980 | protectState2 = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 981 | if protectState2 > 0: 982 | warnings += "Protection State 2: " 983 | for x in range(0,8): 984 | if (protectState2 & (1<>7 & 1)) 989 | byte_index += 2 990 | 991 | # instructionState = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 992 | # if instructionState > 0: 993 | # warnings += "Instruction State: " 994 | # for x in range(0,8): 995 | # if (instructionState & (1<>0 & 1)) 1003 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/charge_fet",str(instructionState>>1 & 1)) 1004 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/discharge_fet",str(instructionState>>2 & 1)) 1005 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/pack_indicate",str(instructionState>>3 & 1)) 1006 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/reverse",str(instructionState>>4 & 1)) 1007 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/ac_in",str(instructionState>>5 & 1)) 1008 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/heart",str(instructionState>>7 & 1)) 1009 | byte_index += 2 1010 | 1011 | controlState = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 1012 | if controlState > 0: 1013 | warnings += "Control State: " 1014 | for x in range(0,8): 1015 | if (controlState & (1< 0: 1023 | warnings += "Fault State: " 1024 | for x in range(0,8): 1025 | if (faultState & (1< 0: 1039 | warnings += "Warning State 1: " 1040 | for x in range(0,8): 1041 | if (warnState1 & (1< 0: 1049 | warnings += "Warning State 2: " 1050 | for x in range(0,8): 1051 | if (warnState2 & (1< 3600: 1137 | repub_discovery = 0 1138 | print_initial = True 1139 | 1140 | else: #MQTT not connected 1141 | client.loop_stop() 1142 | print("MQTT disconnected, trying to reconnect...") 1143 | client.connect(config['mqtt_host'], config['mqtt_port'], 60) 1144 | client.loop_start() 1145 | time.sleep(5) 1146 | print_initial = True 1147 | else: #BMS not connected 1148 | print("BMS disconnected, trying to reconnect...") 1149 | bms,bms_connected = bms_connect(config['bms_ip'],config['bms_port']) 1150 | client.publish(config['mqtt_base_topic'] + "/availability","offline") 1151 | time.sleep(5) 1152 | print_initial = True 1153 | 1154 | client.loop_stop() 1155 | -------------------------------------------------------------------------------- /config.yaml: -------------------------------------------------------------------------------- 1 | name: "BMS Pace" 2 | description: "Pace BMS Interface" 3 | version: "2.2.0" 4 | slug: "bms_pace" 5 | url: "https://github.com/Tertiush/bmspace/pace-bms" 6 | init: false 7 | arch: 8 | - aarch64 9 | - amd64 10 | - armhf 11 | - armv7 12 | - i386 13 | 14 | uart: true 15 | usb: true 16 | 17 | options: 18 | mqtt_host: "10.0.0.132" 19 | mqtt_port: 1883 20 | mqtt_user: "mqtt-users" 21 | mqtt_password: "mqtt-users" 22 | mqtt_ha_discovery: true 23 | mqtt_ha_discovery_topic: "homeassistant" 24 | mqtt_base_topic: "bmspace" 25 | connection_type: "IP" 26 | bms_ip: "10.0.0.161" 27 | bms_port: 5000 28 | bms_serial: "/dev/ttyUSB0" 29 | scan_interval: 5 30 | debug_output: 0 31 | schema: 32 | mqtt_host: str 33 | mqtt_port: int 34 | mqtt_user: str 35 | mqtt_password: str 36 | mqtt_ha_discovery: bool 37 | mqtt_ha_discovery_topic: str 38 | mqtt_base_topic: str 39 | connection_type: list(IP|Serial) 40 | bms_ip: str 41 | bms_port: int 42 | bms_serial: str 43 | scan_interval: int 44 | debug_output: int 45 | -------------------------------------------------------------------------------- /constants.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | cid2PackNumber = b"\x39\x30" # 0x90 4 | cid2PackAnalogData = b"\x34\x32" # 0x42 5 | cid2SoftwareVersion = b"\x43\x31" # 0xC1 6 | cid2SerialNumber = b"\x43\x32" # 0xC2 7 | cid2PackCapacity = b"\x41\x36" # 0xA6 8 | cid2WarnInfo = b"\x34\x34" # 0x44 9 | 10 | 11 | warningStates = { b'00': "Normal", 12 | b'01': "< low limit", 13 | b'02': "> up limit", 14 | b'F0': "other fault"} # 80H~EFH:user defined 15 | 16 | protectState1 = { 1: "Above cell volt protect", 17 | 2: "Lower cell volt protect", 18 | 3: "Above total volt protect", 19 | 4: "Lower total volt protect", 20 | 5: "Charge current protect", 21 | 6: "Discharge current protect", 22 | 7: "Short circuit", 23 | 8: "undefined"} 24 | 25 | protectState2 = { 1: "Above charge temp protect", 26 | 2: "Above discharge temp protect", 27 | 3: "Lower charge temp protect", 28 | 4: "Lower discharge temp protect", 29 | 5: "Above MOS temp protect", 30 | 6: "Above Env temp protect", 31 | 7: "Lower Env temp protect", 32 | 8: "Fully"} 33 | 34 | instructionState = {1: "Current limit indicate ON", 35 | 2: "CFET indicate ON", 36 | 3: "DFET indicate ON", 37 | 4: "Pack indicate ON", 38 | 5: "Reverse indicate ON", 39 | 6: "ACin ON", 40 | 7: "Undefined", 41 | 8: "Heart indicate ON"} 42 | 43 | controlState = {1: "Buzzer warn function enabled", 44 | 2: "undefined", 45 | 3: "undefined", 46 | 4: "Current limit gear => low gear", 47 | 5: "Current limit function disabled", 48 | 6: "LED warn functiuon disabled", 49 | 7: "Undefined", 50 | 8: "Undefined"} 51 | 52 | faultState = {1: "Charge MOS fault", 53 | 2: "Discharge MOS fault", 54 | 3: "NTC fault (NTC)", 55 | 4: "Undefined", 56 | 5: "Cell fault", 57 | 6: "Sample fault", 58 | 7: "Undefined", 59 | 8: "Undefined"} 60 | 61 | warnState1 = {1: "Above cell volt warn", 62 | 2: "Lower cell volt warn", 63 | 3: "Above total volt warn", 64 | 4: "Lower total volt warn", 65 | 5: "Charge current warn", 66 | 6: "Discharge current warn", 67 | 7: "Undefined", 68 | 8: "Undefined"} 69 | 70 | warnState2 = {1: "Above charge temp warn", 71 | 2: "Above discharge temp warn", 72 | 3: "Low charge temp warn", 73 | 4: "Low discharge temp warn", 74 | 5: "High env temp warn", 75 | 6: "Low env temp warn", 76 | 7: "High MOS temp warn", 77 | 8: "Low power warn"} -------------------------------------------------------------------------------- /docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | bmspace: 4 | build: 5 | context: . 6 | restart: unless-stopped 7 | privileged: true 8 | volumes: 9 | - ./config.yaml:/workdir/config.yaml 10 | - /dev:/dev 11 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tertiush/bmspace/c756863884bad153b35330c97f107deea3b8de18/icon.png -------------------------------------------------------------------------------- /pace-bms-dev/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | WARNING: Breaking Changes! As of version 2.0.0 each pack (battery) will be pre-fixed with its pack number. 2 |
3 | Use at own risk!! 4 |
5 | This is to support multiple packs. 6 |
7 | Additional data is now being retrieved, including warning, balancing, status indications, etc. 8 |
9 | This script excludes COMMANDS and should only retrieve data. Nonetheless the author accepts no reponsibility whatsoever of your use, in any way, of this script / addon. Again, USE AT OWN RISK! 10 |
11 |

Changelog

12 |

Development Version:

13 | 14 | 2.3dev - Added optional zero(0) padding for pack and cell values, to help maintain ordering. If used your history will be spread across the old and new names! 15 | 16 | Added nested exception catches that might help the script not fail if a pack is missing. 17 | 18 | 19 |

Known / possible issues

20 | The overall Pack data collected under the root MQTT topic seems to follow the data of the first battery in the Pack. -------------------------------------------------------------------------------- /pace-bms-dev/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-alpine 2 | 3 | ENV WORK_DIR=workdir \ 4 | HASSIO_DATA_PATH=/data 5 | 6 | RUN mkdir -p ${WORK_DIR} 7 | WORKDIR /${WORK_DIR} 8 | COPY requirements.txt . 9 | 10 | # install python libraries 11 | RUN pip3 install -r requirements.txt 12 | 13 | # Copy code 14 | COPY bms.py constants.py run.sh ./ 15 | RUN chmod a+x run.sh 16 | 17 | CMD [ "sh", "./run.sh" ] 18 | -------------------------------------------------------------------------------- /pace-bms-dev/config.yaml: -------------------------------------------------------------------------------- 1 | name: "BMS Pace - Development" 2 | description: "Pace BMS Interface" 3 | version: "2.3dev" 4 | slug: "bms_pace_dev" 5 | url: "https://github.com/Tertiush/bmspace/pace-bms-dev" 6 | init: false 7 | arch: 8 | - aarch64 9 | - amd64 10 | - armhf 11 | - armv7 12 | - i386 13 | 14 | uart: true 15 | usb: true 16 | 17 | options: 18 | mqtt_host: "10.0.0.132" 19 | mqtt_port: 1883 20 | mqtt_user: "mqtt-users" 21 | mqtt_password: "mqtt-users" 22 | mqtt_ha_discovery: true 23 | mqtt_ha_discovery_topic: "homeassistant" 24 | mqtt_base_topic: "bmspace" 25 | connection_type: "IP" 26 | bms_ip: "10.0.0.161" 27 | bms_port: 5000 28 | bms_serial: "/dev/ttyUSB0" 29 | scan_interval: 5 30 | debug_output: 0 31 | force_pack_offset: 0 32 | zero_pad_number_cells: 0 33 | zero_pad_number_packs: 0 34 | schema: 35 | mqtt_host: str 36 | mqtt_port: int 37 | mqtt_user: str 38 | mqtt_password: str 39 | mqtt_ha_discovery: bool 40 | mqtt_ha_discovery_topic: str 41 | mqtt_base_topic: str 42 | connection_type: list(IP|Serial) 43 | bms_ip: str 44 | bms_port: int 45 | bms_serial: str 46 | scan_interval: int 47 | debug_output: int 48 | force_pack_offset: "int?" 49 | zero_pad_number_cells: "int?" 50 | zero_pad_number_packs: "int?" -------------------------------------------------------------------------------- /pace-bms-dev/constants.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | cid2PackNumber = b"\x39\x30" # 0x90 4 | cid2PackAnalogData = b"\x34\x32" # 0x42 5 | cid2SoftwareVersion = b"\x43\x31" # 0xC1 6 | cid2SerialNumber = b"\x43\x32" # 0xC2 7 | cid2PackCapacity = b"\x41\x36" # 0xA6 8 | cid2WarnInfo = b"\x34\x34" # 0x44 9 | 10 | 11 | warningStates = { b'00': "Normal", 12 | b'01': "< low limit", 13 | b'02': "> up limit", 14 | b'F0': "other fault"} # 80H~EFH:user defined 15 | 16 | protectState1 = { 1: "Above cell volt protect", 17 | 2: "Lower cell volt protect", 18 | 3: "Above total volt protect", 19 | 4: "Lower total volt protect", 20 | 5: "Charge current protect", 21 | 6: "Discharge current protect", 22 | 7: "Short circuit", 23 | 8: "undefined"} 24 | 25 | protectState2 = { 1: "Above charge temp protect", 26 | 2: "Above discharge temp protect", 27 | 3: "Lower charge temp protect", 28 | 4: "Lower discharge temp protect", 29 | 5: "Above MOS temp protect", 30 | 6: "Above Env temp protect", 31 | 7: "Lower Env temp protect", 32 | 8: "Fully"} 33 | 34 | instructionState = {1: "Current limit indicate ON", 35 | 2: "CFET indicate ON", 36 | 3: "DFET indicate ON", 37 | 4: "Pack indicate ON", 38 | 5: "Reverse indicate ON", 39 | 6: "ACin ON", 40 | 7: "Undefined", 41 | 8: "Heart indicate ON"} 42 | 43 | controlState = {1: "Buzzer warn function enabled", 44 | 2: "undefined", 45 | 3: "undefined", 46 | 4: "Current limit gear => low gear", 47 | 5: "Current limit function disabled", 48 | 6: "LED warn functiuon disabled", 49 | 7: "Undefined", 50 | 8: "Undefined"} 51 | 52 | faultState = {1: "Charge MOS fault", 53 | 2: "Discharge MOS fault", 54 | 3: "NTC fault (NTC)", 55 | 4: "Undefined", 56 | 5: "Cell fault", 57 | 6: "Sample fault", 58 | 7: "Undefined", 59 | 8: "Undefined"} 60 | 61 | warnState1 = {1: "Above cell volt warn", 62 | 2: "Lower cell volt warn", 63 | 3: "Above total volt warn", 64 | 4: "Lower total volt warn", 65 | 5: "Charge current warn", 66 | 6: "Discharge current warn", 67 | 7: "Undefined", 68 | 8: "Undefined"} 69 | 70 | warnState2 = {1: "Above charge temp warn", 71 | 2: "Above discharge temp warn", 72 | 3: "Low charge temp warn", 73 | 4: "Low discharge temp warn", 74 | 5: "High env temp warn", 75 | 6: "Low env temp warn", 76 | 7: "High MOS temp warn", 77 | 8: "Low power warn"} -------------------------------------------------------------------------------- /pace-bms-dev/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | bmspace: 4 | build: 5 | context: . 6 | restart: unless-stopped 7 | privileged: true 8 | volumes: 9 | - ./config.yaml:/workdir/config.yaml 10 | - /dev:/dev 11 | -------------------------------------------------------------------------------- /pace-bms-dev/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tertiush/bmspace/c756863884bad153b35330c97f107deea3b8de18/pace-bms-dev/icon.png -------------------------------------------------------------------------------- /pace-bms-dev/requirements.txt: -------------------------------------------------------------------------------- 1 | paho_mqtt==1.6.1 2 | PyYAML==6.0.1 3 | pyserial==3.5 4 | -------------------------------------------------------------------------------- /pace-bms-dev/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv bashio 2 | set -e 3 | 4 | echo "Hello BMS Pace" 5 | 6 | # cd "${0%/*}" 7 | cd /workdir 8 | python3 -u ./bms.py #"$@" -------------------------------------------------------------------------------- /pace-bms-ports.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tertiush/bmspace/c756863884bad153b35330c97f107deea3b8de18/pace-bms-ports.png -------------------------------------------------------------------------------- /repository.yaml: -------------------------------------------------------------------------------- 1 | 2 | "name": "BMS Pace addon for Home Assistant" 3 | "url": "https://github.com/Tertiush/bmspace" 4 | "maintainer": "Tertius Hyman" -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | paho_mqtt==1.6.1 2 | PyYAML==6.0.1 3 | pyserial==3.5 4 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv bashio 2 | set -e 3 | 4 | echo "Hello BMS Pace" 5 | 6 | # cd "${0%/*}" 7 | cd /workdir 8 | python3 -u ./bms.py #"$@" -------------------------------------------------------------------------------- /volta-sg1-bms-dev/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | 2 |
3 | Use at own risk!! 4 |
5 | This script excludes COMMANDS and should only retrieve data. Nonetheless the author accepts no reponsibility whatsoever of your use, in any way, of this script / addon. Again, USE AT OWN RISK! 6 |
7 |

Changelog

8 |

Development Version:

9 | For Volta Stage 1 - Adapted from BMS code base, many data disabled as mappings are completely different. 10 | 11 | 12 |

Known / possible issues

13 | The overall Pack data collected under the root MQTT topic seems to follow the data of the first battery in the Pack. -------------------------------------------------------------------------------- /volta-sg1-bms-dev/Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-alpine 2 | 3 | ENV WORK_DIR=workdir \ 4 | HASSIO_DATA_PATH=/data 5 | 6 | RUN mkdir -p ${WORK_DIR} 7 | WORKDIR /${WORK_DIR} 8 | COPY requirements.txt . 9 | 10 | # install python libraries 11 | RUN pip3 install -r requirements.txt 12 | 13 | # Copy code 14 | COPY bms.py constants.py run.sh ./ 15 | RUN chmod a+x run.sh 16 | 17 | CMD [ "sh", "./run.sh" ] 18 | -------------------------------------------------------------------------------- /volta-sg1-bms-dev/bms.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | import paho.mqtt.client as mqtt 4 | import socket 5 | import time 6 | import yaml 7 | import os 8 | import json 9 | import serial 10 | import io 11 | import json 12 | import atexit 13 | import sys 14 | import constants 15 | 16 | print("Starting up...") 17 | 18 | config = {} 19 | script_version = "" 20 | 21 | if os.path.exists('/data/options.json'): 22 | print("Loading options.json") 23 | with open(r'/data/options.json') as file: 24 | config = json.load(file) 25 | print("Config: " + json.dumps(config)) 26 | 27 | elif os.path.exists('volta-sg1-bms-dev\\config.yaml'): 28 | print("Loading config.yaml") 29 | with open(r'volta-sg1-bms-dev\\config.yaml') as file: 30 | config = yaml.load(file, Loader=yaml.FullLoader)['options'] 31 | 32 | else: 33 | sys.exit("No config file found") 34 | 35 | 36 | scan_interval = config['scan_interval'] 37 | connection_type = config['connection_type'] 38 | bms_serial = config['bms_serial'] 39 | packs_to_read = int(config['packs_to_read']) 40 | ha_discovery_enabled = config['mqtt_ha_discovery'] 41 | code_running = True 42 | bms_connected = False 43 | mqtt_connected = False 44 | print_initial = True 45 | debug_output = config['debug_output'] 46 | disc_payload = {} 47 | repub_discovery = 0 48 | 49 | bms_version = '' 50 | bms_sn = '' 51 | pack_sn = '' 52 | packs = packs_to_read 53 | cells = 13 54 | temps = 6 55 | bat_read = 1 56 | 57 | i_pack = [] 58 | v_pack = [] 59 | i_remain_cap = [] 60 | i_design_cap = [] 61 | cycles = [] 62 | i_full_cap = [] 63 | soc = [] 64 | soh = [] 65 | 66 | print("Connection Type: " + connection_type) 67 | 68 | def on_connect(client, userdata, flags, rc): 69 | print("MQTT connected with result code "+str(rc)) 70 | client.will_set(config['mqtt_base_topic'] + "/availability","offline", qos=0, retain=False) 71 | global mqtt_connected 72 | mqtt_connected = True 73 | 74 | def on_disconnect(client, userdata, rc): 75 | print("MQTT disconnected with result code "+str(rc)) 76 | global mqtt_connected 77 | mqtt_connected = False 78 | 79 | 80 | client = mqtt.Client("bmspace") 81 | client.on_connect = on_connect 82 | client.on_disconnect = on_disconnect 83 | #client.on_message = on_message 84 | 85 | client.username_pw_set(username=config['mqtt_user'], password=config['mqtt_password']) 86 | client.connect(config['mqtt_host'], config['mqtt_port'], 60) 87 | client.loop_start() 88 | time.sleep(2) 89 | 90 | def exit_handler(): 91 | print("Script exiting") 92 | client.publish(config['mqtt_base_topic'] + "/availability","offline") 93 | return 94 | 95 | atexit.register(exit_handler) 96 | 97 | def bms_connect(address, port): 98 | 99 | if connection_type == "Serial": 100 | 101 | try: 102 | print("trying to connect %s" % bms_serial) 103 | s = serial.Serial(bms_serial,timeout = 1) 104 | print("BMS serial connected") 105 | return s, True 106 | except IOError as msg: 107 | print("BMS serial error connecting: %s" % msg) 108 | return False, False 109 | 110 | else: 111 | 112 | try: 113 | print("trying to connect " + address + ":" + str(port)) 114 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 115 | s.settimeout(2) 116 | s.connect((address, port)) 117 | print("BMS socket connected") 118 | return s, True 119 | except OSError as msg: 120 | print("BMS socket error connecting: %s" % msg) 121 | return False, False 122 | 123 | def bms_sendData(comms,request=''): 124 | 125 | if connection_type == "Serial": 126 | 127 | try: 128 | if len(request) > 0: 129 | comms.write(request) 130 | time.sleep(0.25) 131 | return True 132 | except IOError as e: 133 | print("BMS serial error: %s" % e) 134 | # global bms_connected 135 | return False 136 | 137 | else: 138 | 139 | try: 140 | if len(request) > 0: 141 | comms.send(request) 142 | time.sleep(0.25) 143 | return True 144 | except Exception as e: 145 | print("BMS socket error: %s" % e) 146 | # global bms_connected 147 | return False 148 | 149 | def bms_get_data(comms): 150 | try: 151 | if connection_type == "Serial": 152 | inc_data = comms.readline() 153 | else: 154 | temp = bytes() 155 | 156 | while len(temp) == 0 or temp[-1] != 13: 157 | temp = temp + comms.recv(4096) 158 | 159 | temp2 = temp.split(b'\r') 160 | # Decide which one to take: 161 | for element in range(0,len(temp2)): 162 | SOI = hex(ord(temp2[element][0:1])) 163 | if SOI == '0x7e': 164 | inc_data = temp2[element] + b'\r' 165 | break 166 | 167 | if (len(temp2) > 2) & (debug_output > 0): 168 | print("Multiple EOIs detected") 169 | print("...for incoming data: " + str(temp) + " |Hex: " + str(temp.hex(' '))) 170 | 171 | return inc_data 172 | except Exception as e: 173 | print("BMS socket receive error: %s" % e) 174 | # global bms_connected 175 | return False 176 | 177 | def ha_discovery(): 178 | 179 | global ha_discovery_enabled 180 | global packs 181 | 182 | if ha_discovery_enabled: 183 | 184 | print("Publishing HA Discovery topic...") 185 | 186 | disc_payload['availability_topic'] = config['mqtt_base_topic'] + "/availability" 187 | 188 | device = {} 189 | device['manufacturer'] = "BMS Pace" 190 | device['model'] = "AM-x" 191 | device['identifiers'] = "bmspace_" + bms_sn 192 | device['name'] = "Generic Lithium" 193 | device['sw_version'] = bms_version 194 | disc_payload['device'] = device 195 | 196 | for p in range (1,packs+1): 197 | 198 | for i in range(0,cells): 199 | disc_payload['name'] = "Pack " + str(p) + " Cell " + str(i+1) + " Voltage" 200 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_v_cell_" + str(i+1) 201 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_cells/cell_" + str(i+1) 202 | disc_payload['unit_of_measurement'] = "mV" 203 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 204 | 205 | for i in range(0,temps): 206 | disc_payload['name'] = "Pack " + str(p) + " Temperature " + str(i+1) 207 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_temp_" + str(i+1) 208 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/temps/temp_" + str(i+1) 209 | disc_payload['unit_of_measurement'] = "°C" 210 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 211 | 212 | 213 | disc_payload['name'] = "Pack " + str(p) + " Current" 214 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_pack" 215 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_pack" 216 | disc_payload['unit_of_measurement'] = "A" 217 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 218 | 219 | disc_payload['name'] = "Pack " + str(p) + " Voltage" 220 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_v_pack" 221 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_pack" 222 | disc_payload['unit_of_measurement'] = "V" 223 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 224 | 225 | disc_payload['name'] = "Pack " + str(p) + " Remaining Capacity" 226 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_remain_cap" 227 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_remain_cap" 228 | disc_payload['unit_of_measurement'] = "mAh" 229 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 230 | 231 | disc_payload['name'] = "Pack " + str(p) + " State of Health" 232 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_soh" 233 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/soh" 234 | disc_payload['unit_of_measurement'] = "%" 235 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 236 | 237 | disc_payload['name'] = "Pack " + str(p) + " Cycles" 238 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_cycles" 239 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/cycles" 240 | disc_payload['unit_of_measurement'] = "" 241 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 242 | 243 | disc_payload['name'] = "Pack " + str(p) + " Full Capacity" 244 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_full_cap" 245 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_full_cap" 246 | disc_payload['unit_of_measurement'] = "mAh" 247 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 248 | 249 | # disc_payload['name'] = "Pack " + str(p) + " Design Capacity" 250 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_i_design_cap" 251 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_design_cap" 252 | # disc_payload['unit_of_measurement'] = "mAh" 253 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 254 | 255 | disc_payload['name'] = "Pack " + str(p) + " State of Charge" 256 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_soc" 257 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/soc" 258 | disc_payload['unit_of_measurement'] = "%" 259 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 260 | 261 | disc_payload['name'] = "Pack " + str(p) + " State of Health" 262 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_soh" 263 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/soh" 264 | disc_payload['unit_of_measurement'] = "%" 265 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 266 | 267 | 268 | disc_payload.pop('unit_of_measurement') 269 | 270 | # disc_payload['name'] = "Pack " + str(p) + " Warnings" 271 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_warnings" 272 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/warnings" 273 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 274 | 275 | # disc_payload['name'] = "Pack " + str(p) + " Balancing1" 276 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_balancing1" 277 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/balancing1" 278 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 279 | 280 | # disc_payload['name'] = "Pack " + str(p) + " Balancing2" 281 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_balancing2" 282 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/balancing2" 283 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 284 | 285 | 286 | # # Binary Sensors 287 | # disc_payload['name'] = "Pack " + str(p) + " Protection Short Circuit" 288 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_prot_short_circuit" 289 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_short_circuit" 290 | # disc_payload['payload_on'] = "1" 291 | # disc_payload['payload_off'] = "0" 292 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 293 | 294 | # disc_payload['name'] = "Pack " + str(p) + " Protection Discharge Current" 295 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_prot_discharge_current" 296 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_discharge_current" 297 | # disc_payload['payload_on'] = "1" 298 | # disc_payload['payload_off'] = "0" 299 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 300 | 301 | # disc_payload['name'] = "Pack " + str(p) + " Protection Charge Current" 302 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_prot_charge_current" 303 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_charge_current" 304 | # disc_payload['payload_on'] = "1" 305 | # disc_payload['payload_off'] = "0" 306 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 307 | 308 | # disc_payload['name'] = "Pack " + str(p) + " Current Limit" 309 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_current_limit" 310 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/current_limit" 311 | # disc_payload['payload_on'] = "1" 312 | # disc_payload['payload_off'] = "0" 313 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 314 | 315 | # disc_payload['name'] = "Pack " + str(p) + " Charge FET" 316 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_charge_fet" 317 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/charge_fet" 318 | # disc_payload['payload_on'] = "1" 319 | # disc_payload['payload_off'] = "0" 320 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 321 | 322 | # disc_payload['name'] = "Pack " + str(p) + " Discharge FET" 323 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_discharge_fet" 324 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/discharge_fet" 325 | # disc_payload['payload_on'] = "1" 326 | # disc_payload['payload_off'] = "0" 327 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 328 | 329 | # disc_payload['name'] = "Pack " + str(p) + " Pack Indicate" 330 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_pack_indicate" 331 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/pack_indicate" 332 | # disc_payload['payload_on'] = "1" 333 | # disc_payload['payload_off'] = "0" 334 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 335 | 336 | # disc_payload['name'] = "Pack " + str(p) + " Reverse" 337 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_reverse" 338 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/reverse" 339 | # disc_payload['payload_on'] = "1" 340 | # disc_payload['payload_off'] = "0" 341 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 342 | 343 | # disc_payload['name'] = "Pack " + str(p) + " AC In" 344 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_ac_in" 345 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/ac_in" 346 | # disc_payload['payload_on'] = "1" 347 | # disc_payload['payload_off'] = "0" 348 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 349 | 350 | # disc_payload['name'] = "Pack " + str(p) + " Heart" 351 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_heart" 352 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/heart" 353 | # disc_payload['payload_on'] = "1" 354 | # disc_payload['payload_off'] = "0" 355 | # client.publish(config['mqtt_ha_discovery_topic']+"/binary_sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 356 | 357 | disc_payload['name'] = "Pack " + str(p) + " Cell Max Volt Diff" 358 | disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_" + str(p) + "_cells_max_diff_calc" 359 | disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_" + str(p) + "/cells_max_diff_calc" 360 | disc_payload['unit_of_measurement'] = "mV" 361 | client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 362 | 363 | # # Pack data 364 | # disc_payload.pop('payload_on') 365 | # disc_payload.pop('payload_off') 366 | 367 | # disc_payload['name'] = "Pack Remaining Capacity" 368 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_i_remain_cap" 369 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_remain_cap" 370 | # disc_payload['unit_of_measurement'] = "mAh" 371 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 372 | 373 | # disc_payload['name'] = "Pack Full Capacity" 374 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_i_full_cap" 375 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_full_cap" 376 | # disc_payload['unit_of_measurement'] = "mAh" 377 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 378 | 379 | # disc_payload['name'] = "Pack Design Capacity" 380 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_i_design_cap" 381 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_design_cap" 382 | # disc_payload['unit_of_measurement'] = "mAh" 383 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 384 | 385 | # disc_payload['name'] = "Pack State of Charge" 386 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_soc" 387 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_soc" 388 | # disc_payload['unit_of_measurement'] = "%" 389 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 390 | 391 | # disc_payload['name'] = "Pack State of Health" 392 | # disc_payload['unique_id'] = "bmspace_" + bms_sn + "_pack_soh" 393 | # disc_payload['state_topic'] = config['mqtt_base_topic'] + "/pack_soh" 394 | # disc_payload['unit_of_measurement'] = "%" 395 | # client.publish(config['mqtt_ha_discovery_topic']+"/sensor/BMS-" + bms_sn + "/" + disc_payload['name'].replace(' ', '_') + "/config",json.dumps(disc_payload),qos=0, retain=True) 396 | 397 | else: 398 | print("HA Discovery Disabled") 399 | 400 | def chksum_calc(data): 401 | 402 | global debug_output 403 | chksum = 0 404 | 405 | try: 406 | 407 | for element in range(1, len(data)): #-5): 408 | chksum += (data[element]) 409 | 410 | chksum = chksum % 65536 411 | chksum = '{0:016b}'.format(chksum) 412 | 413 | flip_bits = '' 414 | for i in chksum: 415 | if i == '0': 416 | flip_bits += '1' 417 | else: 418 | flip_bits += '0' 419 | 420 | chksum = flip_bits 421 | chksum = int(chksum,2)+1 422 | 423 | chksum = format(chksum, 'X') 424 | 425 | except Exception as e: 426 | if debug_output > 0: 427 | print("Error calculating CHKSUM using data: " + data) 428 | print("Error details: ", str(e)) 429 | return(False) 430 | 431 | return(chksum) 432 | 433 | def cid2_rtn(rtn): 434 | 435 | # RTN Reponse codes, looking for errors 436 | if rtn == b'00': 437 | return False, False 438 | elif rtn == b'01': 439 | return True, "RTN Error 01: Undefined RTN error" 440 | elif rtn == b'02': 441 | return True, "RTN Error 02: CHKSUM error" 442 | elif rtn == b'03': 443 | return True, "RTN Error 03: LCHKSUM error" 444 | elif rtn == b'04': 445 | return True, "RTN Error 04: CID2 undefined" 446 | elif rtn == b'05': 447 | return True, "RTN Error 05: Undefined error" 448 | elif rtn == b'06': 449 | return True, "RTN Error 06: Undefined error" 450 | elif rtn == b'09': 451 | return True, "RTN Error 09: Operation or write error" 452 | else: 453 | return False, False 454 | 455 | def bms_parse_data(inc_data): 456 | 457 | global debug_output 458 | 459 | #inc_data = b'~25014600D0F40002100DD50DBC0DD70DD70DD40DD70DD20DD50DD30DD60DC10DD40DD50DD70DD30DD5060B760B710B700B7A0B7D0B9D0000DD2326A90226AC011126AC64100DD30DBD0DD40DC60DD50DD40DD50DD50DD60DD60DD40DD20DD30\r' 460 | 461 | try: 462 | 463 | SOI = hex(ord(inc_data[0:1])) 464 | if SOI != '0x7e': 465 | return(False,"Incorrect starting byte for incoming data") 466 | 467 | if debug_output > 1: 468 | print("SOI: ", SOI) 469 | print("VER: ", inc_data[1:3]) 470 | print("ADR: ", inc_data[3:5]) 471 | print("CID1 (Type): ", inc_data[5:7]) 472 | 473 | RTN = inc_data[7:9] 474 | error, info = cid2_rtn(RTN) 475 | if error: 476 | print(error) 477 | raise Exception(error) 478 | 479 | LCHKSUM = inc_data[9] 480 | 481 | if debug_output > 1: 482 | print("RTN: ", RTN) 483 | print("LENGTH: ", inc_data[9:13]) 484 | print(" - LCHKSUM: ", LCHKSUM) 485 | print(" - LENID: ", inc_data[10:13]) 486 | 487 | LENID = int(inc_data[10:13],16) #amount of bytes, i.e. 2x hex 488 | 489 | calc_LCHKSUM = lchksum_calc(inc_data[10:13]) 490 | if calc_LCHKSUM == False: 491 | return(False,"Error calculating LCHKSUM for incoming data") 492 | 493 | if LCHKSUM != ord(calc_LCHKSUM): 494 | if debug_output > 0: 495 | print("LCHKSUM received: " + str(LCHKSUM) + " does not match calculated: " + str(ord(calc_LCHKSUM))) 496 | return(False,"LCHKSUM received: " + str(LCHKSUM) + " does not match calculated: " + str(ord(calc_LCHKSUM))) 497 | 498 | if debug_output > 1: 499 | print(" - LENID (int): ", LENID) 500 | 501 | INFO = inc_data[13:13+LENID] 502 | 503 | if debug_output > 1: 504 | print("INFO: ", INFO) 505 | 506 | CHKSUM = inc_data[13+LENID:13+LENID+4] 507 | 508 | if debug_output > 1: 509 | print("CHKSUM: ", CHKSUM) 510 | #print("EOI: ", hex(inc_data[13+LENID+4])) 511 | 512 | calc_CHKSUM = chksum_calc(inc_data[:len(inc_data)-5]) 513 | 514 | 515 | if debug_output > 1: 516 | print("Calc CHKSUM: ", calc_CHKSUM) 517 | except Exception as e: 518 | if debug_output > 0: 519 | print("Error1 calculating CHKSUM using data: ", inc_data) 520 | return(False,"Error1 calculating CHKSUM: " + str(e)) 521 | 522 | if calc_CHKSUM == False: 523 | if debug_output > 0: 524 | print("Error2 calculating CHKSUM using data: ", inc_data) 525 | return(False,"Error2 calculating CHKSUM") 526 | 527 | if CHKSUM.decode("ASCII") == calc_CHKSUM: 528 | return(True,INFO) 529 | else: 530 | if debug_output > 0: 531 | print("Received and calculated CHKSUM does not match: Received: " + CHKSUM.decode("ASCII") + ", Calculated: " + calc_CHKSUM) 532 | print("...for incoming data: " + str(inc_data) + " |Hex: " + str(inc_data.hex(' '))) 533 | print("Length of incoming data as measured: " + str(len(inc_data))) 534 | print("SOI: ", SOI) 535 | print("VER: ", inc_data[1:3]) 536 | print("ADR: ", inc_data[3:5]) 537 | print("CID1 (Type): ", inc_data[5:7]) 538 | print("RTN (decode!): ", RTN) 539 | print("LENGTH: ", inc_data[9:13]) 540 | print(" - LCHKSUM: ", inc_data[9]) 541 | print(" - LENID: ", inc_data[10:13]) 542 | print(" - LENID (int): ", int(inc_data[10:13],16)) 543 | print("INFO: ", INFO) 544 | print("CHKSUM: ", CHKSUM) 545 | #print("EOI: ", hex(inc_data[13+LENID+4])) 546 | return(False,"Checksum error") 547 | 548 | def lchksum_calc(lenid): 549 | 550 | chksum = 0 551 | 552 | try: 553 | 554 | # for element in range(1, len(lenid)): #-5): 555 | # chksum += (lenid[element]) 556 | 557 | for element in range(0, len(lenid)): 558 | chksum += int(chr(lenid[element]),16) 559 | 560 | chksum = chksum % 16 561 | chksum = '{0:04b}'.format(chksum) 562 | 563 | flip_bits = '' 564 | for i in chksum: 565 | if i == '0': 566 | flip_bits += '1' 567 | else: 568 | flip_bits += '0' 569 | 570 | chksum = flip_bits 571 | chksum = int(chksum,2) 572 | 573 | chksum += 1 574 | 575 | if chksum > 15: 576 | chksum = 0 577 | 578 | chksum = format(chksum, 'X') 579 | 580 | except: 581 | 582 | print("Error calculating LCHKSUM using LENID: ", lenid) 583 | return(False) 584 | 585 | return(chksum) 586 | 587 | def bms_request(bms, adr,cid1=b"\x34\x36",cid2=b"\x43\x31",info=b"",LENID=False): 588 | # adr=b"\x30\x31" 589 | 590 | global bms_connected 591 | global debug_output 592 | 593 | request = b'\x7e' 594 | request += b"\x32\x31" #ver 595 | request += adr 596 | request += cid1 597 | request += cid2 598 | 599 | if not(LENID): 600 | LENID = len(info) 601 | #print("Length: ", LENID) 602 | LENID = bytes(format(LENID, '03X'), "ASCII") 603 | 604 | #print("LENID: ", LENID) 605 | 606 | if LENID == b'000': 607 | LCHKSUM = '0' 608 | else: 609 | LCHKSUM = lchksum_calc(LENID) 610 | if LCHKSUM == False: 611 | return(False,"Error calculating LCHKSUM)") 612 | #print("LCHKSUM: ", LCHKSUM) 613 | request += bytes(LCHKSUM, "ASCII") 614 | request += LENID 615 | request += info 616 | CHKSUM = bytes(chksum_calc(request), "ASCII") 617 | if CHKSUM == False: 618 | return(False,"Error calculating CHKSUM)") 619 | request += CHKSUM 620 | request += b'\x0d' 621 | 622 | if debug_output > 2: 623 | print("-> Outgoing Data: ", request) 624 | 625 | if not bms_sendData(bms,request): 626 | bms_connected = False 627 | print("Error, connection to BMS lost") 628 | return(False,"Error, connection to BMS lost") 629 | 630 | inc_data = bms_get_data(bms) 631 | 632 | if inc_data == False: 633 | print("Error retrieving data from BMS") 634 | return(False,"Error retrieving data from BMS") 635 | 636 | if debug_output > 2: 637 | print("<- Incoming data: ", inc_data) 638 | 639 | success, INFO = bms_parse_data(inc_data) 640 | 641 | return(success, INFO) 642 | 643 | def bms_getPackNumber(bms): 644 | 645 | success, INFO = bms_request(bms,cid2=constants.cid2PackNumber) 646 | 647 | if success == False: 648 | return(False,INFO) 649 | 650 | try: 651 | packNumber = int(INFO,16) 652 | except: 653 | print("Error extracting total battery count in pack") 654 | return(False,"Error extracting total battery count in pack") 655 | 656 | return(success,packNumber) 657 | 658 | def bms_getVersion(comms): 659 | 660 | global bms_version 661 | 662 | success, INFO = bms_request(bms,cid2=constants.cid2SoftwareVersion) 663 | 664 | if success == False: 665 | return(False,INFO) 666 | 667 | try: 668 | 669 | bms_version = bytes.fromhex(INFO.decode("ascii")).decode("ASCII") 670 | client.publish(config['mqtt_base_topic'] + "/bms_version",bms_version) 671 | print("BMS Version: " + bms_version) 672 | except: 673 | return(False,"Error extracting BMS version") 674 | 675 | return(success,bms_version) 676 | 677 | def bms_getSerial(comms): 678 | 679 | global bms_sn 680 | global pack_sn 681 | 682 | success, INFO = bms_request(bms,cid2=constants.cid2SerialNumber) 683 | 684 | if success == False: 685 | print("Error: " + INFO) 686 | return(False,INFO, False) 687 | 688 | try: 689 | 690 | bms_sn = bytes.fromhex(INFO[0:30].decode("ascii")).decode("ASCII").replace(" ", "") #Remove spaces to prevent the unique ID having spaces 691 | pack_sn = bytes.fromhex(INFO[40:68].decode("ascii")).decode("ASCII").replace(" ", "") 692 | client.publish(config['mqtt_base_topic'] + "/bms_sn",bms_sn) 693 | client.publish(config['mqtt_base_topic'] + "/pack_sn",pack_sn) 694 | print("BMS Serial Number: " + bms_sn) 695 | print("Pack Serial Number: " + pack_sn) 696 | 697 | except: 698 | return(False,"Error extracting BMS version", False) 699 | 700 | return(success,bms_sn,pack_sn) 701 | 702 | def bms_getAnalogData(bms,adr,batNumber): 703 | 704 | global print_initial 705 | global cells 706 | global temps 707 | global packs 708 | byte_index = 0 709 | 710 | 711 | p = adr 712 | battery = bytes(format(batNumber, '02X'), 'ASCII') 713 | adr = bytes(format(adr, '02X'), 'ASCII') 714 | 715 | if debug_output > 1: 716 | print("Reading Pack: ", p) 717 | 718 | 719 | success, inc_data = bms_request(bms,adr,cid2=constants.cid2PackAnalogData,info=battery) 720 | 721 | #bms_request -> bms_get_data(inc_data/INFO = bms_parse_data) 722 | 723 | if success == False: 724 | return(False,inc_data) 725 | 726 | try: 727 | 728 | byte_index = 2 729 | 730 | v_cell = {} 731 | t_cell = {} 732 | 733 | if p > 1: 734 | cells_prev = cells 735 | 736 | cells = int(inc_data[byte_index:byte_index+2],16) 737 | 738 | if print_initial: 739 | print("Pack " + str(p) + ", Total cells: " + str(cells)) 740 | byte_index += 2 741 | 742 | cell_min_volt = 0 743 | cell_max_volt = 0 744 | 745 | for i in range(0,cells): 746 | v_cell[(p-1,i)] = int(inc_data[byte_index:byte_index+4],16) 747 | byte_index += 4 748 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_cells/cell_" + str(i+1) ,str(v_cell[(p-1,i)])) 749 | if print_initial: 750 | print("Pack " + str(p) +", V Cell" + str(i+1) + ": " + str(v_cell[(p-1,i)]) + " mV") 751 | 752 | #Calculate cell max and min volt 753 | if i == 0: 754 | cell_min_volt = v_cell[(p-1,i)] 755 | cell_max_volt = v_cell[(p-1,i)] 756 | else: 757 | if v_cell[(p-1,i)] < cell_min_volt: 758 | cell_min_volt = v_cell[(p-1,i)] 759 | if v_cell[(p-1,i)] > cell_max_volt: 760 | cell_max_volt = v_cell[(p-1,i)] 761 | 762 | #Calculate cells max diff volt 763 | cell_max_diff_volt = cell_max_volt - cell_min_volt 764 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/cells_max_diff_calc" ,str(cell_max_diff_volt)) 765 | if print_initial: 766 | print("Pack " + str(p) +", Cell Max Diff Volt Calc: " + str(cell_max_diff_volt) + " mV") 767 | 768 | temps = int(inc_data[byte_index:byte_index + 2],16) 769 | if print_initial: 770 | print("Pack " + str(p) + ", Total temperature sensors: " + str(temps)) 771 | byte_index += 2 772 | 773 | for i in range(0,temps): #temps-2 774 | t_cell[(p-1,i)] = int(inc_data[byte_index:byte_index + 4],16) -40 775 | byte_index += 4 776 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/temps/temp_" + str(i+1) ,str(round(t_cell[(p-1,i)],1))) 777 | if print_initial: 778 | print("Pack " + str(p) + ", Temp" + str(i+1) + ": " + str(round(t_cell[(p-1,i)],1)) + " ℃") 779 | 780 | # t_mos= (int(inc_data[byte_index:byte_index+4],16))/160-273 781 | # client.publish(config['mqtt_base_topic'] + "/t_mos",str(round(t_mos,1))) 782 | # if print_initial: 783 | # print("T Mos: " + str(t_mos) + " Deg") 784 | 785 | # t_env= (int(inc_data[byte_index:byte_index+4],16))/160-273 786 | # client.publish(config['mqtt_base_topic'] + "/t_env",str(round(t_env,1))) 787 | # offset += 7 788 | # if print_initial: 789 | # print("T Env: " + str(t_env) + " Deg") 790 | 791 | i_pack.append(int(inc_data[byte_index:byte_index+4],16)) 792 | byte_index += 4 793 | if i_pack[p-1] >= 32768: 794 | i_pack[p-1] = -1*(65535 - i_pack[p-1]) 795 | i_pack[p-1] = i_pack[p-1]/100 796 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_pack",str(i_pack[p-1])) 797 | if print_initial: 798 | print("Pack " + str(p) + ", I Pack: " + str(i_pack[p-1]) + " A") 799 | 800 | v_pack.append(int(inc_data[byte_index:byte_index+4],16)/100) 801 | byte_index += 4 802 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/v_pack",str(v_pack[p-1])) 803 | if print_initial: 804 | print("Pack " + str(p) + ", V Pack: " + str(v_pack[p-1]) + " V") 805 | 806 | i_remain_cap.append(int(inc_data[byte_index:byte_index+4],16)*10) 807 | byte_index += 4 808 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_remain_cap",str(i_remain_cap[p-1])) 809 | if print_initial: 810 | print("Pack " + str(p) + ", I Remaining Capacity: " + str(i_remain_cap[p-1]) + " mAh") 811 | 812 | byte_index += 2 # Manual: Define number P = 3 813 | 814 | i_full_cap.append(int(inc_data[byte_index:byte_index+4],16)*10) 815 | byte_index += 4 816 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_full_cap",str(i_full_cap[p-1])) 817 | if print_initial: 818 | print("Pack " + str(p) + ", I Full Capacity: " + str(i_full_cap[p-1]) + " mAh") 819 | 820 | cycles.append(int(inc_data[byte_index:byte_index+4],16)) 821 | byte_index += 4 822 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/cycles",str(cycles[p-1])) 823 | if print_initial: 824 | print("Pack " + str(p) + ", Cycles: " + str(cycles[p-1])) 825 | 826 | soc.append(int(inc_data[byte_index:byte_index+2],16)) 827 | byte_index += 2 828 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/soc",str(soc[p-1])) 829 | if print_initial: 830 | print("Pack " + str(p) + ", SOC: " + str(soc[p-1]) + " %") 831 | 832 | # i_design_cap.append(int(inc_data[byte_index:byte_index+4],16)*10) 833 | # byte_index += 4 834 | # client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/i_design_cap",str(i_design_cap[p-1])) 835 | # if print_initial: 836 | # print("Pack " + str(p) + ", Design Capacity: " + str(i_design_cap[p-1]) + " mAh") 837 | 838 | soh.append(int(inc_data[byte_index:byte_index+2],16)) 839 | byte_index += 2 840 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/soh",str(soh[p-1])) 841 | if print_initial: 842 | print("Pack " + str(p) + ", SOH: " + str(soh[p-1]) + " %") 843 | 844 | 845 | except Exception as e: 846 | print("Error parsing BMS analog data: ", str(e)) 847 | return(False,"Error parsing BMS analog data: " + str(e)) 848 | 849 | if print_initial: 850 | print("Script running....") 851 | 852 | return True,True 853 | 854 | def bms_getPackCapacity(bms): 855 | 856 | byte_index = 0 857 | 858 | success, inc_data = bms_request(bms,cid2=constants.cid2PackCapacity) # Seem to always reply with pack 1 data, even with ADR= 0 or FF and INFO= '' or FF 859 | 860 | if success == False: 861 | return(False,inc_data) 862 | 863 | try: 864 | 865 | pack_remain_cap = int(inc_data[byte_index:byte_index+4],16)*10 866 | byte_index += 4 867 | client.publish(config['mqtt_base_topic'] + "/pack_remain_cap",str(pack_remain_cap)) 868 | if print_initial: 869 | print("Pack Remaining Capacity: " + str(pack_remain_cap) + " mAh") 870 | 871 | pack_full_cap = int(inc_data[byte_index:byte_index+4],16)*10 872 | byte_index += 4 873 | client.publish(config['mqtt_base_topic'] + "/pack_full_cap",str(pack_full_cap)) 874 | if print_initial: 875 | print("Pack Full Capacity: " + str(pack_full_cap) + " mAh") 876 | 877 | pack_design_cap = int(inc_data[byte_index:byte_index+4],16)*10 878 | byte_index += 4 879 | client.publish(config['mqtt_base_topic'] + "/pack_design_cap",str(pack_design_cap)) 880 | if print_initial: 881 | print("Pack Design Capacity: " + str(pack_design_cap) + " mAh") 882 | 883 | pack_soc = round(pack_remain_cap/pack_full_cap*100,2) 884 | client.publish(config['mqtt_base_topic'] + "/pack_soc",str(pack_soc)) 885 | if print_initial: 886 | print("Pack SOC: " + str(pack_soc) + " %") 887 | 888 | pack_soh = round(pack_full_cap/pack_design_cap*100,2) 889 | client.publish(config['mqtt_base_topic'] + "/pack_soh",str(pack_soh)) 890 | if print_initial: 891 | print("Pack SOH: " + str(pack_soh) + " %") 892 | 893 | except Exception as e: 894 | print("Error parsing BMS pack capacity data: ", str(e)) 895 | return False, "Error parsing BMS pack capacity data: " + str(e) 896 | 897 | return True,True 898 | 899 | def bms_getWarnInfo(bms,adr,batNumber): 900 | 901 | byte_index = 2 902 | packsW = 1 903 | warnings = "" 904 | 905 | p = adr 906 | adr = bytes(format(adr, '02X'), 'ASCII') 907 | battery = bytes(format(batNumber, '02X'), 'ASCII') 908 | 909 | success, inc_data = bms_request(bms,adr,cid2=constants.cid2WarnInfo,info=battery) 910 | 911 | if success == False: 912 | return(False,inc_data) 913 | 914 | #inc_data = b'000210000000000000000000000000000000000600000000000000000000000E0000000000001110000000000000000000000000000000000600000000000000000000000E00000000000000' 915 | 916 | 917 | try: 918 | 919 | packsW = int(inc_data[byte_index:byte_index+2],16) 920 | if print_initial: 921 | print("Packs for warnings: " + str(packs)) 922 | byte_index += 2 923 | 924 | cellsW = int(inc_data[byte_index:byte_index+2],16) 925 | byte_index += 2 926 | 927 | for c in range(1,cellsW+1): 928 | 929 | if inc_data[byte_index:byte_index+2] != b'00': 930 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 931 | warnings += "cell " + str(c) + " " + warn + ", " 932 | byte_index += 2 933 | 934 | tempsW = int(inc_data[byte_index:byte_index+2],16) 935 | byte_index += 2 936 | 937 | for t in range(1,tempsW+1): 938 | 939 | if inc_data[byte_index:byte_index+2] != b'00': 940 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 941 | warnings += "temp " + str(t) + " " + warn + ", " 942 | byte_index += 2 943 | 944 | if inc_data[byte_index:byte_index+2] != b'00': 945 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 946 | warnings += "charge current " + warn + ", " 947 | byte_index += 2 948 | 949 | if inc_data[byte_index:byte_index+2] != b'00': 950 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 951 | warnings += "total voltage " + warn + ", " 952 | byte_index += 2 953 | 954 | if inc_data[byte_index:byte_index+2] != b'00': 955 | warn = constants.warningStates[inc_data[byte_index:byte_index+2]] 956 | warnings += "discharge current " + warn + ", " 957 | byte_index += 2 958 | 959 | protectState1 = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 960 | if protectState1 > 0: 961 | warnings += "Protection State 1: " 962 | for x in range(0,8): 963 | if (protectState1 & (1<>6 & 1)) 968 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_discharge_current",str(protectState1>>5 & 1)) 969 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/prot_charge_current",str(protectState1>>4 & 1)) 970 | byte_index += 2 971 | 972 | protectState2 = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 973 | if protectState2 > 0: 974 | warnings += "Protection State 2: " 975 | for x in range(0,8): 976 | if (protectState2 & (1<>7 & 1)) 981 | byte_index += 2 982 | 983 | # instructionState = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 984 | # if instructionState > 0: 985 | # warnings += "Instruction State: " 986 | # for x in range(0,8): 987 | # if (instructionState & (1<>0 & 1)) 995 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/charge_fet",str(instructionState>>1 & 1)) 996 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/discharge_fet",str(instructionState>>2 & 1)) 997 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/pack_indicate",str(instructionState>>3 & 1)) 998 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/reverse",str(instructionState>>4 & 1)) 999 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/ac_in",str(instructionState>>5 & 1)) 1000 | client.publish(config['mqtt_base_topic'] + "/pack_" + str(p) + "/heart",str(instructionState>>7 & 1)) 1001 | byte_index += 2 1002 | 1003 | controlState = ord(bytes.fromhex(inc_data[byte_index:byte_index+2].decode('ascii'))) 1004 | if controlState > 0: 1005 | warnings += "Control State: " 1006 | for x in range(0,8): 1007 | if (controlState & (1< 0: 1015 | warnings += "Fault State: " 1016 | for x in range(0,8): 1017 | if (faultState & (1< 0: 1031 | warnings += "Warning State 1: " 1032 | for x in range(0,8): 1033 | if (warnState1 & (1< 0: 1041 | warnings += "Warning State 2: " 1042 | for x in range(0,8): 1043 | if (warnState2 & (1< packs_to_read: 1103 | bat_read = 1 1104 | i_pack = [] 1105 | v_pack = [] 1106 | i_remain_cap = [] 1107 | i_design_cap = [] 1108 | cycles = [] 1109 | i_full_cap = [] 1110 | soc = [] 1111 | soh = [] 1112 | 1113 | success, data = bms_getAnalogData(bms,bat_read,batNumber=255) 1114 | if success != True: 1115 | print("Error retrieving BMS analog data: " + data) 1116 | time.sleep(scan_interval/2) 1117 | 1118 | # success, data = bms_getPackCapacity(bms) 1119 | # if success != True: 1120 | # print("Error retrieving BMS pack capacity: " + data) 1121 | # time.sleep(scan_interval/3) 1122 | # success, data = bms_getWarnInfo(bms,bat_read,batNumber=255) 1123 | # if success != True: 1124 | # print("Error retrieving BMS warning info: " + data) 1125 | # time.sleep(scan_interval/3) 1126 | 1127 | bat_read = bat_read + 1 1128 | 1129 | if print_initial: 1130 | ha_discovery() 1131 | 1132 | client.publish(config['mqtt_base_topic'] + "/availability","online") 1133 | 1134 | print_initial = False 1135 | 1136 | 1137 | repub_discovery += 1 1138 | if repub_discovery*scan_interval > 3600: 1139 | repub_discovery = 0 1140 | print_initial = True 1141 | 1142 | else: #MQTT not connected 1143 | client.loop_stop() 1144 | print("MQTT disconnected, trying to reconnect...") 1145 | client.connect(config['mqtt_host'], config['mqtt_port'], 60) 1146 | client.loop_start() 1147 | time.sleep(5) 1148 | print_initial = True 1149 | else: #BMS not connected 1150 | print("BMS disconnected, trying to reconnect...") 1151 | bms,bms_connected = bms_connect(config['bms_ip'],config['bms_port']) 1152 | client.publish(config['mqtt_base_topic'] + "/availability","offline") 1153 | time.sleep(5) 1154 | print_initial = True 1155 | 1156 | client.loop_stop() 1157 | -------------------------------------------------------------------------------- /volta-sg1-bms-dev/config.yaml: -------------------------------------------------------------------------------- 1 | name: "BMS Volta V2.1 - Development" 2 | description: "Volta V2.1 BMS Interface" 3 | version: "2.2.5dev" 4 | slug: "bms_volta_dev" 5 | url: "https://github.com/Tertiush/bmspace/volta-sg1-bms-dev" 6 | init: false 7 | arch: 8 | - aarch64 9 | - amd64 10 | - armhf 11 | - armv7 12 | - i386 13 | 14 | uart: true 15 | usb: true 16 | 17 | options: 18 | mqtt_host: "192.168.0.15" 19 | mqtt_port: 1883 20 | mqtt_user: "mqtt-users" 21 | mqtt_password: "mqtt-users" 22 | mqtt_ha_discovery: true 23 | mqtt_ha_discovery_topic: "homeassistant" 24 | mqtt_base_topic: "bmspace" 25 | connection_type: "IP" 26 | bms_ip: "192.168.0.22" 27 | bms_port: 5000 28 | bms_serial: "/dev/ttyUSB0" 29 | scan_interval: 5 30 | debug_output: 0 31 | packs_to_read: 1 32 | force_pack_offset: 0 33 | schema: 34 | mqtt_host: str 35 | mqtt_port: int 36 | mqtt_user: str 37 | mqtt_password: str 38 | mqtt_ha_discovery: bool 39 | mqtt_ha_discovery_topic: str 40 | mqtt_base_topic: str 41 | connection_type: list(IP|Serial) 42 | bms_ip: str 43 | bms_port: int 44 | bms_serial: str 45 | scan_interval: int 46 | debug_output: int 47 | packs_to_read: int 48 | force_pack_offset: "int?" 49 | -------------------------------------------------------------------------------- /volta-sg1-bms-dev/constants.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | cid2PackNumber = b"\x39\x30" # 0x90 4 | cid2PackAnalogData = b"\x34\x32" # 0x42 5 | cid2SoftwareVersion = b"\x43\x31" # 0xC1 6 | cid2SerialNumber = b"\x43\x32" # 0xC2 7 | cid2PackCapacity = b"\x41\x36" # 0xA6 8 | cid2WarnInfo = b"\x34\x34" # 0x44 9 | 10 | 11 | warningStates = { b'00': "Normal", 12 | b'01': "< low limit", 13 | b'02': "> up limit", 14 | b'F0': "other fault"} # 80H~EFH:user defined 15 | 16 | protectState1 = { 1: "Above cell volt protect", 17 | 2: "Lower cell volt protect", 18 | 3: "Above total volt protect", 19 | 4: "Lower total volt protect", 20 | 5: "Charge current protect", 21 | 6: "Discharge current protect", 22 | 7: "Short circuit", 23 | 8: "undefined"} 24 | 25 | protectState2 = { 1: "Above charge temp protect", 26 | 2: "Above discharge temp protect", 27 | 3: "Lower charge temp protect", 28 | 4: "Lower discharge temp protect", 29 | 5: "Above MOS temp protect", 30 | 6: "Above Env temp protect", 31 | 7: "Lower Env temp protect", 32 | 8: "Fully"} 33 | 34 | instructionState = {1: "Current limit indicate ON", 35 | 2: "CFET indicate ON", 36 | 3: "DFET indicate ON", 37 | 4: "Pack indicate ON", 38 | 5: "Reverse indicate ON", 39 | 6: "ACin ON", 40 | 7: "Undefined", 41 | 8: "Heart indicate ON"} 42 | 43 | controlState = {1: "Buzzer warn function enabled", 44 | 2: "undefined", 45 | 3: "undefined", 46 | 4: "Current limit gear => low gear", 47 | 5: "Current limit function disabled", 48 | 6: "LED warn functiuon disabled", 49 | 7: "Undefined", 50 | 8: "Undefined"} 51 | 52 | faultState = {1: "Charge MOS fault", 53 | 2: "Discharge MOS fault", 54 | 3: "NTC fault (NTC)", 55 | 4: "Undefined", 56 | 5: "Cell fault", 57 | 6: "Sample fault", 58 | 7: "Undefined", 59 | 8: "Undefined"} 60 | 61 | warnState1 = {1: "Above cell volt warn", 62 | 2: "Lower cell volt warn", 63 | 3: "Above total volt warn", 64 | 4: "Lower total volt warn", 65 | 5: "Charge current warn", 66 | 6: "Discharge current warn", 67 | 7: "Undefined", 68 | 8: "Undefined"} 69 | 70 | warnState2 = {1: "Above charge temp warn", 71 | 2: "Above discharge temp warn", 72 | 3: "Low charge temp warn", 73 | 4: "Low discharge temp warn", 74 | 5: "High env temp warn", 75 | 6: "Low env temp warn", 76 | 7: "High MOS temp warn", 77 | 8: "Low power warn"} -------------------------------------------------------------------------------- /volta-sg1-bms-dev/docker-compose.yaml: -------------------------------------------------------------------------------- 1 | version: '3' 2 | services: 3 | bmspace: 4 | build: 5 | context: . 6 | restart: unless-stopped 7 | privileged: true 8 | volumes: 9 | - ./config.yaml:/workdir/config.yaml 10 | - /dev:/dev 11 | -------------------------------------------------------------------------------- /volta-sg1-bms-dev/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Tertiush/bmspace/c756863884bad153b35330c97f107deea3b8de18/volta-sg1-bms-dev/icon.png -------------------------------------------------------------------------------- /volta-sg1-bms-dev/requirements.txt: -------------------------------------------------------------------------------- 1 | paho_mqtt==1.6.1 2 | PyYAML==6.0.1 3 | pyserial==3.5 4 | -------------------------------------------------------------------------------- /volta-sg1-bms-dev/run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/with-contenv bashio 2 | set -e 3 | 4 | echo "Hello BMS Pace" 5 | 6 | # cd "${0%/*}" 7 | cd /workdir 8 | python3 -u ./bms.py #"$@" --------------------------------------------------------------------------------