├── .gitignore ├── CMakeLists.txt ├── COPYING ├── README.md ├── inputparser.cpp ├── inputparser.h ├── inverter.conf ├── inverter.cpp ├── inverter.h ├── main.cpp ├── main.h ├── tools.cpp └── tools.h /.gitignore: -------------------------------------------------------------------------------- 1 | # System Files 2 | .DS_Store 3 | Thumbs.db 4 | 5 | # Build Binaries 6 | bin/ 7 | 8 | CMakeFiles 9 | CMakeCache.txt 10 | cmake_install.cmake 11 | Makefile 12 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | CMAKE_MINIMUM_REQUIRED(VERSION 2.6) 2 | PROJECT("inverter_poller") 3 | 4 | set (CMAKE_CXX_FLAGS "-O2 --std=c++0x ${CMAKE_CXX_FLAGS}") 5 | 6 | file(GLOB SOURCES *.cpp) 7 | ADD_EXECUTABLE(inverter_poller ${SOURCES}) 8 | target_link_libraries(inverter_poller -lpthread) 9 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License 307 | along with this program; if not, write to the Free Software 308 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 309 | 310 | 311 | Also add information on how to contact you by electronic and paper mail. 312 | 313 | If the program is interactive, make it output a short notice like this 314 | when it starts in an interactive mode: 315 | 316 | Gnomovision version 69, Copyright (C) year name of author 317 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 318 | This is free software, and you are welcome to redistribute it 319 | under certain conditions; type `show c' for details. 320 | 321 | The hypothetical commands `show w' and `show c' should show the appropriate 322 | parts of the General Public License. Of course, the commands you use may 323 | be called something other than `show w' and `show c'; they could even be 324 | mouse-clicks or menu items--whatever suits your program. 325 | 326 | You should also get your employer (if you work as a programmer) or your 327 | school, if any, to sign a "copyright disclaimer" for the program, if 328 | necessary. Here is a sample; alter the names: 329 | 330 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 331 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 332 | 333 | , 1 April 1989 334 | Ty Coon, President of Vice 335 | 336 | This General Public License does not permit incorporating your program into 337 | proprietary programs. If your program is a subroutine library, you may 338 | consider it more useful to permit linking proprietary applications with the 339 | library. If this is what you want to do, use the GNU Lesser General 340 | Public License instead of this License. 341 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Inverter Poller 2 | 3 | This is a simple program designed to query the basic runtime parameters of Voltronic, Axpert, Mppsolar PIP, Voltacon, Effekta, and other branded OEM solar inverters. 4 | 5 | - Please see this [blog post](https://skyboo.net/2017/03/monitoring-voltronic-power-axpert-mex-inverter-under-linux/) for the original findings, and inspiration for this project. 6 | 7 | - [@ned-kelly](https://github.com/ned-kelly/) has also created a docker based [Home Assistant](https://www.home-assistant.io/) automation of this project and tested 8 | it with both Serial & USB. It can be used as a fully-fledged integration to the inverter, with a user-interface and hooked up to a monitoring system such as Grafana - If you are interested, please head to: 9 | [https://github.com/ned-kelly/docker-voltronic-homeassistant](https://github.com/ned-kelly/docker-voltronic-homeassistant) 10 | 11 | ------------------------------------------------------------ 12 | 13 | ## Compilation / running 14 | 15 | build/compilation procedure: 16 | 17 | ``` 18 | git clone git://github.com/manio/skymax-demo.git 19 | cd skymax-demo 20 | cmake .. && make 21 | ``` 22 | 23 | The code requires your inverter to be connected either via USB or RS323, and can be configured in the `inverter.conf` file... 24 | 25 | 26 | You can then run the inverter binary afterwards - By default, it will query the inverter every few seconds and return a JSON response to the console... 27 | 28 | 29 | #### Basic command line arguments supported are: 30 | 31 | ``` 32 | USAGE: ./inverter_poller [-r ], [-h | --help], [-1 | --run-once] 33 | 34 | SUPPORTED ARGUMENTS: 35 | -r TX 'raw' command to the inverter 36 | -h | --help This Help Message 37 | -1 | --run-once Runs one iteration on the inverter, and then exits 38 | -l Define the buffersize for the response of raw command. Default value 7. 39 | -d Additional debugging 40 | 41 | ``` 42 | 43 | #### Configuration hint: 44 | 45 | Quite a lot of inverters seams to use this protocol. The base seams not to change but depending on your device, you might have more queries available to comunicate with your device and/or more parameters in query response from inverter. 46 | 47 | Configuration file allow you to custom the buffersize of wrapped queries qmod, qpigs, qpiri, qpiws, in case default value does not match. Those wrapped queries are use to extract part of the data exposed by your device then wrapped into nice json output. 48 | 49 | To get the raw output of your device, you can use the rawcmnd option providing the right buffersize of the query (that's where start your guessing game!). 50 | 51 | Here some valid example, tested on an Axpert VM3 inverter, of buffer size to provide to the rawcmd for the associated command: 52 | 53 | ``` 54 | QPI = 8 55 | QID = 18 56 | QVFW = 18 57 | QVFM2 = 19 58 | QFLAG = 15 59 | QBOOT = 5 60 | QOPM = 6 61 | default: 7, valid value for PE commands 62 | ``` 63 | Note: 64 | 65 | - When using the `tx` command, your commands will need to follow the specification outlined [here](https://github.com/ned-kelly/docker-voltronic-homeassistant/blob/master/manual/HS_MS_MSX_RS232_Protocol_20140822_after_current_upgrade.pdf). 66 | - TX commands will be executed directly on the inverter, then the process wil exit thereafter. 67 | 68 | -------------------------------------------------------------------------------------- 69 | license 70 | -------------------------------------------------------------------------------------- 71 | This program is free software; you can redistribute it and/or modify 72 | it under the terms of the GNU General Public License as published by 73 | the Free Software Foundation; either version 2 of the License, or 74 | (at your option) any later version. 75 | See the file COPYING for more information. 76 | -------------------------------------------------------------------------------- /inputparser.cpp: -------------------------------------------------------------------------------- 1 | // @author iain 2 | 3 | #include 4 | #include 5 | #include 6 | #include "inputparser.h" 7 | 8 | // This class simply finds cmd line args and parses them for use in a program. 9 | // It is not posix compliant and wont work with args like: ./program -xf filename 10 | // You must place each arg after its own seperate dash like: ./program -x -f filename 11 | 12 | InputParser::InputParser (int &argc, char **argv) { 13 | for (int i=1; i < argc; ++i) 14 | this->tokens.push_back(std::string(argv[i])); 15 | } 16 | 17 | const std::string& InputParser::getCmdOption(const std::string &option) const { 18 | std::vector::const_iterator itr; 19 | itr = std::find(this->tokens.begin(), this->tokens.end(), option); 20 | if (itr != this->tokens.end() && ++itr != this->tokens.end()) 21 | { 22 | return *itr; 23 | } 24 | static const std::string empty_string(""); 25 | return empty_string; 26 | } 27 | 28 | bool InputParser::cmdOptionExists(const std::string &option) const { 29 | return std::find(this->tokens.begin(), this->tokens.end(), option) 30 | != this->tokens.end(); 31 | } 32 | 33 | std::vector tokens; 34 | -------------------------------------------------------------------------------- /inputparser.h: -------------------------------------------------------------------------------- 1 | // inputparser.h 2 | // @author iain 3 | #ifndef INPUTPARSER_H 4 | #define INPUTPARSER_H 5 | 6 | #include 7 | 8 | class InputParser { 9 | std::vector tokens; 10 | 11 | public: 12 | InputParser (int &argc, char **argv); 13 | const std::string& getCmdOption(const std::string &option) const; 14 | bool cmdOptionExists(const std::string &option) const; 15 | }; 16 | 17 | #endif // ___INPUTPARSER_H 18 | -------------------------------------------------------------------------------- /inverter.conf: -------------------------------------------------------------------------------- 1 | # Basic configuration options for the actual inverter polling process... 2 | 3 | # The device to read from... 4 | # Use: /dev/ttyS0 if you have a serial device, 5 | # /dev/ttyUSB0 if a USB<>Serial, 6 | # /dev/hidraw0 if you're connecting via the USB port on the inverter. 7 | 8 | device=/dev/ttyUSB0 9 | 10 | # How many times per hour is the program going to run... 11 | # This is used to calculate the PV & Load Watt Hours between runs... 12 | # If unsure, leave as default - it will run every minute... 13 | 14 | # (120 = every 30 seconds)... 15 | run_interval=120 16 | 17 | # This allows you to modify the amperage in case the inverter is giving an incorrect 18 | # reading compared to measurement tools. Normally this will remain '1' 19 | amperage_factor=1.0 20 | 21 | # This allos you to modify the wattage in case the inverter is giving an incorrect 22 | # reading compared to measurement tools. Normally this will remain '1' 23 | watt_factor=1.01 24 | 25 | # Depending on the protocol version used and your device, 26 | # you might need to change the following parameters 27 | 28 | #### For Axpert VM3 inverter like, use those values ### 29 | # This allows you to modify the buffersize for the qpiri command 30 | qpiri=98 31 | 32 | # This allows you to modify the buffersize for the qpiws command 33 | qpiws=36 34 | 35 | # This allows you to modify the buffersize for the qmod command 36 | qmod=5 37 | 38 | # This allows you to modify the buffersize for the qpigs command 39 | qpigs=110 40 | -------------------------------------------------------------------------------- /inverter.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include "inverter.h" 6 | #include "tools.h" 7 | #include "main.h" 8 | 9 | #include 10 | 11 | cInverter::cInverter(std::string devicename) { 12 | device = devicename; 13 | status1[0] = 0; 14 | status2[0] = 0; 15 | warnings[0] = 0; 16 | mode = 0; 17 | } 18 | 19 | string *cInverter::GetQpigsStatus() { 20 | m.lock(); 21 | string *result = new string(status1); 22 | m.unlock(); 23 | return result; 24 | } 25 | 26 | string *cInverter::GetQpiriStatus() { 27 | m.lock(); 28 | string *result = new string(status2); 29 | m.unlock(); 30 | return result; 31 | } 32 | 33 | string *cInverter::GetWarnings() { 34 | m.lock(); 35 | string *result = new string(warnings); 36 | m.unlock(); 37 | return result; 38 | } 39 | 40 | void cInverter::SetMode(char newmode) { 41 | m.lock(); 42 | if (mode && newmode != mode) 43 | ups_status_changed = true; 44 | mode = newmode; 45 | m.unlock(); 46 | } 47 | 48 | int cInverter::GetMode() { 49 | int result; 50 | m.lock(); 51 | 52 | switch (mode) { 53 | case 'P': result = 1; break; // Power_On 54 | case 'S': result = 2; break; // Standby 55 | case 'L': result = 3; break; // Line 56 | case 'B': result = 4; break; // Battery 57 | case 'F': result = 5; break; // Fault 58 | case 'H': result = 6; break; // Power_Saving 59 | default: result = 0; break; // Unknown 60 | } 61 | 62 | m.unlock(); 63 | return result; 64 | } 65 | 66 | bool cInverter::query(const char *cmd) { 67 | time_t started; 68 | int fd; 69 | int i=0, n, replysize; 70 | 71 | fd = open(this->device.data(), O_RDWR | O_NONBLOCK); 72 | if (fd == -1) { 73 | lprintf("INVERTER: Unable to open device file (errno=%d %s)", errno, strerror(errno)); 74 | sleep(5); 75 | return false; 76 | } 77 | 78 | 79 | // Once connected, set the baud rate and other serial config (Don't rely on this being correct on the system by default...) 80 | speed_t baud = B2400; 81 | 82 | // Speed settings (in this case, 2400 8N1) 83 | struct termios settings; 84 | tcgetattr(fd, &settings); 85 | 86 | cfsetspeed(&settings, baud); // baud rate 87 | settings.c_cflag &= ~PARENB; // no parity 88 | settings.c_cflag &= ~CSTOPB; // 1 stop bit 89 | settings.c_cflag &= ~CSIZE; // Clear all bits that set the data size 90 | settings.c_cflag |= CS8 | CLOCAL; // 8 bits 91 | 92 | settings.c_oflag &= ~OPOST; // Prevent special interpretation of output bytes (e.g. newline chars) 93 | settings.c_lflag &= ~ICANON; 94 | settings.c_iflag &= ~(IXON | IXOFF | IXANY); // Turn off s/w flow ctrl 95 | settings.c_lflag &= ~ISIG; 96 | settings.c_oflag &= ~ONLCR; // Prevent conversion of newline to carriage return/line feed 97 | settings.c_lflag &= ~ECHO; // turn off Echo input characters. 98 | settings.c_lflag &= ~IEXTEN; // disable implementation-defined input processing. 99 | settings.c_iflag &= ~(IGNBRK|BRKINT|PARMRK|ISTRIP|INLCR|IGNCR|ICRNL); // Disable any special handling of received bytes 100 | tcsetattr(fd, TCSANOW, &settings); // apply the settings 101 | tcflush(fd, TCOFLUSH); 102 | 103 | // --------------------------------------------------------------- 104 | 105 | // Generating CRC for a command 106 | uint16_t crc = cal_crc_half((uint8_t*)cmd, strlen(cmd)); 107 | n = strlen(cmd); 108 | memcpy(&buf, cmd, n); 109 | lprintf("INVERTER: Current CRC: %X %X", crc >> 8, crc & 0xff); 110 | 111 | buf[n++] = crc >> 8; 112 | buf[n++] = crc & 0xff; 113 | buf[n++] = 0x0d; 114 | 115 | //send a command 116 | write(fd, &buf, n); 117 | time(&started); 118 | 119 | const int READ_BUFFER_SIZE = 15; 120 | bool reading = true; 121 | bool timeout = false; 122 | do { 123 | n = read(fd, (void*)buf+i, READ_BUFFER_SIZE); 124 | if (n < 0) { 125 | if (time(NULL) - started > 2) { 126 | timeout = true; 127 | lprintf("INVERTER: %s read timeout", cmd); 128 | break; 129 | } else { 130 | usleep(2000); 131 | continue; 132 | } 133 | } else { 134 | for (int j=i; j>8))>>4; 253 | crc<<=4; 254 | crc^=crc_ta[da^(*ptr>>4)]; 255 | da=((uint8_t)(crc>>8))>>4; 256 | crc<<=4; 257 | crc^=crc_ta[da^(*ptr&0x0f)]; 258 | ptr++; 259 | } 260 | 261 | bCRCLow = crc; 262 | bCRCHign= (uint8_t)(crc>>8); 263 | 264 | if(bCRCLow==0x28||bCRCLow==0x0d||bCRCLow==0x0a) 265 | bCRCLow++; 266 | if(bCRCHign==0x28||bCRCHign==0x0d||bCRCHign==0x0a) 267 | bCRCHign++; 268 | 269 | crc = ((uint16_t)bCRCHign)<<8; 270 | crc += bCRCLow; 271 | return(crc); 272 | } 273 | 274 | bool cInverter::CheckCRC(unsigned char *data, int len) { 275 | uint16_t crc = cal_crc_half(data, len-3); 276 | return data[len-3]==(crc>>8) && data[len-2]==(crc&0xff); 277 | } 278 | -------------------------------------------------------------------------------- /inverter.h: -------------------------------------------------------------------------------- 1 | #ifndef ___INVERTER_H 2 | #define ___INVERTER_H 3 | 4 | #include 5 | #include 6 | #include 7 | 8 | #include 9 | 10 | using namespace std; 11 | 12 | class cInverter { 13 | unsigned char buf[1024]; //internal work buffer 14 | 15 | char warnings[1024]; 16 | char status1[1024]; 17 | char status2[1024]; 18 | char mode; 19 | 20 | std::string device; 21 | std::mutex m; 22 | std::thread t1; 23 | std::atomic_bool quit_thread{false}; 24 | 25 | void SetMode(char newmode); 26 | bool CheckCRC(unsigned char *buff, int len); 27 | bool query(const char *cmd); 28 | uint16_t cal_crc_half(uint8_t *pin, uint8_t len); 29 | 30 | public: 31 | cInverter(std::string devicename); 32 | void poll(); 33 | void runMultiThread() { 34 | t1 = std::thread(&cInverter::poll, this); 35 | } 36 | void terminateThread() { 37 | quit_thread = true; 38 | t1.join(); 39 | } 40 | 41 | string *GetQpiriStatus(); 42 | string *GetQpigsStatus(); 43 | string *GetWarnings(); 44 | 45 | int GetMode(); 46 | void ExecuteCmd(const std::string cmd); 47 | }; 48 | 49 | #endif // ___INVERTER_H 50 | -------------------------------------------------------------------------------- /main.cpp: -------------------------------------------------------------------------------- 1 | // Lightweight program to take the sensor data from a Voltronic Axpert, Mppsolar PIP, Voltacon, Effekta, and other branded OEM Inverters and send it to a MQTT server for ingestion... 2 | // Adapted from "Maio's" C application here: https://skyboo.net/2017/03/monitoring-voltronic-power-axpert-mex-inverter-under-linux/ 3 | // 4 | // Please feel free to adapt this code and add more parameters -- See the following forum for a breakdown on the RS323 protocol: http://forums.aeva.asn.au/viewtopic.php?t=4332 5 | // ------------------------------------------------------------------------ 6 | 7 | #include 8 | #include 9 | #include 10 | #include 11 | #include 12 | 13 | #include "main.h" 14 | #include "tools.h" 15 | #include "inputparser.h" 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | 27 | 28 | bool debugFlag = false; 29 | bool runOnce = false; 30 | bool ups_leave = false; 31 | 32 | cInverter *ups = NULL; 33 | 34 | atomic_bool ups_status_changed(false); 35 | atomic_bool ups_qmod_changed(false); 36 | atomic_bool ups_qpiri_changed(false); 37 | atomic_bool ups_qpigs_changed(false); 38 | atomic_bool ups_qpiws_changed(false); 39 | atomic_bool ups_cmd_executed(false); 40 | 41 | 42 | // --------------------------------------- 43 | // Global configs read from 'inverter.conf' 44 | 45 | string devicename; 46 | int runinterval; 47 | float ampfactor; 48 | float wattfactor; 49 | int qpiri = 98; 50 | int qpiws = 36; 51 | int qmod = 5; 52 | int qpigs = 110; 53 | 54 | // --------------------------------------- 55 | 56 | void attemptAddSetting(int *addTo, string addFrom) { 57 | try { 58 | *addTo = stof(addFrom); 59 | } catch (exception e) { 60 | cout << e.what() << '\n'; 61 | cout << "There's probably a string in the settings file where an int should be.\n"; 62 | } 63 | } 64 | 65 | void attemptAddSetting(float *addTo, string addFrom) { 66 | try { 67 | *addTo = stof(addFrom); 68 | } catch (exception e) { 69 | cout << e.what() << '\n'; 70 | cout << "There's probably a string in the settings file where a floating point should be.\n"; 71 | } 72 | } 73 | 74 | void getSettingsFile(string filename) { 75 | 76 | try { 77 | string fileline, linepart1, linepart2; 78 | ifstream infile; 79 | infile.open(filename); 80 | while(!infile.eof()) { 81 | getline(infile, fileline); 82 | size_t firstpos = fileline.find("#"); 83 | 84 | if(firstpos != 0 && fileline.length() != 0) { // Ignore lines starting with # (comment lines) 85 | size_t delimiter = fileline.find("="); 86 | linepart1 = fileline.substr(0, delimiter); 87 | linepart2 = fileline.substr(delimiter+1, string::npos - delimiter); 88 | if(linepart1 == "device") 89 | devicename = linepart2; 90 | else if(linepart1 == "run_interval") 91 | attemptAddSetting(&runinterval, linepart2); 92 | else if(linepart1 == "amperage_factor") 93 | attemptAddSetting(&factor, linepart2); 94 | else if(linepart1 == "watt_factor") 95 | attemptAddSetting(&wattfactor, linepart2); 96 | else if(linepart1 == "qpiri") 97 | attemptAddSetting(&qpiri, linepart2); 98 | else if(linepart1 == "qpiws") 99 | attemptAddSetting(&qpiws, linepart2); 100 | else if(linepart1 == "qmod") 101 | attemptAddSetting(&qmod, linepart2); 102 | else if(linepart1 == "qpigs") 103 | attemptAddSetting(&qpigs, linepart2); 104 | else 105 | continue; 106 | } 107 | } 108 | infile.close(); 109 | } catch (...) { 110 | cout << "Settings could not be read properly...\n"; 111 | } 112 | } 113 | 114 | int main(int argc, char* argv[]) { 115 | 116 | // Reply1 117 | float voltage_grid; 118 | float freq_grid; 119 | float voltage_out; 120 | float freq_out; 121 | int load_va; 122 | int load_watt; 123 | int load_percent; 124 | int voltage_bus; 125 | float voltage_batt; 126 | int batt_charge_current; 127 | int batt_capacity; 128 | int temp_heatsink; 129 | float pv_input_current; 130 | float pv_input_voltage; 131 | float pv_input_watts; 132 | float pv_input_watthour; 133 | float load_watthour = 0; 134 | float scc_voltage; 135 | int batt_discharge_current; 136 | char device_status[9]; 137 | 138 | // Reply2 139 | float grid_voltage_rating; 140 | float grid_current_rating; 141 | float out_voltage_rating; 142 | float out_freq_rating; 143 | float out_current_rating; 144 | int out_va_rating; 145 | int out_watt_rating; 146 | float batt_rating; 147 | float batt_recharge_voltage; 148 | float batt_under_voltage; 149 | float batt_bulk_voltage; 150 | float batt_float_voltage; 151 | int batt_type; 152 | int max_grid_charge_current; 153 | int max_charge_current; 154 | int in_voltage_range; 155 | int out_source_priority; 156 | int charger_source_priority; 157 | int machine_type; 158 | int topology; 159 | int out_mode; 160 | float batt_redischarge_voltage; 161 | 162 | // Get command flag settings from the arguments (if any) 163 | InputParser cmdArgs(argc, argv); 164 | const string &rawcmd = cmdArgs.getCmdOption("-r"); 165 | int replylen = 7; 166 | sscanf(cmdArgs.getCmdOption("-l").c_str(), "%d", &replylen); 167 | 168 | if(cmdArgs.cmdOptionExists("-h") || cmdArgs.cmdOptionExists("--help")) { 169 | return print_help(); 170 | } 171 | if(cmdArgs.cmdOptionExists("-d")) { 172 | debugFlag = true; 173 | } 174 | if(cmdArgs.cmdOptionExists("-1") || cmdArgs.cmdOptionExists("--run-once")) { 175 | runOnce = true; 176 | } 177 | lprintf("INVERTER: Debug set"); 178 | const char *settings; 179 | 180 | // Get the rest of the settings from the conf file 181 | if( access( "./inverter.conf", F_OK ) != -1 ) { // file exists 182 | settings = "./inverter.conf"; 183 | } else { // file doesn't exist 184 | settings = "/etc/inverter/inverter.conf"; 185 | } 186 | getSettingsFile(settings); 187 | int fd = open(settings, O_RDWR); 188 | while (flock(fd, LOCK_EX)) sleep(1); 189 | 190 | bool ups_status_changed(false); 191 | ups = new cInverter(devicename); 192 | 193 | // Logic to send 'raw commands' to the inverter.. 194 | if (!rawcmd.empty()) { 195 | ups->ExecuteCmd(rawcmd); 196 | // We're piggybacking off the qpri status response... 197 | printf("Reply: %s\n", ups->GetQpiriStatus()->c_str()); 198 | exit(0); 199 | } else { 200 | ups->runMultiThread(); 201 | } 202 | 203 | while (true) { 204 | if (ups_status_changed) { 205 | int mode = ups->GetMode(); 206 | 207 | if (mode) 208 | lprintf("INVERTER: Mode Currently set to: %d", mode); 209 | 210 | ups_status_changed = false; 211 | } 212 | 213 | if (ups_qmod_changed && ups_qpiri_changed && ups_qpigs_changed) { 214 | 215 | ups_qmod_changed = false; 216 | ups_qpiri_changed = false; 217 | ups_qpigs_changed = false; 218 | 219 | int mode = ups->GetMode(); 220 | string *reply1 = ups->GetQpigsStatus(); 221 | string *reply2 = ups->GetQpiriStatus(); 222 | string *warnings = ups->GetWarnings(); 223 | 224 | if (reply1 && reply2 && warnings) { 225 | 226 | // Parse and display values 227 | sscanf(reply1->c_str(), "%f %f %f %f %d %d %d %d %f %d %d %d %f %f %f %d %s", &voltage_grid, &freq_grid, &voltage_out, &freq_out, &load_va, &load_watt, &load_percent, &voltage_bus, &voltage_batt, &batt_charge_current, &batt_capacity, &temp_heatsink, &pv_input_current, &pv_input_voltage, &scc_voltage, &batt_discharge_current, &device_status); 228 | sscanf(reply2->c_str(), "%f %f %f %f %f %d %d %f %f %f %f %f %d %d %d %d %d %d %d %d %d %f", &grid_voltage_rating, &grid_current_rating, &out_voltage_rating, &out_freq_rating, &out_current_rating, &out_va_rating, &out_watt_rating, &batt_rating, &batt_recharge_voltage, &batt_under_voltage, &batt_bulk_voltage, &batt_float_voltage, &batt_type, &max_grid_charge_current, &max_charge_current, &in_voltage_range, &out_source_priority, &charger_source_priority, &machine_type, &topology, &out_mode, &batt_redischarge_voltage); 229 | 230 | // There appears to be a discrepancy in actual DMM measured current vs what the meter is 231 | // telling me it's getting, so lets add a variable we can multiply/divide by to adjust if 232 | // needed. This should be set in the config so it can be changed without program recompile. 233 | if (debugFlag) { 234 | printf("INVERTER: ampfactor from config is %.2f\n", ampfactor); 235 | printf("INVERTER: wattfactor from config is %.2f\n", wattfactor); 236 | } 237 | 238 | pv_input_current = pv_input_current * ampfactor; 239 | 240 | // It appears on further inspection of the documentation, that the input current is actually 241 | // current that is going out to the battery at battery voltage (NOT at PV voltage). This 242 | // would explain the larger discrepancy we saw before. 243 | 244 | pv_input_watts = (scc_voltage * pv_input_current) * wattfactor; 245 | 246 | // Calculate watt-hours generated per run interval period (given as program argument) 247 | pv_input_watthour = pv_input_watts / (3600 / runinterval); 248 | load_watthour = (float)load_watt / (3600 / runinterval); 249 | 250 | // Print as JSON (output is expected to be parsed by another tool...) 251 | printf("{\n"); 252 | 253 | printf(" \"Inverter_mode\":%d,\n", mode); 254 | printf(" \"AC_grid_voltage\":%.1f,\n", voltage_grid); 255 | printf(" \"AC_grid_frequency\":%.1f,\n", freq_grid); 256 | printf(" \"AC_out_voltage\":%.1f,\n", voltage_out); 257 | printf(" \"AC_out_frequency\":%.1f,\n", freq_out); 258 | printf(" \"PV_in_voltage\":%.1f,\n", pv_input_voltage); 259 | printf(" \"PV_in_current\":%.1f,\n", pv_input_current); 260 | printf(" \"PV_in_watts\":%.1f,\n", pv_input_watts); 261 | printf(" \"PV_in_watthour\":%.4f,\n", pv_input_watthour); 262 | printf(" \"SCC_voltage\":%.4f,\n", scc_voltage); 263 | printf(" \"Load_pct\":%d,\n", load_percent); 264 | printf(" \"Load_watt\":%d,\n", load_watt); 265 | printf(" \"Load_watthour\":%.4f,\n", load_watthour); 266 | printf(" \"Load_va\":%d,\n", load_va); 267 | printf(" \"Bus_voltage\":%d,\n", voltage_bus); 268 | printf(" \"Heatsink_temperature\":%d,\n", temp_heatsink); 269 | printf(" \"Battery_capacity\":%d,\n", batt_capacity); 270 | printf(" \"Battery_voltage\":%.2f,\n", voltage_batt); 271 | printf(" \"Battery_charge_current\":%d,\n", batt_charge_current); 272 | printf(" \"Battery_discharge_current\":%d,\n", batt_discharge_current); 273 | printf(" \"Load_status_on\":%c,\n", device_status[3]); 274 | printf(" \"SCC_charge_on\":%c,\n", device_status[6]); 275 | printf(" \"AC_charge_on\":%c,\n", device_status[7]); 276 | printf(" \"Battery_recharge_voltage\":%.1f,\n", batt_recharge_voltage); 277 | printf(" \"Battery_under_voltage\":%.1f,\n", batt_under_voltage); 278 | printf(" \"Battery_bulk_voltage\":%.1f,\n", batt_bulk_voltage); 279 | printf(" \"Battery_float_voltage\":%.1f,\n", batt_float_voltage); 280 | printf(" \"Max_grid_charge_current\":%d,\n", max_grid_charge_current); 281 | printf(" \"Max_charge_current\":%d,\n", max_charge_current); 282 | printf(" \"Out_source_priority\":%d,\n", out_source_priority); 283 | printf(" \"Charger_source_priority\":%d,\n", charger_source_priority); 284 | printf(" \"Battery_redischarge_voltage\":%.1f,\n", batt_redischarge_voltage); 285 | printf(" \"Warnings\":\"%s\"\n", warnings->c_str()); 286 | printf("}\n"); 287 | 288 | // Delete reply string so we can update with new data when polled again... 289 | delete reply1; 290 | delete reply2; 291 | } 292 | } else if (ups_leave) { 293 | ups->terminateThread(); 294 | // Do once and exit instead of loop endlessly 295 | lprintf("INVERTER: All queries complete, exiting loop."); 296 | exit(0); 297 | } 298 | 299 | sleep(1); 300 | } 301 | 302 | if (ups) { 303 | ups->terminateThread(); 304 | delete ups; 305 | } 306 | return 0; 307 | } 308 | -------------------------------------------------------------------------------- /main.h: -------------------------------------------------------------------------------- 1 | #ifndef ___MAIN_H 2 | #define ___MAIN_H 3 | 4 | #include 5 | #include "inverter.h" 6 | 7 | extern bool debugFlag; 8 | extern bool ups_leave; 9 | 10 | extern atomic_bool ups_data_changed; 11 | 12 | extern atomic_bool ups_status_changed; 13 | extern atomic_bool ups_qpiws_changed; 14 | extern atomic_bool ups_qmod_changed; 15 | extern atomic_bool ups_qpiri_changed; 16 | extern atomic_bool ups_qpigs_changed; 17 | 18 | #endif // ___MAIN_H 19 | -------------------------------------------------------------------------------- /tools.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | #include 6 | #include 7 | #include 8 | #include 9 | #include 10 | #include "main.h" 11 | #include "tools.h" 12 | 13 | std::mutex log_mutex; 14 | 15 | void lprintf(const char *format, ...) { 16 | // Only print if debug flag is set, else do nothing 17 | if (debugFlag) { 18 | va_list ap; 19 | char fmt[2048]; 20 | 21 | //actual time 22 | time_t rawtime; 23 | struct tm *timeinfo; 24 | time(&rawtime); 25 | timeinfo = localtime(&rawtime); 26 | char buf[256]; 27 | strcpy(buf, asctime(timeinfo)); 28 | buf[strlen(buf)-1] = 0; 29 | 30 | //connect with args 31 | snprintf(fmt, sizeof(fmt), "%s %s\n", buf, format); 32 | 33 | //put on screen: 34 | va_start(ap, format); 35 | vprintf(fmt, ap); 36 | va_end(ap); 37 | 38 | //to the logfile: 39 | static FILE *log; 40 | log_mutex.lock(); 41 | log = fopen(LOG_FILE, "a"); 42 | va_start(ap, format); 43 | vfprintf(log, fmt, ap); 44 | va_end(ap); 45 | fclose(log); 46 | log_mutex.unlock(); 47 | } 48 | } 49 | 50 | int print_help() { 51 | printf("\nUSAGE: ./inverter_poller [-r ], [-h | --help], [-1 | --run-once]\n\n"); 52 | 53 | printf("SUPPORTED ARGUMENTS:\n"); 54 | printf(" -r TX 'raw' command to the inverter\n"); 55 | printf(" -h | --help This Help Message\n"); 56 | printf(" -1 | --run-once Runs one iteration on the inverter, and then exits\n"); 57 | printf(" -d Additional debugging\n\n"); 58 | 59 | printf("RAW COMMAND EXAMPLES (see protocol manual for complete list):\n"); 60 | printf("Set output source priority POP00 (Utility first)\n"); 61 | printf(" POP01 (Solar first)\n"); 62 | printf(" POP02 (SBU)\n"); 63 | printf("Set charger priority PCP00 (Utility first)\n"); 64 | printf(" PCP01 (Solar first)\n"); 65 | printf(" PCP02 (Solar and utility)\n"); 66 | printf(" PCP03 (Solar only)\n"); 67 | printf("Set other commands PEa / PDa (Enable/disable buzzer)\n"); 68 | printf(" PEb / PDb (Enable/disable overload bypass)\n"); 69 | printf(" PEj / PDj (Enable/disable power saving)\n"); 70 | printf(" PEu / PDu (Enable/disable overload restart)\n"); 71 | printf(" PEx / PDx (Enable/disable backlight)\n\n"); 72 | 73 | return 1; 74 | } -------------------------------------------------------------------------------- /tools.h: -------------------------------------------------------------------------------- 1 | #ifndef ___TOOLS_H 2 | #define ___TOOLS_H 3 | 4 | #define LOG_FILE "/dev/null" 5 | 6 | void lprintf(const char *format, ...); 7 | int print_help(); 8 | 9 | #endif // ___TOOLS_H 10 | --------------------------------------------------------------------------------