├── .gitignore
├── LICENSE
├── README.md
├── components
└── twc-controller
│ ├── __init__.py
│ ├── functions.cpp
│ ├── functions.h
│ ├── io.h
│ ├── twc_connector.cpp
│ ├── twc_connector.h
│ ├── twc_controller.cpp
│ ├── twc_controller.h
│ ├── twc_protocol.cpp
│ └── twc_protocol.h
└── twc.yaml
/.gitignore:
--------------------------------------------------------------------------------
1 | __pycache__/
2 |
3 | # Ignore vim recovery files
4 | .*.swp
5 |
6 |
--------------------------------------------------------------------------------
/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 | # TWC Controller
2 |
3 | This is an [esphome](https://esphome.io) external component of the Tesla Wall Connector Gen2 controller which was previously a standalone Arduino application (https://github.com/jnicolson/twc-controller). The change to esphome means no more worrying about the boilerplate type setup of Wifi, Over the air updates, MQTT connections, etc. Instead the focus just becomes on the Tesla load sharing protocol.
4 |
5 | Credit goes to [WinterDragoness](https://teslamotorsclub.com/tmc/members/winterdragoness.40930/) from the Tesla Motor Club forums for figuring out the protocol (with many others in the forum also giving help) and [Craig 128](https://teslamotorsclub.com/tmc/members/craig-128.113283/) for the original C code I used as a reference. Both their projects are linked in the links section below - without both of them this wouldn't have been possible.
6 |
7 | ## Features
8 |
9 | This is designed to work with Home Assistant by exposing a single controllable number - the current to make available to the charger. This can be automated in Home Assistant based on whatever data is available in Home Assistant (i.e. time of day, solar availability).
10 |
11 | The charger also exposes many sensors for Voltage, Current, kWh provided over the lifetime, serial number, connected VIN. These are all visible in the example YAML file twc.yaml.
12 |
13 | ## Hardware
14 |
15 | This should run on any ESP32 based board with an RS485 transceiver which supports reading and writing. This code is tested on a custom board with hardware design available at https://github.com/jnicolson/TWCController
16 |
17 | ## Installation
18 |
19 | Included in this repository is an example esphome yaml file. This assumes:
20 | * Secondary UART connected to GPIO5 and GPIO19 (update as required)
21 | * RS485 Receive Enable connected to GPIO18
22 |
23 | ## Other Projects
24 |
25 | * [TWC](https://github.com/craigpeacock/TWC)
26 | * [TWCManager](https://github.com/ngardiner/TWCManager)
27 | * [TWCManager (original)](https://github.com/dracoventions/TWCManager)
28 |
--------------------------------------------------------------------------------
/components/twc-controller/__init__.py:
--------------------------------------------------------------------------------
1 | import esphome.codegen as cg
2 | import esphome.config_validation as cv
3 | from esphome.cpp_helpers import gpio_pin_expression
4 | from esphome import pins
5 | from esphome.components import (
6 | number,
7 | sensor,
8 | text_sensor,
9 | uart,
10 | )
11 |
12 | from esphome.const import (
13 | CONF_ID,
14 | CONF_NAME,
15 | CONF_STEP,
16 | CONF_RESTORE_VALUE,
17 | CONF_UNIT_OF_MEASUREMENT,
18 | CONF_CURRENT,
19 | CONF_STATE,
20 | CONF_FLOW_CONTROL_PIN,
21 |
22 | UNIT_AMPERE,
23 | UNIT_KILOWATT_HOURS,
24 | UNIT_VOLT,
25 |
26 | DEVICE_CLASS_CURRENT,
27 | DEVICE_CLASS_ENERGY,
28 | DEVICE_CLASS_VOLTAGE,
29 |
30 | STATE_CLASS_MEASUREMENT,
31 | STATE_CLASS_TOTAL_INCREASING,
32 | )
33 |
34 | CONF_MAX_ALLOWABLE_CURRENT = "max_allowable_current"
35 | CONF_TOTAL_KWH = "total_kwh_delivered"
36 | CONF_SERIAL = "serial"
37 | CONF_PHASE_1_VOLTAGE = "phase_1_voltage"
38 | CONF_PHASE_2_VOLTAGE = "phase_2_voltage"
39 | CONF_PHASE_3_VOLTAGE = "phase_3_voltage"
40 | CONF_PHASE_1_CURRENT = "phase_1_current"
41 | CONF_PHASE_2_CURRENT = "phase_2_current"
42 | CONF_PHASE_3_CURRENT = "phase_3_current"
43 | CONF_FIRMWARE_VERSION = "firmware_version"
44 | CONF_ACTUAL_CURRENT = "actual_current"
45 | CONF_VIN = "connected_vin"
46 | CONF_PASSIVE_MODE = "passive_mode"
47 |
48 | CONF_MIN_CURRENT = "min_current"
49 | CONF_MAX_CURRENT = "max_current"
50 | CONF_SET_CURRENT = "set_current"
51 | CONF_TWCID = "twc_id"
52 |
53 | ICON_CURRENT_AC = "mdi:current-ac"
54 | ICON_CAR = "mdi:car"
55 | ICON_NUMERIC = "mdi:numeric"
56 | ICON_LIGHTNING_BOLT = "mdi:lightning-bolt"
57 |
58 | AUTO_LOAD = ["number", "sensor", "text_sensor"]
59 | DEPENDENCIES = ["uart"]
60 |
61 | TEXT_TYPES = [
62 | CONF_SERIAL,
63 | CONF_FIRMWARE_VERSION,
64 | CONF_VIN
65 | ]
66 |
67 | TYPES = [
68 | CONF_MAX_ALLOWABLE_CURRENT,
69 | CONF_CURRENT,
70 | CONF_STATE,
71 | CONF_TOTAL_KWH,
72 | CONF_PHASE_1_VOLTAGE,
73 | CONF_PHASE_2_VOLTAGE,
74 | CONF_PHASE_3_VOLTAGE,
75 | CONF_PHASE_1_CURRENT,
76 | CONF_PHASE_2_CURRENT,
77 | CONF_PHASE_3_CURRENT,
78 | CONF_ACTUAL_CURRENT,
79 | ]
80 |
81 | twc_controller_ns = cg.esphome_ns.namespace("twc_controller")
82 | TWCController = twc_controller_ns.class_(
83 | "TWCController", number.Number, cg.Component, uart.UARTDevice
84 | )
85 |
86 | def validate_min_max(config):
87 | if config[CONF_MAX_CURRENT] <= config[CONF_MIN_CURRENT]:
88 | raise cv.Invalid(f"{CONF_MAX_CURRENT} must be greater than {CONF_MIN_CURRENT}")
89 |
90 | if CONF_SET_CURRENT in config:
91 | if (config[CONF_SET_CURRENT] > config[CONF_MAX_CURRENT]) or (config[CONF_SET_CURRENT] < config[CONF_MIN_CURRENT]):
92 | raise cv.Invalid(f"{CONF_SET_CURRENT} must be between {CONF_MIN_CURRENT} and {CONF_MAX_CURRENT}")
93 |
94 | return config
95 |
96 | CONFIG_SCHEMA = cv.All(
97 | number.number_schema(TWCController).extend(
98 | {
99 | cv.Optional(CONF_NAME, default="Set Current"): cv.string,
100 | cv.Optional(CONF_MIN_CURRENT, default=6): cv.int_range(min=6, max=32),
101 | cv.Optional(CONF_MAX_CURRENT, default=32): cv.int_range(min=6, max=32),
102 | cv.Optional(CONF_TWCID, default=0xABCD): cv.hex_int_range(0, 65535),
103 | cv.Optional(CONF_SET_CURRENT): cv.positive_int,
104 | cv.Optional(CONF_STEP, default=1): cv.positive_int,
105 | cv.Optional(CONF_RESTORE_VALUE, default=True): cv.boolean,
106 | cv.Optional(CONF_UNIT_OF_MEASUREMENT, default=UNIT_AMPERE): cv.one_of(UNIT_AMPERE),
107 | cv.Optional(CONF_PASSIVE_MODE, default=0): cv.int_range(min=0, max=1),
108 | cv.Required(CONF_FLOW_CONTROL_PIN): pins.gpio_output_pin_schema,
109 | cv.Optional(CONF_CURRENT): sensor.sensor_schema(
110 | unit_of_measurement=UNIT_AMPERE,
111 | icon=ICON_CURRENT_AC,
112 | accuracy_decimals=0,
113 | device_class=DEVICE_CLASS_CURRENT,
114 | state_class=STATE_CLASS_MEASUREMENT,
115 | ),
116 | cv.Optional(CONF_MAX_ALLOWABLE_CURRENT): sensor.sensor_schema(
117 | unit_of_measurement=UNIT_AMPERE,
118 | icon=ICON_CURRENT_AC,
119 | accuracy_decimals=0,
120 | device_class=DEVICE_CLASS_CURRENT,
121 | state_class=STATE_CLASS_MEASUREMENT,
122 | ),
123 | cv.Optional(CONF_TOTAL_KWH): sensor.sensor_schema(
124 | unit_of_measurement=UNIT_KILOWATT_HOURS,
125 | icon=ICON_CURRENT_AC,
126 | accuracy_decimals=0,
127 | device_class=DEVICE_CLASS_ENERGY,
128 | state_class=STATE_CLASS_TOTAL_INCREASING,
129 | ),
130 | cv.Optional(CONF_SERIAL): text_sensor.text_sensor_schema(
131 | icon=ICON_CURRENT_AC,
132 | ),
133 | cv.Optional(CONF_PHASE_1_VOLTAGE): sensor.sensor_schema(
134 | unit_of_measurement=UNIT_VOLT,
135 | icon=ICON_LIGHTNING_BOLT,
136 | accuracy_decimals=0,
137 | device_class=DEVICE_CLASS_VOLTAGE,
138 | state_class=STATE_CLASS_MEASUREMENT,
139 | ),
140 | cv.Optional(CONF_PHASE_2_VOLTAGE): sensor.sensor_schema(
141 | unit_of_measurement=UNIT_VOLT,
142 | icon=ICON_LIGHTNING_BOLT,
143 | accuracy_decimals=0,
144 | device_class=DEVICE_CLASS_VOLTAGE,
145 | state_class=STATE_CLASS_MEASUREMENT,
146 | ),
147 | cv.Optional(CONF_PHASE_3_VOLTAGE): sensor.sensor_schema(
148 | unit_of_measurement=UNIT_VOLT,
149 | icon=ICON_LIGHTNING_BOLT,
150 | accuracy_decimals=0,
151 | device_class=DEVICE_CLASS_VOLTAGE,
152 | state_class=STATE_CLASS_MEASUREMENT,
153 | ),
154 | cv.Optional(CONF_PHASE_1_CURRENT): sensor.sensor_schema(
155 | unit_of_measurement=UNIT_AMPERE,
156 | icon=ICON_CURRENT_AC,
157 | accuracy_decimals=0,
158 | device_class=DEVICE_CLASS_CURRENT,
159 | state_class=STATE_CLASS_MEASUREMENT,
160 | ),
161 | cv.Optional(CONF_PHASE_2_CURRENT): sensor.sensor_schema(
162 | unit_of_measurement=UNIT_AMPERE,
163 | icon=ICON_CURRENT_AC,
164 | accuracy_decimals=0,
165 | device_class=DEVICE_CLASS_CURRENT,
166 | state_class=STATE_CLASS_MEASUREMENT,
167 | ),
168 | cv.Optional(CONF_PHASE_3_CURRENT): sensor.sensor_schema(
169 | unit_of_measurement=UNIT_AMPERE,
170 | icon=ICON_CURRENT_AC,
171 | accuracy_decimals=0,
172 | device_class=DEVICE_CLASS_CURRENT,
173 | state_class=STATE_CLASS_MEASUREMENT,
174 | ),
175 | cv.Optional(CONF_FIRMWARE_VERSION): text_sensor.text_sensor_schema(
176 | icon=ICON_NUMERIC,
177 | ),
178 | cv.Optional(CONF_VIN): text_sensor.text_sensor_schema(
179 | icon=ICON_CAR,
180 | ),
181 | cv.Optional(CONF_ACTUAL_CURRENT): sensor.sensor_schema(
182 | unit_of_measurement=UNIT_AMPERE,
183 | icon=ICON_CURRENT_AC,
184 | accuracy_decimals=0,
185 | device_class=DEVICE_CLASS_CURRENT,
186 | state_class=STATE_CLASS_MEASUREMENT,
187 | ),
188 | cv.Optional(CONF_STATE): sensor.sensor_schema(
189 | icon=ICON_CURRENT_AC,
190 | accuracy_decimals=0,
191 | ),
192 | }
193 | )
194 | .extend(uart.UART_DEVICE_SCHEMA)
195 | .extend(cv.COMPONENT_SCHEMA),
196 | validate_min_max
197 | )
198 |
199 | async def setup_sensor(config, key, hub):
200 | if sensor_config := config.get(key):
201 | sens = await sensor.new_sensor(sensor_config)
202 | cg.add(getattr(hub, f"set_{key}_sensor")(sens))
203 |
204 | async def setup_text_sensor(config, key, hub):
205 | if sensor_config := config.get(key):
206 | sens = await text_sensor.new_text_sensor(sensor_config)
207 | cg.add(getattr(hub, f"set_{key}_text_sensor")(sens))
208 |
209 | async def to_code(config):
210 | num_var = await number.new_number(
211 | config,
212 | min_value=config[CONF_MIN_CURRENT],
213 | max_value=config[CONF_MAX_CURRENT],
214 | step=config[CONF_STEP],
215 | )
216 |
217 | await cg.register_component(num_var, config)
218 | await uart.register_uart_device(num_var, config)
219 |
220 | cg.add(num_var.set_min_current(config[CONF_MIN_CURRENT]))
221 | cg.add(num_var.set_max_current(config[CONF_MAX_CURRENT]))
222 | cg.add(num_var.set_twcid(config[CONF_TWCID]))
223 | cg.add(num_var.set_passive_mode(config[CONF_PASSIVE_MODE]))
224 |
225 | for key in TYPES:
226 | await setup_sensor(config, key, num_var)
227 |
228 | for key in TEXT_TYPES:
229 | await setup_text_sensor(config, key, num_var)
230 |
231 | pin = await gpio_pin_expression(config[CONF_FLOW_CONTROL_PIN])
232 | cg.add(num_var.set_flow_control_pin(pin))
233 |
--------------------------------------------------------------------------------
/components/twc-controller/functions.cpp:
--------------------------------------------------------------------------------
1 | #include
2 |
3 | #include "functions.h"
4 |
5 | namespace esphome {
6 | namespace twc_controller {
7 | uint8_t hexCharacterStringToBytes(uint8_t *byteArray, const uint8_t *hexString, size_t length)
8 | {
9 | //bool oddLength = strlen(hexString) & 1;
10 | bool oddLength = length & 1;
11 |
12 | std::uint8_t currentByte = 0;
13 | std::uint8_t byteIndex = 0;
14 |
15 | for (uint8_t charIndex = 0; charIndex < length; charIndex++)
16 | {
17 | bool oddCharIndex = charIndex & 1;
18 |
19 | if (oddLength)
20 | {
21 | // If the length is odd
22 | if (oddCharIndex)
23 | {
24 | // odd characters go in high nibble
25 | currentByte = nibble(hexString[charIndex]) << 4;
26 | }
27 | else
28 | {
29 | // Even characters go into low nibble
30 | currentByte |= nibble(hexString[charIndex]);
31 | byteArray[byteIndex++] = currentByte;
32 | currentByte = 0;
33 | }
34 | }
35 | else
36 | {
37 | // If the length is even
38 | if (!oddCharIndex)
39 | {
40 | // Odd characters go into the high nibble
41 | currentByte = nibble(hexString[charIndex]) << 4;
42 | }
43 | else
44 | {
45 | // Odd characters go into low nibble
46 | currentByte |= nibble(hexString[charIndex]);
47 | byteArray[byteIndex++] = currentByte;
48 | currentByte = 0;
49 | }
50 | }
51 | }
52 | return byteIndex;
53 | }
54 |
55 | uint8_t nibble(uint8_t c) {
56 | if (c >= '0' && c <= '9')
57 | return c - '0';
58 |
59 | if (c >= 'a' && c <= 'f')
60 | return c - 'a' + 10;
61 |
62 | if (c >= 'A' && c <= 'F')
63 | return c - 'A' + 10;
64 |
65 | return 0; // Not a valid hexadecimal character
66 | }
67 |
68 | long random(long lower, long upper) {
69 | if(lower >= upper) {
70 | return lower;
71 | }
72 | return random_uint32()%(upper - lower) + lower;
73 | }
74 |
75 |
76 | }
77 | }
--------------------------------------------------------------------------------
/components/twc-controller/functions.h:
--------------------------------------------------------------------------------
1 | #pragma once
2 |
3 | #include
4 |
5 | #include "esphome/core/helpers.h"
6 |
7 | namespace esphome {
8 | namespace twc_controller {
9 | uint8_t hexCharacterStringToBytes(uint8_t*, const uint8_t*, size_t);
10 | uint8_t nibble(uint8_t);
11 | long random(long, long);
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/components/twc-controller/io.h:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2023 Jarl Nicolson
4 | This program is free software; you can redistribute it and/or
5 | modify it under the terms of the GNU General Public License
6 | as published by the Free Software Foundation; either version 3
7 | of the License, or (at your option) any later version.
8 | This program is distributed in the hope that it will be useful,
9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | GNU General Public License for more details.
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | */
15 |
16 | #pragma once
17 |
18 | namespace esphome {
19 | namespace twc_controller {
20 | class TeslaControllerIO {
21 | public:
22 | virtual ~TeslaControllerIO() {};
23 | virtual void resetIO(uint16_t);
24 | virtual void writeActualCurrent(uint8_t) = 0;
25 | virtual void writeCharger(uint16_t, uint8_t) = 0;
26 | virtual void writeChargerCurrent(uint16_t, uint8_t, uint8_t) = 0;
27 | virtual void writeChargerSerial(uint16_t, std::string) = 0;
28 | virtual void writeChargerTotalKwh(uint16_t, uint32_t) = 0;
29 | virtual void writeChargerVoltage(uint16_t, uint16_t, uint8_t) = 0;
30 | virtual void writeTotalConnectedChargers(uint8_t) = 0;
31 | virtual void writeChargerFirmware(uint16_t, std::string) = 0;
32 | virtual void writeChargerActualCurrent(uint16_t, uint8_t) = 0;
33 | virtual void writeChargerTotalPhaseCurrent(uint8_t, uint8_t) = 0;
34 | virtual void writeChargerConnectedVin(uint16_t, std::string) = 0;
35 | virtual void writeChargerState(uint16_t, uint8_t) = 0;
36 | virtual void writeTotalConnectedCars(uint8_t) = 0;
37 | virtual void writeRaw(uint8_t*, size_t) = 0;
38 | virtual void writeRawPacket(uint8_t *data, size_t length) = 0;
39 | virtual void onCurrentMessage(std::function) = 0;
40 | };
41 | }
42 | }
43 |
--------------------------------------------------------------------------------
/components/twc-controller/twc_connector.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2020 Jarl Nicolson
4 | This program is free software; you can redistribute it and/or
5 | modify it under the terms of the GNU General Public License
6 | as published by the Free Software Foundation; either version 3
7 | of the License, or (at your option) any later version.
8 | This program is distributed in the hope that it will be useful,
9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | GNU General Public License for more details.
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | */
15 |
16 |
17 |
18 | #include "twc_connector.h"
19 |
20 |
21 | namespace esphome {
22 | namespace twc_controller {
23 | static const char *TAG = "twc-controller.connector";
24 |
25 | TeslaConnector::TeslaConnector(uint16_t twcid, uint8_t max_allowable_current) :
26 | twcid(twcid),
27 | max_allowable_current(max_allowable_current)
28 | {
29 | // Fill array with null. That way when the VIN
30 | // has been fully populated (by 3 different calls),
31 | // strlen(vin_) will return 17.
32 | memset(vin_, '\0', sizeof(uint8_t) * 18);
33 | }
34 |
35 | uint8_t * TeslaConnector::GetVin() {
36 | return vin_;
37 | }
38 |
39 | void TeslaConnector::SetActualCurrent(uint8_t current) {
40 | actual_current_ = current;
41 | }
42 |
43 | uint8_t TeslaConnector::GetActualCurrent() {
44 | return actual_current_;
45 | }
46 |
47 | uint8_t TeslaConnector::GetPhaseCurrent(uint8_t phase) {
48 | switch (phase) {
49 | case 1:
50 | return phase1_current;
51 | break;
52 | case 2:
53 | return phase2_current;
54 | break;
55 | case 3:
56 | return phase3_current;
57 | break;
58 | default:
59 | ESP_LOGE(TAG, "Request for phase >3 - ignored");
60 | return 0;
61 | }
62 | }
63 | }
64 | }
--------------------------------------------------------------------------------
/components/twc-controller/twc_connector.h:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2023 Jarl Nicolson
4 | This program is free software; you can redistribute it and/or
5 | modify it under the terms of the GNU General Public License
6 | as published by the Free Software Foundation; either version 3
7 | of the License, or (at your option) any later version.
8 | This program is distributed in the hope that it will be useful,
9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | GNU General Public License for more details.
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | */
15 |
16 | #pragma once
17 |
18 | #include
19 | #include
20 |
21 | #include "esphome/core/log.h"
22 |
23 | namespace esphome {
24 | namespace twc_controller {
25 | // Encapsulate some information specific to a single wall connector. This is to allow multiple connectors to be added
26 | class TeslaConnector {
27 | public:
28 | TeslaConnector(uint16_t twcid, uint8_t max_charge_rate);
29 | void SetVin(uint8_t* upperVin);
30 | uint8_t* GetVin();
31 | void SetActualCurrent(uint8_t current);
32 | uint8_t GetActualCurrent();
33 | uint8_t GetPhaseCurrent(uint8_t phase);
34 |
35 | uint16_t twcid;
36 | uint8_t state;
37 | uint8_t firmware_version[4];
38 |
39 | uint8_t serial_number[11];
40 |
41 | uint32_t total_kwh;
42 | uint16_t phase1_voltage;
43 | uint16_t phase2_voltage;
44 | uint16_t phase3_voltage;
45 |
46 | uint8_t phase1_current;
47 | uint8_t phase2_current;
48 | uint8_t phase3_current;
49 |
50 | uint8_t max_allowable_current;
51 | private:
52 | uint8_t vin_[18];
53 | uint8_t actual_current_;
54 |
55 | };
56 | }
57 | }
--------------------------------------------------------------------------------
/components/twc-controller/twc_controller.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2023 Jarl Nicolson
4 | This program is free software; you can redistribute it and/or
5 | modify it under the terms of the GNU General Public License
6 | as published by the Free Software Foundation; either version 3
7 | of the License, or (at your option) any later version.
8 | This program is distributed in the hope that it will be useful,
9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | GNU General Public License for more details.
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | */
15 |
16 | #include "esphome/core/log.h"
17 |
18 | #include "twc_controller.h"
19 |
20 | namespace esphome {
21 | namespace twc_controller {
22 | static const char *TAG = "twc";
23 |
24 | void TWCController::setup() {
25 | if (this->flow_control_pin_ != nullptr) {
26 | this->flow_control_pin_->setup();
27 | }
28 |
29 | this->publish_state(this->min_current_);
30 |
31 | teslaController_ = new TeslaController(this->parent_, this, twcid_, flow_control_pin_, passive_mode_);
32 |
33 | teslaController_->SetMinCurrent(this->min_current_);
34 | teslaController_->SetMaxCurrent(this->max_current_);
35 |
36 | teslaController_->Begin();
37 | teslaController_->Startup();
38 | }
39 |
40 | void TWCController::loop() {
41 | teslaController_->Handle();
42 |
43 | }
44 |
45 | /* IO Functions */
46 | void TWCController::resetIO(uint16_t twcid) {
47 | // Write 0's to MQTT for each topic which has 0 as a valid value. This is because
48 | // we compare the old and new values and by default everything is 0 so it never writes
49 | // anything. This way we start at 0 and immediately update to the real value if there is
50 | // one, or stay at 0 (which is correct) if there isn't.
51 | writeChargerVoltage(twcid, 0, 1);
52 | writeChargerVoltage(twcid, 0, 2);
53 | writeChargerVoltage(twcid, 0, 3);
54 |
55 | writeChargerCurrent(twcid, 0, 1);
56 | writeChargerCurrent(twcid, 0, 2);
57 | writeChargerCurrent(twcid, 0, 3);
58 |
59 | writeChargerActualCurrent(twcid, 0);
60 |
61 | writeChargerConnectedVin(twcid, "0");
62 |
63 | writeChargerState(twcid, 0);
64 | writeTotalConnectedCars(0);
65 | }
66 |
67 | void TWCController::writeActualCurrent(uint8_t actualCurrent) {
68 | this->current_sensor_->publish_state((float)actualCurrent);
69 | }
70 |
71 | void TWCController::writeCharger(uint16_t twcid, uint8_t max_allowable_current) {
72 | this->max_allowable_current_sensor_->publish_state((float)max_allowable_current);
73 | }
74 |
75 | void TWCController::writeChargerCurrent(uint16_t twcid, uint8_t current, uint8_t phase) {
76 | switch (phase) {
77 | case 1:
78 | this->phase_1_current_sensor_->publish_state((float)current);
79 | break;
80 | case 2:
81 | this->phase_2_current_sensor_->publish_state((float)current);
82 | break;
83 | case 3:
84 | this->phase_3_current_sensor_->publish_state((float)current);
85 | break;
86 | default:
87 | ESP_LOGE(TAG, "Phase should be 3 or less");
88 | return;
89 | }
90 | };
91 |
92 | void TWCController::writeChargerSerial(uint16_t twcid, std::string serial) {
93 | this->serial_text_sensor_->publish_state(serial);
94 | }
95 |
96 | void TWCController::writeChargerTotalKwh(uint16_t twcid, uint32_t total_kwh) {
97 | this->total_kwh_delivered_sensor_->publish_state((float)total_kwh);
98 | }
99 |
100 | void TWCController::writeChargerVoltage(uint16_t twcid, uint16_t voltage, uint8_t phase) {
101 | switch (phase) {
102 | case 1:
103 | this->phase_1_voltage_sensor_->publish_state((float)voltage);
104 | break;
105 | case 2:
106 | this->phase_2_voltage_sensor_->publish_state((float)voltage);
107 | break;
108 | case 3:
109 | this->phase_3_voltage_sensor_->publish_state((float)voltage);
110 | break;
111 | default:
112 | ESP_LOGE(TAG, "Phase should be 3 or less");
113 | return;
114 | }
115 | }
116 |
117 | void TWCController::writeTotalConnectedChargers(uint8_t connected_chargers) {
118 |
119 | };
120 |
121 | void TWCController::writeChargerFirmware(uint16_t twcid, std::string firmware_version) {
122 | this->firmware_version_text_sensor_->publish_state(firmware_version);
123 | };
124 |
125 | void TWCController::writeChargerActualCurrent(uint16_t twcid, uint8_t current) {
126 | this->actual_current_sensor_->publish_state((float)current);
127 | }
128 |
129 | void TWCController::writeChargerTotalPhaseCurrent(uint8_t current, uint8_t phase) {
130 |
131 | }
132 |
133 | void TWCController::writeChargerConnectedVin(uint16_t twcid, std::string vin) {
134 | this->connected_vin_text_sensor_->publish_state(vin);
135 | }
136 |
137 | void TWCController::writeChargerState(uint16_t twcid, uint8_t state) {
138 | this->state_sensor_->publish_state((float)state);
139 | }
140 |
141 | void TWCController::writeTotalConnectedCars(uint8_t connected_cars) {
142 |
143 | }
144 |
145 | void TWCController::writeRaw(uint8_t *data, size_t length) {
146 |
147 | }
148 |
149 | void TWCController::writeRawPacket(uint8_t *data, size_t length) {
150 |
151 | }
152 |
153 | void TWCController::onCurrentMessage(std::function callback) {
154 | onCurrentMessageCallback_ = callback;
155 | }
156 |
157 |
158 | /* End IO Functions */
159 |
160 | void TWCController::dump_config() {
161 | ESP_LOGCONFIG(TAG, "TWC Controller:");
162 | this->print_params_();
163 | }
164 |
165 | void TWCController::print_params_() {
166 | ESP_LOGCONFIG(TAG," TWC ID: 0x%s", format_hex(this->twcid_).c_str());
167 | ESP_LOGCONFIG(TAG," Min Current: %d", this->min_current_);
168 | ESP_LOGCONFIG(TAG," Max Current: %d", this->max_current_);
169 | LOG_PIN(" Flow Control Pin: ", this->flow_control_pin_);
170 | }
171 |
172 | void TWCController::set_min_current(uint8_t current) {
173 | ESP_LOGD(TAG, "Set min current");
174 | this->min_current_ = current;
175 | }
176 |
177 | void TWCController::set_max_current(uint8_t current) {
178 | ESP_LOGD(TAG, "Set max current");
179 | this->max_current_ = current;
180 | }
181 |
182 | void TWCController::set_twcid(uint16_t twcid) {
183 | ESP_LOGD(TAG, "Set TWC ID");
184 | this->twcid_ = twcid;
185 | }
186 |
187 | void TWCController::control(float value) {
188 | this->onCurrentMessageCallback_(round(value));
189 | this->publish_state(value);
190 | }
191 | }
192 | }
193 |
--------------------------------------------------------------------------------
/components/twc-controller/twc_controller.h:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2023 Jarl Nicolson
4 | This program is free software; you can redistribute it and/or
5 | modify it under the terms of the GNU General Public License
6 | as published by the Free Software Foundation; either version 3
7 | of the License, or (at your option) any later version.
8 | This program is distributed in the hope that it will be useful,
9 | but WITHOUT ANY WARRANTY; without even the implied warranty of
10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 | GNU General Public License for more details.
12 | You should have received a copy of the GNU General Public License
13 | along with this program. If not, see .
14 | */
15 |
16 | #pragma once
17 |
18 | #include "esphome/core/component.h"
19 | #include "esphome/core/entity_base.h"
20 | #include "esphome/components/api/custom_api_device.h"
21 | #include "esphome/components/sensor/sensor.h"
22 | #include "esphome/components/text_sensor/text_sensor.h"
23 | #include "esphome/components/uart/uart.h"
24 |
25 | #include "twc_protocol.h"
26 | #include "io.h"
27 |
28 | namespace esphome {
29 | namespace twc_controller {
30 |
31 | class TWCController : public number::Number, public uart::UARTDevice, public Component, public TeslaControllerIO {
32 | public:
33 | void setup() override;
34 | void loop() override;
35 | void dump_config() override;
36 |
37 | float get_setup_priority() const override {
38 | return esphome::setup_priority::AFTER_CONNECTION;
39 | }
40 |
41 | void set_min_current(uint8_t current);
42 | void set_max_current(uint8_t current);
43 | void set_twcid(uint16_t);
44 |
45 | void set_passive_mode(int passive_mode) { this->passive_mode_ = passive_mode; }
46 | void set_flow_control_pin(GPIOPin *flow_control_pin) { this->flow_control_pin_ = flow_control_pin; }
47 |
48 | SUB_SENSOR(current)
49 | SUB_SENSOR(max_allowable_current)
50 | SUB_SENSOR(total_kwh_delivered)
51 | SUB_SENSOR(phase_1_voltage)
52 | SUB_SENSOR(phase_2_voltage)
53 | SUB_SENSOR(phase_3_voltage)
54 | SUB_SENSOR(phase_1_current)
55 | SUB_SENSOR(phase_2_current)
56 | SUB_SENSOR(phase_3_current)
57 | SUB_SENSOR(actual_current)
58 | SUB_SENSOR(state)
59 |
60 | SUB_TEXT_SENSOR(serial)
61 | SUB_TEXT_SENSOR(firmware_version)
62 | SUB_TEXT_SENSOR(connected_vin)
63 |
64 | /* IO Functions */
65 | void resetIO(uint16_t);
66 | void writeActualCurrent(uint8_t actualCurrent);
67 | void writeCharger(uint16_t, uint8_t);
68 | void writeChargerCurrent(uint16_t, uint8_t, uint8_t);
69 | void writeChargerSerial(uint16_t, std::string);
70 | void writeChargerTotalKwh(uint16_t, uint32_t);
71 | void writeChargerVoltage(uint16_t, uint16_t, uint8_t);
72 | void writeTotalConnectedChargers(uint8_t);
73 | void writeChargerFirmware(uint16_t, std::string);
74 | void writeChargerActualCurrent(uint16_t, uint8_t);
75 | void writeChargerTotalPhaseCurrent(uint8_t, uint8_t);
76 | void writeChargerConnectedVin(uint16_t, std::string);
77 | void writeChargerState(uint16_t, uint8_t);
78 | void writeTotalConnectedCars(uint8_t);
79 | void writeRaw(uint8_t*, size_t);
80 | void writeRawPacket(uint8_t *data, size_t length);
81 | void onCurrentMessage(std::function);
82 |
83 | /* End IO Functions */
84 | protected:
85 | GPIOPin *flow_control_pin_{nullptr};
86 | void print_params_();
87 | void control(float value);
88 |
89 | TeslaController *teslaController_;
90 | std::function onCurrentMessageCallback_=nullptr;
91 | uint8_t min_current_;
92 | uint8_t max_current_;
93 | uint16_t twcid_;
94 | uint8_t passive_mode_;
95 | };
96 |
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/components/twc-controller/twc_protocol.cpp:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2020 Craig Peacock
4 | Copyright (C) 2020 Jarl Nicolson
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 3
8 | of the License, or (at your option) any later version.
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 | You should have received a copy of the GNU General Public License
14 | along with this program. If not, see .
15 | */
16 |
17 | //#include
18 |
19 | #include
20 | #include
21 |
22 | #include "twc_controller.h"
23 | #include "twc_protocol.h"
24 | #include "functions.h"
25 |
26 | namespace esphome {
27 | namespace twc_controller {
28 | static const char *TAG = "twc.protocol";
29 |
30 | TeslaController::TeslaController(uart::UARTComponent* serial, TeslaControllerIO *io, uint16_t twcid, GPIOPin *flow_control_pin, int passive_mode) :
31 | serial_(serial),
32 | flow_control_pin_(flow_control_pin),
33 | controller_io_(io),
34 | num_connected_chargers_(0),
35 | twcid_(twcid),
36 | sign_(0x77),
37 | max_current_(0),
38 | min_current_(0),
39 | stopstart_delay_(0),
40 | debug_(false),
41 | passive_mode_(passive_mode)
42 | {
43 | }
44 |
45 | void TeslaController::Begin() {
46 | ESP_LOGD(TAG, "Starting Tesla Controller... ");
47 |
48 | // Register callbacks for IO
49 | controller_io_->onCurrentMessage([this](uint8_t current){ this->SetCurrent(current); });
50 |
51 | receive_index_ = 0;
52 | if (this->flow_control_pin_ != nullptr)
53 | this->flow_control_pin_->digital_write(false);
54 | }
55 |
56 |
57 | // This method is called in arduino setup() to start the main controller loop (a FreeRTOS task)
58 | void TeslaController::Startup() {
59 | ESP_LOGD(TAG, "Starting up Tesla Controller task as primary... ");
60 | xTaskCreate(this->startupTask_, "TeslaControllerTask", 2048, this, 1, NULL);
61 | }
62 |
63 | // This is a static method which is just used as the FreeRTOS task which sends
64 | // the presence startup messages (5 * Presence 1, 5 * Presence 2)
65 | void TeslaController::startupTask_(void *pvParameter) {
66 |
67 | TeslaController* twc = static_cast(pvParameter);
68 |
69 | while (twc->passive_mode_)
70 | vTaskDelay(1000+random(100,200)/portTICK_PERIOD_MS);
71 |
72 |
73 | for (uint8_t i = 0; i < 5; i++) {
74 | twc->SendPresence();
75 | vTaskDelay(1000/portTICK_PERIOD_MS);
76 | };
77 |
78 | for (uint8_t i = 0; i < 5; i++) {
79 | twc->SendPresence2();
80 | vTaskDelay(1000/portTICK_PERIOD_MS);
81 | };
82 |
83 | uint8_t commandNumber = 0;
84 |
85 | for (;;) {
86 | if (twc->ChargersConnected() > 0) {
87 | for (uint8_t i = 0; i < twc->ChargersConnected(); i++) {
88 | twc->SendHeartbeat(twc->chargers[i]->twcid);
89 | if (twc->current_changed_ == true) { twc->current_changed_ = false; };
90 |
91 | vTaskDelay(500+random(50,100)/portTICK_PERIOD_MS);
92 |
93 | switch (commandNumber) {
94 | case 0:
95 | twc->SendCommand(GET_VIN_FIRST, twc->chargers[i]->twcid);
96 | break;
97 | case 1:
98 | twc->SendCommand(GET_VIN_MIDDLE, twc->chargers[i]->twcid);
99 | break;
100 | case 2:
101 | twc->SendCommand(GET_VIN_LAST, twc->chargers[i]->twcid);
102 | break;
103 | case 3:
104 | twc->SendCommand(GET_SERIAL_NUMBER, twc->chargers[i]->twcid);
105 | break;
106 | case 4:
107 | twc->SendCommand(GET_PWR_STATE, twc->chargers[i]->twcid);
108 | break;
109 | case 5:
110 | twc->SendCommand(GET_FIRMWARE_VER_EXT, twc->chargers[i]->twcid);
111 | break;
112 | }
113 | vTaskDelay(1000+random(100,200)/portTICK_PERIOD_MS);
114 | }
115 |
116 | if (commandNumber >= 5) {
117 | commandNumber = 0;
118 | } else {
119 | commandNumber++;
120 | };
121 |
122 | } else {
123 | vTaskDelay(1000+random(100,200)/portTICK_PERIOD_MS);
124 | }
125 | }
126 |
127 | // This should never be reached, but just in case, make sure the task is cleaned up
128 | vTaskDelete(NULL);
129 | }
130 |
131 | // This is run via the main arduino loop() to actually receive data and do something with it
132 | void TeslaController::Handle() {
133 | uint8_t receivedChar;
134 |
135 | while (serial_->available()) {
136 | serial_->read_byte(&receivedChar);
137 |
138 | if (receive_index_ > MAX_PACKET_LENGTH-1) {
139 | ESP_LOGE(TAG, "Packet length exceeded");
140 | receive_index_ = 0;
141 | return;
142 | }
143 |
144 | switch (receivedChar) {
145 | case SLIP_END:
146 | if (message_started_) {
147 | if (receive_index_ <= 2) {
148 | // TODO: can this be improved? It seems a bit arbitary to just try and
149 | // detect small packets as errors. The byte after the end frame always seems
150 | // to be a fairly high number (>= 0xFC). I'm guessing it's meant to be 0xFF but
151 | // the last 1-2 bits are being dropped. Maybe a better way would be to see if there is a
152 | // byte > 0xF0 but this could be caught out by data corruption too.
153 |
154 | // It's likely there was a corrupt start frame and so we're flipped
155 | // and thinking that the end is the start instead. Reset this to be the start
156 | receive_index_ = 0;
157 | break;
158 | }
159 | ProcessPacket(receive_buffer_, receive_index_);
160 |
161 | message_started_ = false;
162 | receive_index_ = 0;
163 | break;
164 | } else {
165 | message_started_ = true;
166 | receive_index_ = 0;
167 | }
168 | break;
169 |
170 | case SLIP_ESC:
171 | // Use readBytes rather than read so that this blocks. Previously using
172 | // read, it would try to read too fast before the secondary had sent the next
173 | // byte and this would fall through to default. This meant bytes were not being
174 | // decoded and the next character was appearing in the packet rather than the
175 | // decoded character.
176 |
177 | // Check if readBytes returned 1 character. If it didn't, it means
178 | // the timeout was hit and therefore this should be discarded (dropping)
179 | // the whole packet
180 | if (serial_->read_array(&receivedChar, 1) != 1) {
181 | ESP_LOGE(TAG, "Error while receiving packet data for a packet");
182 | return;
183 | }
184 |
185 | switch (receivedChar) {
186 | case SLIP_ESC_END:
187 | receive_buffer_[receive_index_++] = SLIP_END;
188 | break;
189 |
190 | case SLIP_ESC_ESC:
191 | receive_buffer_[receive_index_++] = SLIP_ESC;
192 | break;
193 |
194 | default:
195 | break;
196 | // TODO: This should be an error
197 | }
198 | break;
199 |
200 | default:
201 | if (message_started_) {
202 | receive_buffer_[receive_index_++] = receivedChar;
203 | } // else disgard - probably corruption or started receiving
204 | // in the middle of a message
205 | }
206 | }
207 | }
208 |
209 | void TeslaController::Debug(bool enabled) {
210 | if (enabled) {
211 | ESP_LOGD(TAG, "Enabling Debug");
212 | } else {
213 | ESP_LOGD(TAG, "Disabling Debug");
214 | }
215 | debug_ = enabled;
216 | }
217 |
218 | void TeslaController::GetSerial(uint16_t secondary_twcid) {
219 | SendCommand(GET_SERIAL_NUMBER, secondary_twcid);
220 | }
221 |
222 | void TeslaController::GetFirmwareVer(uint16_t secondary_twcid) {
223 | SendCommand(GET_FIRMWARE_VER, secondary_twcid);
224 | }
225 |
226 | void TeslaController::GetPowerStatus(uint16_t secondary_twcid) {
227 | SendCommand(GET_FIRMWARE_VER, secondary_twcid);
228 | };
229 |
230 | void TeslaController::GetVin(uint16_t secondary_twcid) {
231 | SendCommand(GET_VIN_FIRST, secondary_twcid);
232 | SendCommand(GET_VIN_MIDDLE, secondary_twcid);
233 | SendCommand(GET_VIN_LAST, secondary_twcid);
234 | }
235 |
236 | void TeslaController::SetCurrent(uint8_t current) {
237 | if (available_current_ != current) {
238 | ESP_LOGD(TAG, "Received current change message, new current %d\r\n", current);
239 | current_changed_ = true;
240 | }
241 |
242 | // If the available current is higher than the maximum for our charger,
243 | // clamp it to the maximum
244 | available_current_ = clamp(current, min_current_, max_current_);
245 | /*if (current <= MAX_CURRENT & current >= MIN_CURRENT) {
246 | available_current_ = current;
247 | } else if (current > MAX_CURRENT) {
248 | available_current_ = MAX_CURRENT;
249 | } else if (current < MIN_CURRENT) {
250 | available_current_ = MIN_CURRENT;
251 | }*/
252 | }
253 |
254 | void TeslaController::SendPresence(bool presence2) {
255 | RESP_PACKET_T presence;
256 | PRESENCE_PAYLOAD_T *presence_payload = (PRESENCE_PAYLOAD_T *)&presence.payload;
257 |
258 | presence.command = presence2 ? htons(PRIMARY_PRESENCE2) : htons(PRIMARY_PRESENCE);
259 | presence.twcid = twcid_;
260 | presence_payload->sign = sign_;
261 | presence_payload->max_allowable_current = 0x0C80; // TODO: Repalce this with something not hard coded.
262 | for (uint8_t i = 0; i <= 7; i++) {
263 | presence_payload->padding[i] = 0x00;
264 | }
265 | presence.checksum = CalculateChecksum((uint8_t*)&presence, sizeof(presence));
266 |
267 | SendData((uint8_t*)&presence, sizeof(presence));
268 | }
269 |
270 | bool TeslaController::IsCharging() {
271 | if (total_current_ > 0) {
272 | return true;
273 | } else {
274 | return false;
275 | }
276 | }
277 |
278 | void TeslaController::SendPresence2() {
279 | SendPresence(true);
280 | }
281 |
282 | uint8_t TeslaController::ChargersConnected() {
283 | return num_connected_chargers_;
284 | }
285 |
286 | void TeslaController::SendHeartbeat(uint16_t secondary_twcid) {
287 | P_HEARTBEAT_T heartbeat;
288 | heartbeat.command = htons(PRIMARY_HEARTBEAT);
289 | heartbeat.src_twcid = twcid_;
290 | heartbeat.dst_twcid = secondary_twcid;
291 |
292 | if (current_changed_) {
293 | uint16_t encodedMax = available_current_ * 100;
294 | heartbeat.state = 0x09; // Limit power to the value from the next two bytes
295 |
296 | // current * 100 (to get it to a whole number)
297 | heartbeat.max_current = htons(encodedMax);
298 | } else {
299 | heartbeat.state = 0x00;
300 | heartbeat.max_current = 0x00;
301 | }
302 |
303 | heartbeat.plug_inserted = 0x00;
304 |
305 | for (uint8_t i = 0; i < 5; i++) {
306 | heartbeat.padding[i] = 0x00;
307 | }
308 |
309 | heartbeat.checksum = CalculateChecksum((uint8_t*)&heartbeat, sizeof(heartbeat));
310 |
311 | SendData((uint8_t*)&heartbeat, sizeof(heartbeat));
312 | }
313 |
314 | void TeslaController::SendCommand(uint16_t command, uint16_t send_to) {
315 | PACKET_T packet;
316 | packet.command = htons(command);
317 | packet.twcid = twcid_;
318 | packet.secondary_twcid = send_to;
319 | for (uint8_t i = 0; i < 6; i++) {
320 | packet.payload[i] = 0x00;
321 | }
322 | packet.checksum = CalculateChecksum((uint8_t*)&packet, sizeof(packet));
323 | SendData((uint8_t*)&packet, sizeof(packet));
324 | }
325 |
326 | uint8_t TeslaController::CalculateChecksum(uint8_t *buffer, size_t length) {
327 | uint8_t i;
328 | uint8_t endByte = 0;
329 | uint8_t checksum = 0;
330 |
331 | for (i = 1; i < length; i++) {
332 | checksum = checksum + buffer[i];
333 | }
334 |
335 | return checksum;
336 | }
337 |
338 | bool TeslaController::VerifyChecksum(uint8_t *buffer, size_t length) {
339 | uint8_t checksum = CalculateChecksum(buffer, length-1);
340 | if (buffer[length-1] == checksum) {
341 | return true;
342 | }
343 |
344 | return false;
345 | }
346 |
347 | void TeslaController::DecodeExtFirmwareVerison(RESP_PACKET_T *firmware_ver) {
348 | EXT_FIRMWARE_PAYLOAD_T *firmware_payload = (EXT_FIRMWARE_PAYLOAD_T *)firmware_ver->payload;
349 |
350 | TeslaConnector *c = GetConnector(firmware_ver->twcid);
351 |
352 | char buffer[10];
353 | snprintf(buffer, 10, "%d.%d.%d.%d",
354 | firmware_payload->major,
355 | firmware_payload->minor,
356 | firmware_payload->revision,
357 | firmware_payload->extended
358 | );
359 |
360 | if (memcmp(&c->firmware_version, &firmware_payload, 4) != 0) {
361 | memcpy(&c->firmware_version, &firmware_payload, 4);
362 | controller_io_->writeChargerFirmware(firmware_ver->twcid, std::string(buffer));
363 | }
364 |
365 | if (debug_) {
366 | ESP_LOGD(TAG, "Decoded: ID: %04x, Firmware Ver: %d.%d.%d.%d\r\n",
367 | firmware_ver->twcid,
368 | firmware_payload->major,
369 | firmware_payload->minor,
370 | firmware_payload->revision,
371 | firmware_payload->extended
372 | );
373 | }
374 | }
375 |
376 | void TeslaController::DecodeSerialNumber(EXTENDED_RESP_PACKET_T *serial) {
377 | SERIAL_PAYLOAD_T *serial_payload = (SERIAL_PAYLOAD_T *)serial->payload;
378 |
379 | TeslaConnector *c = GetConnector(serial->twcid);
380 |
381 | if (strcmp((const char*)c->serial_number, (const char*)serial_payload->serial) != 0) {
382 | strcpy((char *)&c->serial_number, (const char*)&serial_payload->serial);
383 | controller_io_->writeChargerSerial(serial->twcid, std::string((char*)&c->serial_number));
384 | }
385 |
386 |
387 | if (debug_) {
388 | ESP_LOGD(TAG, "Decoded: ID: %04x, Serial Number: %s", serial->twcid, std::string((char*)&c->serial_number));
389 | }
390 | }
391 |
392 | void TeslaController::DecodePowerState(EXTENDED_RESP_PACKET_T *power_state) {
393 | POWERSTATUS_PAYLOAD_T *power_state_payload = (POWERSTATUS_PAYLOAD_T *)power_state->payload;
394 |
395 | TeslaConnector *c = GetConnector(power_state->twcid);
396 |
397 | if (!c) {
398 | if (!passive_mode_) return;
399 |
400 | // Accept the fact that we've missed Primary's presence message.
401 | ESP_LOGD(TAG, "New charger seen - adding to controller. ID: %04x,Max Allowable Current: ?\r\n",
402 | power_state->twcid);
403 |
404 | uint8_t max_allowable_current = 99;
405 |
406 | c = new TeslaConnector(power_state->twcid, max_allowable_current);
407 | chargers[num_connected_chargers_++] = c;
408 |
409 | controller_io_->writeCharger(c->twcid, c->max_allowable_current);
410 | controller_io_->writeTotalConnectedChargers(num_connected_chargers_);
411 |
412 | controller_io_->resetIO(power_state->twcid);
413 | }
414 |
415 | uint32_t total_kwh = ntohl(power_state_payload->total_kwh);
416 | if (total_kwh != c->total_kwh) {
417 | c->total_kwh = total_kwh;
418 | controller_io_->writeChargerTotalKwh(power_state->twcid, total_kwh);
419 | };
420 |
421 | uint16_t voltage = ntohs(power_state_payload->phase1_voltage);
422 | if (voltage != c->phase1_voltage) {
423 | c->phase1_voltage = voltage;
424 | controller_io_->writeChargerVoltage(power_state->twcid, voltage, 1);
425 | };
426 |
427 | voltage = ntohs(power_state_payload->phase2_voltage);
428 | if (voltage != c->phase2_voltage) {
429 | c->phase2_voltage = voltage;
430 | controller_io_->writeChargerVoltage(power_state->twcid, voltage, 2);
431 | };
432 |
433 | voltage = ntohs(power_state_payload->phase3_voltage);
434 | if (voltage != c->phase3_voltage) {
435 | c->phase3_voltage = voltage;
436 | controller_io_->writeChargerVoltage(power_state->twcid, voltage, 3);
437 | };
438 |
439 | uint8_t current = power_state_payload->phase1_current/2;
440 | if (current != c->phase1_current) {
441 | c->phase1_current = current;
442 | controller_io_->writeChargerCurrent(power_state->twcid, current, 1);
443 | UpdateTotalPhaseCurrent(1);
444 | };
445 |
446 | current = power_state_payload->phase2_current/2;
447 | if (current != c->phase2_current) {
448 | c->phase2_current = current;
449 | controller_io_->writeChargerCurrent(power_state->twcid, current, 2);
450 | UpdateTotalPhaseCurrent(2);
451 | };
452 |
453 | current = power_state_payload->phase3_current/2;
454 | if (current != c->phase3_current) {
455 | c->phase3_current = current;
456 | controller_io_->writeChargerCurrent(power_state->twcid, current, 3);
457 | UpdateTotalPhaseCurrent(3);
458 | };
459 |
460 | if (debug_) {
461 | ESP_LOGD(TAG, "Decoded: ID: %04x, Power State Total kWh %d, Phase Voltages: %d, %d, %d, Phase Currents: %d, %d, %d\r\n",
462 | power_state->twcid,
463 | ntohl(power_state_payload->total_kwh),
464 | ntohs(power_state_payload->phase1_voltage),
465 | ntohs(power_state_payload->phase2_voltage),
466 | ntohs(power_state_payload->phase3_voltage),
467 | power_state_payload->phase1_current,
468 | power_state_payload->phase2_current,
469 | power_state_payload->phase3_current);
470 | }
471 | }
472 |
473 | void TeslaController::DecodePrimaryPresence(RESP_PACKET_T *presence, uint8_t num) {
474 | PRESENCE_PAYLOAD_T *presence_payload = (PRESENCE_PAYLOAD_T *)presence->payload;
475 |
476 | // in case we're passively listening we have to handle primary presence like a secondary
477 | // one.. beacuse we will still get the power status
478 | TeslaConnector *connector = GetConnector(presence->twcid);
479 |
480 | if (!connector) {
481 | ESP_LOGD(TAG, "New charger seen - adding to controller. ID: %04x, Sign: %02x, Max Allowable Current: %d\r\n",
482 | presence->twcid,
483 | presence_payload->sign,
484 | ntohs(presence_payload->max_allowable_current)
485 | );
486 |
487 | uint8_t max_allowable_current = (uint8_t)(ntohs(presence_payload->max_allowable_current)/100);
488 |
489 | connector = new TeslaConnector(presence->twcid, max_allowable_current);
490 | chargers[num_connected_chargers_++] = connector;
491 |
492 | controller_io_->writeCharger(connector->twcid, connector->max_allowable_current);
493 | controller_io_->writeTotalConnectedChargers(num_connected_chargers_);
494 |
495 | controller_io_->resetIO(presence->twcid);
496 | }
497 |
498 |
499 | if (debug_) {
500 | ESP_LOGD(TAG, "Decoded: Primary Presence %d - ID: %02x, Sign: %02x\r\n",
501 | num,
502 | presence->twcid,
503 | presence_payload->sign
504 | );
505 | }
506 | }
507 |
508 | void TeslaController::DecodePrimaryHeartbeat(P_HEARTBEAT_T *heartbeat) {
509 | if (debug_) {
510 | ESP_LOGD(TAG, "Decoded: Primary Heartbeat - ID: %02x, To %02x, State %02x, Max Current: %d, Plug Inserted: %02x\r\n",
511 | heartbeat->src_twcid,
512 | heartbeat->dst_twcid,
513 | heartbeat->state,
514 | ntohs(heartbeat->max_current),
515 | heartbeat->plug_inserted
516 | );
517 | }
518 |
519 | /*S_HEARTBEAT_T reply;
520 | reply.command = SECONDARY_HEARTBEAT;
521 | reply.src_twcid = twcid_
522 | reply.dst_twcid = heartbeat->src_twcid;
523 | reply.status =
524 | reply.max_current =
525 | reply.actual_current =
526 | for (uint8_t i = 0; i < 4; i++) {
527 | reply.padding[i] = 0x00;
528 | }
529 |
530 | reply.checksum = CalculateChecksum(reply);
531 |
532 | SendData((uint8_t*)&reply, sizeof(reply));*/
533 | }
534 |
535 | void TeslaController::DecodeSecondaryHeartbeat(S_HEARTBEAT_T *heartbeat) {
536 | if (debug_) {
537 | ESP_LOGD(TAG, "Decoded: Secondary Heartbeat: ID: %02x, To: %02x, Status: %02x, Max Current: %d, Actual Current: %d\r\n",
538 | heartbeat->src_twcid,
539 | heartbeat->dst_twcid,
540 | heartbeat->state,
541 | ntohs(heartbeat->max_current),
542 | ntohs(heartbeat->actual_current)
543 | );
544 | }
545 |
546 | TeslaConnector *c = GetConnector(heartbeat->src_twcid);
547 |
548 | // If the secondary changes it's state to 4, it's most likely because
549 | // it's about to start charging. Set the current changed flag
550 | // so that we send the max current to the secondary again.
551 | if (c->state != heartbeat->state) {
552 | if (heartbeat->state == 4) {
553 | current_changed_ = true;
554 | }
555 |
556 | c->state = heartbeat->state;
557 | UpdateTotalConnectedCars();
558 | controller_io_->writeChargerState(heartbeat->src_twcid, c->state);
559 | }
560 |
561 |
562 | // Check whether the current the secondary is charging at has changed. If it has
563 | // force an udpate of the total current being used and update the internal state
564 | uint8_t newCurrent = ntohs(heartbeat->actual_current)/100;
565 | if (newCurrent != c->GetActualCurrent()) {
566 | c->SetActualCurrent(newCurrent);
567 | UpdateTotalActualCurrent();
568 | controller_io_->writeChargerActualCurrent(heartbeat->src_twcid, newCurrent);
569 | }
570 | }
571 |
572 | void TeslaController::UpdateTotalConnectedCars() {
573 | uint8_t connected_cars = 0;
574 |
575 | for (uint8_t i = 0; i < num_connected_chargers_; i++) {
576 | if (chargers[i]->state != 0) {
577 | connected_cars++;
578 | }
579 | }
580 |
581 | controller_io_->writeTotalConnectedCars(connected_cars);
582 | }
583 |
584 | TeslaConnector * TeslaController::GetConnector(uint16_t twcid) {
585 | for (uint8_t i = 0; i < num_connected_chargers_; i++) {
586 | if (chargers[i]->twcid == twcid) {
587 | return chargers[i];
588 | }
589 | }
590 | return nullptr;
591 | }
592 |
593 | void TeslaController::DecodeSecondaryPresence(RESP_PACKET_T *presence) {
594 | PRESENCE_PAYLOAD_T *presence_payload = (PRESENCE_PAYLOAD_T *)presence->payload;
595 |
596 | TeslaConnector *connector = GetConnector(presence->twcid);
597 |
598 | if (!connector) {
599 | ESP_LOGD(TAG, "New charger seen - adding to controller. ID: %04x, Sign: %02x, Max Allowable Current: %d\r\n",
600 | presence->twcid,
601 | presence_payload->sign,
602 | ntohs(presence_payload->max_allowable_current)
603 | );
604 |
605 | uint8_t max_allowable_current = (uint8_t)(ntohs(presence_payload->max_allowable_current)/100);
606 |
607 | connector = new TeslaConnector(presence->twcid, max_allowable_current);
608 | chargers[num_connected_chargers_++] = connector;
609 |
610 | controller_io_->writeCharger(connector->twcid, connector->max_allowable_current);
611 | controller_io_->writeTotalConnectedChargers(num_connected_chargers_);
612 |
613 | controller_io_->resetIO(presence->twcid);
614 | }
615 | }
616 |
617 | void TeslaController::UpdateTotalActualCurrent() {
618 | total_current_ = 0;
619 | for (uint8_t i = 0; i < num_connected_chargers_; i++) {
620 | total_current_ += chargers[i]->GetActualCurrent();
621 | }
622 |
623 | if (debug_) {
624 | ESP_LOGD(TAG, "Updating actual current to %f\r\n", total_current_);
625 | }
626 | controller_io_->writeActualCurrent(total_current_);
627 | }
628 |
629 | void TeslaController::UpdateTotalPhaseCurrent(uint8_t phase) {
630 | uint8_t phase_current_ = 0;
631 |
632 | for (uint8_t i = 0; i < num_connected_chargers_; i++) {
633 | phase_current_ += chargers[i]->GetPhaseCurrent(phase);
634 | }
635 |
636 | controller_io_->writeChargerTotalPhaseCurrent(phase_current_, phase);
637 | };
638 |
639 | void TeslaController::DecodeVin(EXTENDED_RESP_PACKET_T *vin_data) {
640 | VIN_PAYLOAD_T *vin_payload = (VIN_PAYLOAD_T *)vin_data->payload;
641 |
642 | TeslaConnector *c = GetConnector(vin_data->twcid);
643 | uint8_t *vin = c->GetVin();
644 |
645 | bool changed = false;
646 |
647 | switch (ntohs(vin_data->command)) {
648 | case RESP_VIN_FIRST:
649 | if (memcmp(&vin[0], &vin_payload->vin, sizeof(vin_payload->vin)) != 0) {
650 | changed = true;
651 | memcpy(&vin[0], &vin_payload->vin, sizeof(vin_payload->vin));
652 | }
653 | break;
654 | case RESP_VIN_MIDDLE:
655 | if (memcmp(&vin[7], &vin_payload->vin, sizeof(vin_payload->vin)) != 0) {
656 | changed = true;
657 | memcpy(&vin[7], &vin_payload->vin, sizeof(vin_payload->vin));
658 | }
659 | break;
660 | case RESP_VIN_LAST:
661 | if (memcmp(&vin[14], &vin_payload->vin, 3) != 0) {
662 | changed = true;
663 | memcpy(&vin[14], &vin_payload->vin, 3);
664 | }
665 | break;
666 | }
667 |
668 | if (changed && (strlen((const char*)vin) == 17)) {
669 | controller_io_->writeChargerConnectedVin(vin_data->twcid, std::string((char *)vin));
670 | } else if (changed && strlen((const char*)vin) == 0) {
671 | controller_io_->writeChargerConnectedVin(vin_data->twcid, "0");
672 | }
673 |
674 | if (debug_) {
675 | if (strlen((const char*)vin_payload->vin) == 0) {
676 | ESP_LOGD(TAG, "No Car Connected");
677 | } else {
678 | ESP_LOGD(TAG, "VIN: %s", std::string((char *)vin_payload->vin));
679 | }
680 |
681 | }
682 |
683 | }
684 |
685 | // Process a fully received packet (i.e. data with C0 on each end)
686 | void TeslaController::ProcessPacket(uint8_t *packet, size_t length) {
687 | if (debug_) {
688 | ESP_LOGD(TAG, "Recieved Packet: ");
689 | controller_io_->writeRawPacket(packet, length);
690 | }
691 |
692 | if (!VerifyChecksum(packet, length)) {
693 | ESP_LOGD(TAG, "Error processing packet - checksum verify failed. Full packet: ");
694 |
695 | std::string res;
696 |
697 | char buf[5];
698 | for (uint8_t i = 0; i < length; i++) {
699 | if (i > 0) {
700 | res += ":";
701 | }
702 | sprintf(buf, "%02X", packet[i]);
703 | res += buf;
704 | }
705 |
706 | ESP_LOGD(TAG, "%s", res.c_str());
707 | return;
708 | }
709 |
710 | uint16_t command = ((uint16_t)packet[0]<<8) | packet[1];
711 |
712 | switch (command) {
713 | case PRIMARY_PRESENCE:
714 | DecodePrimaryPresence((RESP_PACKET_T *)packet, 1);
715 | break;
716 | case PRIMARY_PRESENCE2:
717 | DecodePrimaryPresence((RESP_PACKET_T *)packet, 2);
718 | break;
719 | case SECONDARY_PRESENCE:
720 | DecodeSecondaryPresence((RESP_PACKET_T *)packet);
721 | break;
722 | case SECONDARY_HEARTBEAT:
723 | DecodeSecondaryHeartbeat((S_HEARTBEAT_T *)packet);
724 | break;
725 | case RESP_VIN_FIRST:
726 | case RESP_VIN_MIDDLE:
727 | case RESP_VIN_LAST:
728 | DecodeVin((EXTENDED_RESP_PACKET_T *)packet);
729 | break;
730 | case RESP_PWR_STATUS:
731 | DecodePowerState((EXTENDED_RESP_PACKET_T *)packet);
732 | break;
733 | case RESP_FIRMWARE_VER_EXT:
734 | DecodeExtFirmwareVerison((RESP_PACKET_T *)packet);
735 | break;
736 | case RESP_SERIAL_NUMBER:
737 | DecodeSerialNumber((EXTENDED_RESP_PACKET_T *)packet);
738 | break;
739 | // The next commands would normally be sent by a primary so we won't receive them
740 | // unless we're pretending to be a secondary (i.e. for debugging)
741 | case PRIMARY_HEARTBEAT:
742 | DecodePrimaryHeartbeat((P_HEARTBEAT_T *)packet);
743 | break;
744 | case GET_VIN_FIRST:
745 | case GET_VIN_MIDDLE:
746 | case GET_VIN_LAST:
747 | //DecodeGetVin((PACKET_T*)packet)
748 | break;
749 | default:
750 | ESP_LOGD(TAG, "Unknown packet type received: %#02x: 0x", command);
751 | break;
752 | }
753 | }
754 |
755 | void TeslaController::SendDataFromString(const uint8_t *dataString, size_t length) {
756 | uint8_t buffer[MAX_PACKET_LENGTH];
757 | uint8_t packetSize = hexCharacterStringToBytes(buffer, dataString, length);
758 |
759 | SendData(buffer, packetSize);
760 | }
761 |
762 | void TeslaController::SendData(uint8_t *packet, size_t length) {
763 | uint8_t outputBuffer[MAX_PACKET_LENGTH];
764 | uint8_t i;
765 | uint8_t j = 0;
766 |
767 | if (length > MAX_PACKET_LENGTH) {
768 | ESP_LOGD(TAG, "Error - packet larger than maximum allowable size!");
769 | return;
770 | }
771 |
772 | uint16_t command = ((uint16_t)packet[0]<<8) | packet[1];
773 | switch (command) {
774 | case WRITE_ID_DATE:
775 | case WRITE_MODEL_NO:
776 | ESP_LOGD(TAG, "WARNING! WRITE COMMANDS ATTEMPTED! THESE CAN PERMANENTLY BREAK YOUR TWC. COMMANDS BLOCKED!");
777 | return;
778 | }
779 |
780 | // Could probably get rid of the buffer and write directly to the serial port
781 | // but this way lets the value of the buffer be printed for debugging more easily
782 | outputBuffer[j++] = SLIP_END;
783 | for (i = 0; i < length; i++) {
784 | switch (packet[i]) {
785 | case SLIP_END:
786 | outputBuffer[j++] = SLIP_ESC;
787 | outputBuffer[j++] = SLIP_ESC_END;
788 | break;
789 | case SLIP_ESC:
790 | outputBuffer[j++] = SLIP_ESC;
791 | outputBuffer[j++] = SLIP_ESC_ESC;
792 | break;
793 | default:
794 | outputBuffer[j++] = packet[i];
795 | }
796 | }
797 | outputBuffer[j++] = SLIP_END;
798 | outputBuffer[j++] = 0xFF;
799 |
800 | if (debug_) {
801 | ESP_LOGV(TAG, "Sent packet: ");
802 | for (uint8_t i = 0; i < j; i++) {
803 | ESP_LOGD(TAG, "%02x", outputBuffer[i]);
804 | }
805 |
806 | }
807 |
808 | if (this->flow_control_pin_ != nullptr)
809 | this->flow_control_pin_->digital_write(true);
810 |
811 | serial_->write_array(outputBuffer, j);
812 | serial_->flush(); // Make sure the serial data has finished sending before putting the RS485 transceiver back into receive mode
813 |
814 | if (this->flow_control_pin_ != nullptr)
815 | this->flow_control_pin_->digital_write(false);
816 | }
817 |
818 | void TeslaController::SetMaxCurrent(uint8_t max_current) {
819 | ESP_LOGD(TAG, "Setting maximum current to %d\r\n", max_current);
820 | max_current_ = max_current;
821 | }
822 |
823 | void TeslaController::SetMinCurrent(uint8_t min_current) {
824 | ESP_LOGD(TAG, "Setting minimum current to %d\r\n", min_current);
825 | min_current_ = min_current;
826 | };
827 | }
828 | }
829 |
--------------------------------------------------------------------------------
/components/twc-controller/twc_protocol.h:
--------------------------------------------------------------------------------
1 | /*
2 | TWC Manager for ESP32
3 | Copyright (C) 2020 Craig Peacock
4 | Copyright (C) 2020 Jarl Nicolson
5 | This program is free software; you can redistribute it and/or
6 | modify it under the terms of the GNU General Public License
7 | as published by the Free Software Foundation; either version 3
8 | of the License, or (at your option) any later version.
9 | This program is distributed in the hope that it will be useful,
10 | but WITHOUT ANY WARRANTY; without even the implied warranty of
11 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 | GNU General Public License for more details.
13 | You should have received a copy of the GNU General Public License
14 | along with this program; if not, write to the Free Software
15 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 | */
17 |
18 | #pragma once
19 |
20 | #include "esphome/core/log.h"
21 | #include "esphome/core/helpers.h"
22 |
23 | #include "esphome/components/uart/uart_component.h"
24 |
25 | #include "twc_connector.h"
26 | #include "io.h"
27 |
28 | #define MAX_PACKET_LENGTH 32
29 |
30 | #define GET_SERIAL_NUMBER_OLD 0xFB19
31 | #define GET_MODEL_NUMBER 0xFB1A
32 | #define GET_FIRMWARE_VER 0xFB1B
33 | #define GET_PLUG_STATE 0xFBB4
34 |
35 | #define PRIMARY_HEARTBEAT 0xFBE0
36 | #define PRIMARY_PRESENCE2 0xFBE2
37 |
38 | #define GET_PWR_STATE 0xFBEB
39 | #define GET_FIRMWARE_VER_EXT 0xFBEC
40 | #define GET_SERIAL_NUMBER 0xFBED
41 | #define GET_VIN_FIRST 0xFBEE
42 | #define GET_VIN_MIDDLE 0xFBEF
43 | #define GET_VIN_LAST 0xFBF1
44 |
45 | // The next two commands are ** DANGEROUS ** !
46 | // DO NOT USE THESE! They are defined so that
47 | // they can be blocked.
48 | #define WRITE_ID_DATE 0xFC19
49 | #define WRITE_MODEL_NO 0xFC1A
50 |
51 | // Commands without responses (0xFC)
52 | #define IDLE_MESSAGE 0xFC1D
53 | #define START_CHARGING 0xFCB1
54 | #define STOP_CHARGING 0xFCB2
55 | #define PRIMARY_PRESENCE 0xFCE1
56 |
57 | // Responses (0xFD)
58 | #define RESP_SERIAL_NUMBER_OLD 0xFD19
59 | #define RESP_MODEL_NUMBER 0xFD1A
60 | #define RESP_FIRMWARE_VER 0xFD1B
61 | #define RESP_PLUG_STATE 0xFDB4
62 |
63 | #define SECONDARY_HEARTBEAT 0xFDE0
64 |
65 | #define SECONDARY_PRESENCE 0xFDE2 // Sent by secondary on reset
66 | #define RESP_PWR_STATUS 0xFDEB // Sent by primary on reset
67 | #define RESP_FIRMWARE_VER_EXT 0xFDEC
68 | #define RESP_SERIAL_NUMBER 0xFDED
69 | #define RESP_VIN_FIRST 0xFDEE
70 | #define RESP_VIN_MIDDLE 0xFDEF
71 | #define RESP_VIN_LAST 0xFDF1
72 |
73 | // Commands are SLIP encoded on the wire - need the SLIP constants
74 | #define SLIP_END 0xC0
75 | #define SLIP_ESC 0xDB
76 | #define SLIP_ESC_END 0xDC
77 | #define SLIP_ESC_ESC 0xDD
78 |
79 | namespace esphome {
80 | namespace twc_controller {
81 |
82 | struct PACKET_T {
83 | uint16_t command;
84 | uint16_t twcid;
85 | uint16_t secondary_twcid;
86 | uint8_t payload[6];
87 | uint8_t checksum;
88 | } PACKED;
89 |
90 | struct RESP_PACKET_T {
91 | uint16_t command;
92 | uint16_t twcid;
93 | uint8_t payload[11];
94 | uint8_t checksum;
95 | } PACKED;
96 |
97 | struct EXTENDED_RESP_PACKET_T {
98 | uint16_t command;
99 | uint16_t twcid;
100 | uint8_t payload[15];
101 | uint8_t checksum;
102 | } PACKED;
103 |
104 | struct S_HEARTBEAT_T {
105 | uint16_t command;
106 | uint16_t src_twcid;
107 | uint16_t dst_twcid;
108 | uint8_t state;
109 | uint16_t max_current;
110 | uint16_t actual_current;
111 | uint8_t padding[4];
112 | uint8_t checksum;
113 | } PACKED;
114 |
115 | struct P_HEARTBEAT_T {
116 | uint16_t command;
117 | uint16_t src_twcid;
118 | uint16_t dst_twcid;
119 | uint8_t state;
120 | uint16_t max_current;
121 | uint8_t plug_inserted;
122 | uint8_t padding[5];
123 | uint8_t checksum;
124 | } PACKED;
125 |
126 | // Standard response packet payload
127 | struct PRESENCE_PAYLOAD_T {
128 | uint8_t sign;
129 | uint16_t max_allowable_current;
130 | uint8_t padding[8];
131 | } PACKED;
132 |
133 | // Extended response packet payload
134 | struct POWERSTATUS_PAYLOAD_T {
135 | uint32_t total_kwh;
136 | uint16_t phase1_voltage;
137 | uint16_t phase2_voltage;
138 | uint16_t phase3_voltage;
139 | uint8_t phase1_current;
140 | uint8_t phase2_current;
141 | uint8_t phase3_current;
142 | uint8_t padding[2];
143 | } PACKED;
144 |
145 | // Extended response packet payload
146 | struct VIN_PAYLOAD_T {
147 | uint8_t vin[7];
148 | uint8_t padding[8];
149 | } PACKED;
150 |
151 | // Extended response packet payload
152 | struct SERIAL_PAYLOAD_T {
153 | uint8_t serial[11];
154 | uint8_t padding[4];
155 | } PACKED;
156 |
157 | // Standard response packet Payload
158 | struct EXT_FIRMWARE_PAYLOAD_T {
159 | uint8_t major;
160 | uint8_t minor;
161 | uint8_t revision;
162 | uint8_t extended;
163 | uint8_t padding[7];
164 | } PACKED;
165 |
166 | class TeslaController {
167 | public:
168 | TeslaController(uart::UARTComponent* serial, TeslaControllerIO *io, uint16_t twcid, GPIOPin *flow_control_pin, int passive_mode);
169 |
170 | void Begin();
171 | void GetPowerStatus(uint16_t secondary_twcid);
172 | void GetFirmware(uint16_t secondary_twcid);
173 | void GetSerial(uint16_t secondary_twcid);
174 | void GetFirmwareVer(uint16_t secondary_twcid);
175 | void GetVin(uint16_t secondary_twcid);
176 | void Handle();
177 | void SendCommand(uint16_t command, uint16_t send_to);
178 | void SendPresence(bool presence2 = false);
179 | void SendPresence2();
180 | void SendHeartbeat(uint16_t secondary_twcid);
181 | void SendIdle();
182 | void Startup();
183 | void SendData(uint8_t *packet, size_t length);
184 | void DecodePowerState(EXTENDED_RESP_PACKET_T *power_state);
185 | void DecodePrimaryPresence(RESP_PACKET_T *presence, uint8_t num);
186 | void DecodePrimaryHeartbeat(P_HEARTBEAT_T *heartbeat);
187 | void DecodeSecondaryPresence(RESP_PACKET_T *presence);
188 | void DecodeSecondaryHeartbeat(S_HEARTBEAT_T *heartbeat);
189 | void DecodeVin(EXTENDED_RESP_PACKET_T *vin);
190 | void DecodeExtFirmwareVerison(RESP_PACKET_T *firmware_ver);
191 | void DecodeSerialNumber(EXTENDED_RESP_PACKET_T *serial);
192 | void SetCurrent(uint8_t current);
193 | void SetMaxCurrent(uint8_t maxCurrent);
194 | void SetMinCurrent(uint8_t mincurrent);
195 | void SetStopStartDelay(uint16_t stopstart_delay);
196 | uint8_t ChargersConnected();
197 | TeslaConnector * GetConnector(uint16_t twcid);
198 | void UpdateTotalActualCurrent();
199 | void UpdateTotalPhaseCurrent(uint8_t phase);
200 | void UpdateTotalConnectedCars();
201 | void StopCharging(uint16_t twcid);
202 | void StartCharging(uint16_t twcid);
203 | bool IsCharging();
204 |
205 | private:
206 | uint8_t CalculateChecksum(uint8_t *buffer, size_t length);
207 | bool VerifyChecksum(uint8_t *buffer, size_t length);
208 | void DecodeLinkReady();
209 | void DecodePrimaryHeartbeat();
210 | void DecodeSecondaryHeartbeat();
211 | void ProcessPacket(uint8_t *packet, size_t length);
212 | static void startupTask_(void *pvParameter);
213 | void Debug(bool enabled);
214 | void SendDataFromString(const uint8_t* dataString, size_t length);
215 |
216 | private:
217 | uart::UARTComponent *serial_;
218 | GPIOPin *flow_control_pin_{nullptr};
219 | TeslaControllerIO *controller_io_;
220 | uint8_t num_connected_chargers_;
221 | uint16_t twcid_;
222 | uint8_t sign_;
223 | uint8_t receive_buffer_[MAX_PACKET_LENGTH];
224 | uint8_t receive_index_;
225 | bool message_started_ = false;
226 | uint8_t available_current_;
227 | uint8_t max_current_;
228 | uint8_t min_current_;
229 | uint16_t stopstart_delay_;
230 | bool current_changed_;
231 | bool debug_;
232 | uint8_t passive_mode_;
233 | uint8_t total_current_;
234 | TeslaConnector* chargers[3];
235 | };
236 | }
237 | }
238 |
--------------------------------------------------------------------------------
/twc.yaml:
--------------------------------------------------------------------------------
1 | esphome:
2 | name: twc
3 | friendly_name: Tesla Wall Connector
4 |
5 | esp32:
6 | board: esp32dev
7 |
8 | wifi:
9 | ssid: !secret wifi_ssid
10 | password: !secret wifi_password
11 |
12 | logger:
13 | level: DEBUG
14 |
15 | ota:
16 |
17 | api:
18 |
19 | uart:
20 | id: twc_uart
21 | tx_pin: 5
22 | rx_pin: 19
23 | baud_rate: 9600
24 | data_bits: 8
25 | parity: NONE
26 | stop_bits: 1
27 |
28 | external_components:
29 | - source: github://jnicolson/esphome-twc-controller
30 | components: [twc-controller]
31 |
32 | twc-controller:
33 | id: twc
34 | uart_id: twc_uart
35 | min_current: 6
36 | max_current: 32
37 | set_current: 6
38 | twc_id: 0xAB32
39 | flow_control_pin: 18
40 | current:
41 | name: "Charging Current"
42 | max_allowable_current:
43 | name: "Maximum Allowable Current"
44 | total_kwh_delivered:
45 | name: "Total kWh Delivered"
46 | serial:
47 | name: "Serial"
48 | phase_1_voltage:
49 | name: "Phase 1 Voltage"
50 | phase_2_voltage:
51 | name: "Phase 2 Voltage"
52 | phase_3_voltage:
53 | name: "Phase 3 Voltage"
54 | phase_1_current:
55 | name: "Phase 1 Current"
56 | phase_2_current:
57 | name: "Phase 2 Current"
58 | phase_3_current:
59 | name: "Phase 3 Current"
60 | firmware_version:
61 | name: "Firmware Version"
62 | actual_current:
63 | name: "Actual Current"
64 | connected_vin:
65 | name: "Connected VIN"
66 | state:
67 | name: "State"
68 |
--------------------------------------------------------------------------------