├── .checkignore ├── .gitignore ├── .travis.yml ├── LICENSE ├── MANIFEST.in ├── Makefile ├── README.rst ├── evic ├── __init__.py ├── aprom.py ├── cli.py ├── dataflash.py ├── device.py └── logo.py ├── ez_setup.py ├── requirements_dev.txt ├── setup.cfg ├── setup.py ├── testdata ├── helloworld.bin ├── src │ └── helloworld │ │ ├── Makefile │ │ └── main.c └── test_dataflash.bin ├── tests ├── test_aprom.py ├── test_cli.py ├── test_dataflash.py └── test_device.py ├── tox.ini └── udev └── 99-nuvoton-hid.rules /.checkignore: -------------------------------------------------------------------------------- 1 | ez_setup.py 2 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | 5 | # C extensions 6 | *.so 7 | 8 | # Distribution / packaging 9 | .Python 10 | env/ 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | *.egg-info/ 23 | .installed.cfg 24 | *.egg 25 | 26 | # PyInstaller 27 | # Usually these files are written by a python script from a template 28 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 29 | *.manifest 30 | *.spec 31 | 32 | # Installer logs 33 | pip-log.txt 34 | pip-delete-this-directory.txt 35 | 36 | # Unit test / coverage reports 37 | htmlcov/ 38 | .tox/ 39 | .coverage 40 | .coverage.* 41 | .cache 42 | nosetests.xml 43 | coverage.xml 44 | *,cover 45 | 46 | # Translations 47 | *.mo 48 | *.pot 49 | 50 | # Django stuff: 51 | *.log 52 | 53 | # Sphinx documentation 54 | docs/_build/ 55 | 56 | # PyBuilder 57 | target/ 58 | 59 | #IDE / Projects 60 | .ropeproject 61 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | env: 2 | - TOXENV=py34 3 | - TOXENV=py33 4 | - TOXENV=py27 5 | - TOXENV=py26 6 | - TOXENV=pypy 7 | 8 | install: pip install -U tox 9 | 10 | language: python 11 | 12 | matrix: 13 | include: 14 | - python: 3.5 15 | env: TOXENV=py35 16 | 17 | script: tox 18 | cache: 19 | directories: 20 | - .tox 21 | - $HOME/.cache/pip 22 | 23 | deploy: 24 | provider: pypi 25 | password: 26 | secure: !!binary | 27 | VHNRS0I3QlFmTFlzVVhJQk5zM1JUWUxjUkpidU5ZMk0vYS9PM3NuYjMyV2sxQm9uTkk4UzIzT1Zh 28 | cFZnUnpZdDdaTU9xRlJDWmF0VENRWnlPRE9vSldqa1BXQ3lMNVZXODJWVWlrcEM3TjhES3ByOEM4 29 | L2xITkNaeHJhNmtWY3Y4S21PWVZaNUJCSksvY2dGQ2JJYURPN2E2L3E2SmZoRG80YmJLcDAwbmZX 30 | ejh1d1I5ejg2V2FCbm9aQVdrOSs3ZGc2MW43WXJHaU9mSGozRFhLZWdyUlhmMHBNcTRVWUJjZTAv 31 | eFlDWHdYcFNMQnNMZUZvU0p1bmczeDhGNWY2WXcwSWRzaXFFTnVENmQvYkZzK1JYaEd2REQ1RjJF 32 | ZXMycnYrM3VVZzZwUEJMWk1mbjBTeGEwMDNkWG1YczhhSXFRL2hzR2oxNTl3MjE2MW5nNzJaRDlq 33 | YVJuV2Z5RDhJdzZpWm9XeHh6ei9kaXJ5VVU5NVBRdUN1UzI0dndaZ1ZNVXp2SXB2RG5nV2JYYWwy 34 | K05PcnNwdUtEeVpQR2trTmxlUUVGcS92MkY4NFY4aGtPNDV3TStmRGlCVkNuQmtpUUQ4aEhzRTB5 35 | TUpCSFpjRTM1ajZPdHlwVHBtMXJ5aXhlSFpxcXo2ckNGVVM3MzNjaTNTZi9RWndodklMMGZ6L29Q 36 | YUllZlRZYmZ6WXVmWEgxaU5QNEJpMGxpZjVBVnpMZTZYZGdjY3VzY25OK2c4MWZHeVB2MlgxR3pD 37 | S2pCclpSTWZFOHVhK3I0MnZkOU01L2R2dkM3dzFIV3ZMSVRvTHZyeVlrd0lPdU94L0dudFRxN3pP 38 | c1licDhiOU1UMkplbXkzR0daa0ZNNlkwWnhsRWZKMGNHdVFXNnY3ZDUyZEZ2VUE1UDM5Q2J6b1E9 39 | user: Ban3 40 | distributions: sdist bdist_wheel 41 | on: 42 | condition: $TOXENV == py27 43 | repo: Ban3/python-evic 44 | tags: true 45 | -------------------------------------------------------------------------------- /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 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 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 | {project} Copyright (C) {year} {fullname} 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 | 676 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE 2 | include README.rst 3 | include Makefile 4 | 5 | recursive-exclude * __pycache__ 6 | recursive-exclude * *.py[co] 7 | 8 | recursive-include * *.rst 9 | 10 | recursive-include udev * 11 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | .PHONY: clean-pyc clean-build clean 2 | 3 | help: 4 | @echo "clean - remove all build, test, coverage and Python artifacts" 5 | @echo "clean-build - remove build artifacts" 6 | @echo "clean-pyc - remove Python file artifacts" 7 | @echo "clean-test - remove test artifacts" 8 | @echo "lint - check style with flake8" 9 | @echo "test - run tests quickly with the default Python" 10 | @echo "test-all - run tests on every Python version with tox" 11 | @echo "release - package and upload a release" 12 | @echo "dist - package" 13 | @echo "install - install the package to the active Python's site-packages" 14 | 15 | clean: clean-build clean-pyc clean-test 16 | 17 | clean-build: 18 | rm -fr build/ 19 | rm -fr dist/ 20 | rm -fr .eggs/ 21 | find . -name '*.egg-info' -exec rm -fr {} + 22 | find . -name '*.egg' -exec rm -f {} + 23 | 24 | clean-pyc: 25 | find . -name '*.pyc' -exec rm -f {} + 26 | find . -name '*.pyo' -exec rm -f {} + 27 | find . -name '*~' -exec rm -f {} + 28 | find . -name '__pycache__' -exec rm -fr {} + 29 | 30 | clean-test: 31 | rm -fr .tox/ 32 | 33 | lint: 34 | flake8 evic tests 35 | 36 | test: 37 | python setup.py test 38 | 39 | test-all: 40 | tox 41 | 42 | release: clean 43 | python setup.py sdist upload 44 | python setup.py bdist_wheel upload 45 | 46 | dist: clean 47 | python setup.py sdist 48 | python setup.py bdist_wheel 49 | ls -l dist 50 | 51 | install: clean 52 | python setup.py install 53 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | =============================== 2 | Evic 3 | =============================== 4 | 5 | .. image:: https://travis-ci.org/Ban3/python-evic.svg?branch=master 6 | :target: https://travis-ci.org/Ban3/python-evic 7 | 8 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 9 | 10 | Supported devices 11 | --------------------- 12 | 13 | * eVic VTwo* 14 | * Evic VTC Mini 15 | * Cuboid Mini 16 | * Cuboid 17 | * eVic VTC Dual* 18 | * eGrip II* 19 | * eVic AIO* 20 | * eVic VTwo mini* 21 | * eVic Basic* 22 | * iStick TC100W* 23 | * ASTER* 24 | * iStick Pico 25 | * iStick Pico Mega* 26 | * iPower* 27 | * Presa TC75W* 28 | * Vaporflask Classic* 29 | * Vaporflask Lite* 30 | * Vaporflask Stout* 31 | * Reuleaux RX200* 32 | * CENTURION* 33 | * Reuleaux RX2/3* 34 | * Reuleaux RX200S* 35 | 36 | \*Untested 37 | 38 | Tested firmware versions 39 | ----------------------------- 40 | 41 | * Evic VTC Mini <=3.03 42 | * Presa TC75W 1.02\* 43 | * iStick Pico 1.01 44 | * Binaries built with `evic-sdk `_ 45 | 46 | \*Flashing Presa firmware to a VTC Mini requires changing the hardware version 47 | on some devices. Backup your data flash before flashing! 48 | 49 | Installation 50 | ------------- 51 | 52 | Install from source: 53 | ^^^^^^^^^^^^^^^^^^^^^^ 54 | 55 | Using ``evic-usb`` requires ``cython-hidapi``. You can install it using ``pip``: 56 | 57 | :: 58 | 59 | $ pip install hidapi 60 | 61 | Building ``cython-hidapi`` requires libusb headers and cython. On Arch Linux they can be obtained from the repositories by installing packages ``libusb`` and ``cython``. Debian based distributions will have packages ``libusb-1.0-0-dev`` and ``cython``. 62 | 63 | On Windows you will also need the correct compiler for your Python version. See `this `_ 64 | page for more information on setting up the compiler. 65 | 66 | | 67 | 68 | Building python-evic: 69 | 70 | :: 71 | 72 | $ git clone git://github.com/Ban3/python-evic.git 73 | $ cd python-evic 74 | $ python setup.py install 75 | 76 | 77 | Allowing non-root access to the device 78 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 79 | 80 | The file ``udev/99-nuvoton-hid.rules`` contains an example set of rules for setting the device permissions to ``0666``. Copy the file to the directory ``/etc/udev/rules.d/`` to use it. 81 | 82 | Usage 83 | ------- 84 | See ``--help`` for more information on a given command. 85 | 86 | evic-convert 87 | ^^^^^^^^^^^^ 88 | ``evic-convert`` is a tool to encrypt/decrypt firmware images: 89 | 90 | :: 91 | 92 | $ evic-convert in.bin -o out.bin 93 | 94 | evic-usb 95 | ^^^^^^^^^^^^ 96 | ``evic-usb`` is a tool for interfacing with the device through USB. 97 | 98 | 99 | Dump device data flash to a file: 100 | 101 | :: 102 | 103 | $ evic-usb dump-dataflash -o out.bin 104 | 105 | Upload an encrypted firmware image to the device: 106 | 107 | :: 108 | 109 | $ evic-usb upload firmware.bin 110 | 111 | Upload an unencrypted firmware image to the device: 112 | 113 | :: 114 | 115 | $ evic-usb upload -u firmware.bin 116 | 117 | Upload a firmware image using data flash from a file: 118 | 119 | :: 120 | 121 | $ evic-usb upload -d data.bin firmware.bin 122 | 123 | Use ``--no-verify`` to disable verification for APROM or data flash. To disable both: 124 | 125 | :: 126 | 127 | $ evic-usb upload --no-verify aprom --no-verify dataflash firmware.bin 128 | -------------------------------------------------------------------------------- /evic/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | __version__ = '0.1.dev0' 21 | 22 | 23 | from .device import HIDTransfer 24 | from .aprom import APROM, APROMError 25 | from .dataflash import DataFlash, DataFlashError 26 | from .logo import Logo, LogoConversionError 27 | -------------------------------------------------------------------------------- /evic/aprom.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import struct 21 | 22 | 23 | class APROMError(Exception): 24 | """APROM verification error.""" 25 | 26 | pass 27 | 28 | 29 | class APROM(object): 30 | """APROM file class 31 | 32 | Attributes: 33 | data: A bytearray containing the binary data of the firmware. 34 | """ 35 | 36 | def __init__(self, data): 37 | self.data = bytearray(data) 38 | 39 | @staticmethod 40 | def _genfun(filesize, index): 41 | """Generator function for decrypting/encrypting the binary file. 42 | 43 | Args: 44 | filesize: Filesize of the APROM file in bytes. 45 | index: Index of the byte being converted. 46 | """ 47 | 48 | return filesize + 408376 + index - filesize // 408376 49 | 50 | def convert(self): 51 | """Decrypts/Encrypts the binary data. 52 | 53 | Returns: 54 | A Bytearray containing decrypted/encrypted APROM image. 55 | """ 56 | 57 | data = bytearray(len(self.data)) 58 | for i in range(0, len(self.data)): 59 | data[i] = (self.data[i] ^ 60 | self._genfun(len(self.data), i)) & 0xFF 61 | return data 62 | 63 | def verify(self, product_ids, hw_version): 64 | """Verifies the contained data. 65 | 66 | Data needs to be unencrypted. 67 | 68 | Args: 69 | product_ids: A list of supported product IDs for the device. 70 | hw_version: An integer device hardware version. 71 | 72 | Raises: 73 | FirmwareException: Verification failed. 74 | 75 | """ 76 | 77 | # Does the APROM contain the string "Joyetech APROM"? 78 | if b'Joyetech APROM' not in self.data: 79 | raise APROMError("Firmware manufacturer verification failed.") 80 | 81 | id_ind = 0 82 | max_hw_version = 0 83 | # Try to locate supported product IDs 84 | for product_id in product_ids: 85 | try: 86 | product_id = product_id.encode() 87 | id_ind = self.data.index(product_id) 88 | # Maximum hardware version follows the product ID 89 | max_hw_ind = id_ind + len(product_id) 90 | max_hw_version = struct.unpack("=I", bytes(b'\x00' + 91 | self.data[max_hw_ind:max_hw_ind+3]))[0] 92 | break 93 | # Product ID was not found, try the next one 94 | except ValueError: 95 | continue 96 | 97 | # Raise an error if none of the supported product IDs were found 98 | if not id_ind: 99 | raise APROMError("Firmware device name verification failed.") 100 | 101 | # Raise an error if the maximum supported hardware version is less than 102 | # the supplied hardware version 103 | if max_hw_version < hw_version: 104 | raise APROMError("Firmware hardware version verification failed.") 105 | -------------------------------------------------------------------------------- /evic/cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | 21 | import sys 22 | import os 23 | import copy 24 | import struct 25 | from time import sleep 26 | from contextlib import contextmanager 27 | 28 | import click 29 | 30 | import evic 31 | 32 | from .device import DeviceInfo 33 | 34 | @contextmanager 35 | def handle_exceptions(*exceptions): 36 | """Context for handling exceptions.""" 37 | 38 | try: 39 | yield 40 | click.secho("OK", fg='green', bold=True) 41 | except exceptions as error: 42 | click.secho("FAIL", fg='red', bold=True) 43 | click.echo(str(error), err=True) 44 | sys.exit(1) 45 | 46 | 47 | @click.group() 48 | def usb(): 49 | """A USB programmer for devices based on the Joyetech Evic VTC Mini.""" 50 | 51 | pass 52 | 53 | 54 | def connect(dev): 55 | """Connects the USB device. 56 | 57 | Args: 58 | dev: evic.HIDTransfer object. 59 | 60 | Raises: 61 | IOerror: The device was not found 62 | """ 63 | 64 | # Connect the device 65 | with handle_exceptions(IOError): 66 | click.echo("\nFinding device...", nl=False) 67 | dev.connect() 68 | if not dev.manufacturer: 69 | raise IOError("Device not found.") 70 | 71 | 72 | def print_usb_info(dev): 73 | """Prints the USB information attributes of the device 74 | 75 | Args: 76 | dev: evic.HIDTransfer object 77 | """ 78 | 79 | click.echo("\tManufacturer: ", nl=False) 80 | click.secho(dev.manufacturer, bold=True) 81 | click.echo("\tProduct: ", nl=False) 82 | click.secho(dev.product, bold=True) 83 | click.echo("\tSerial No: ", nl=False) 84 | click.secho(dev.serial, bold=True) 85 | click.echo("") 86 | 87 | 88 | def read_dataflash(dev, verify): 89 | """Reads the device data flash. 90 | 91 | Args: 92 | dev: evic.HIDTransfer object. 93 | verify: A Boolean set to True to verify the data flash. 94 | 95 | Returns: 96 | evic.DataFlash object containing the device data flash. 97 | """ 98 | 99 | # Read the data flash 100 | with handle_exceptions(IOError): 101 | click.echo("Reading data flash...", nl=False) 102 | dataflash, checksum = dev.read_dataflash() 103 | 104 | # Verify the data flash 105 | if verify: 106 | verify_dataflash(dataflash, checksum) 107 | 108 | return dataflash 109 | 110 | 111 | def print_device_info(device_info, dataflash): 112 | """Prints the device information found from data flash. 113 | 114 | Args: 115 | device_info: device.DeviceInfo tuple. 116 | dataflash: evic.DataFlash object. 117 | """ 118 | 119 | # Print out the information 120 | click.echo("\tDevice name: ", nl=False) 121 | click.secho(device_info.name, bold=True) 122 | click.echo("\tFirmware version: ", nl=False) 123 | click.secho("{0:.2f}".format(dataflash.fw_version / 100.0), bold=True) 124 | click.echo("\tHardware version: ", nl=False) 125 | click.secho("{0:.2f}\n".format(dataflash.hw_version / 100.0), bold=True) 126 | 127 | # Issue a warning about unset hardware version number 128 | if dataflash.hw_version > 1000: 129 | click.echo("Please set the hardware version.") 130 | 131 | 132 | def verify_dataflash(dataflash, checksum): 133 | """Verifies that the data flash is correct. 134 | 135 | Args: 136 | data_flash: evic.DataFlash object. 137 | checksum: Checksum used for the verification. 138 | """ 139 | 140 | with handle_exceptions(evic.DataFlashError): 141 | click.echo("Verifying data flash...", nl=False) 142 | dataflash.verify(checksum) 143 | 144 | 145 | @usb.command() 146 | @click.argument('inputfile', type=click.File('rb')) 147 | @click.option('--encrypted/--unencrypted', '-e/-u', default=True, 148 | help='Use encrypted/unencrypted image. Defaults to encrypted.') 149 | @click.option('--dataflash', 'dataflashfile', '-d', type=click.File('rb'), 150 | help='Use data flash from a file.') 151 | @click.option('--no-verify', 'noverify', 152 | type=click.Choice(['aprom', 'dataflash']), multiple=True, 153 | help='Disable verification for APROM or data flash.') 154 | def upload(inputfile, encrypted, dataflashfile, noverify): 155 | """Upload an APROM image to the device.""" 156 | 157 | dev = evic.HIDTransfer() 158 | 159 | # Connect the device 160 | connect(dev) 161 | 162 | # Print the USB info of the device 163 | print_usb_info(dev) 164 | 165 | # Read the data flash 166 | verify = 'dataflash' not in noverify 167 | dataflash = read_dataflash(dev, verify) 168 | dataflash_original = copy.deepcopy(dataflash) 169 | 170 | # Get the device info 171 | device_info = dev.devices.get(dataflash.product_id, 172 | DeviceInfo("Unknown device", None, None)) 173 | 174 | # Print the device information 175 | print_device_info(device_info, dataflash) 176 | 177 | # Read the APROM image 178 | aprom = evic.APROM(inputfile.read()) 179 | if encrypted: 180 | aprom = evic.APROM(aprom.convert()) 181 | 182 | # Verify the APROM image 183 | if 'aprom' not in noverify: 184 | with handle_exceptions(evic.APROMError): 185 | click.echo("Verifying APROM...", nl=False) 186 | 187 | supported_product_ids = [dataflash.product_id] 188 | if device_info.supported_product_ids: 189 | supported_product_ids.extend(device_info.supported_product_ids) 190 | 191 | aprom.verify(supported_product_ids, dataflash.hw_version) 192 | 193 | # Are we using a data flash file? 194 | if dataflashfile: 195 | buf = bytearray(dataflashfile.read()) 196 | # We used to store the checksum inside the file 197 | if len(buf) == 2048: 198 | checksum = struct.unpack("=I", bytes(buf[0:4]))[0] 199 | dataflash = evic.DataFlash(buf[4:], 0) 200 | else: 201 | checksum = sum(buf) 202 | dataflash = evic.DataFlash(buf, 0) 203 | if 'dataflash' not in noverify: 204 | verify_dataflash(dataflash, checksum) 205 | 206 | # We want to boot to LDROM on restart 207 | if not dev.ldrom: 208 | dataflash.bootflag = 1 209 | 210 | # Flashing Presa firmware requires HW version <=1.03 on type A devices 211 | if b'W007' in aprom.data and dataflash.product_id == 'E052' \ 212 | and dataflash.hw_version in [106, 108, 109, 111]: 213 | click.echo("Changing HW version to 1.03...", nl=False) 214 | dataflash.hw_version = 103 215 | click.secho("OK", fg='green', bold=True) 216 | 217 | # Write data flash to the device 218 | with handle_exceptions(IOError): 219 | if dataflash.array != dataflash_original.array: 220 | click.echo("Writing data flash...", nl=False) 221 | sleep(0.1) 222 | dev.write_dataflash(dataflash) 223 | click.secho("OK", fg='green', bold=True) 224 | 225 | # We should only restart if we're not in LDROM 226 | if not dev.ldrom: 227 | # Restart 228 | click.echo("Restarting the device...", nl=False) 229 | dev.reset() 230 | sleep(2) 231 | click.secho("OK", fg='green', nl=False, bold=True) 232 | # Reconnect 233 | connect(dev) 234 | 235 | # Write APROM to the device 236 | click.echo("Writing APROM...", nl=False) 237 | dev.write_aprom(aprom) 238 | 239 | 240 | @usb.command('upload-logo') 241 | @click.argument('inputfile', type=click.File('rb')) 242 | @click.option('--invert', '-i', is_flag=True, 243 | help='Invert the colors used in the image.') 244 | @click.option('--no-verify', 'noverify', is_flag=True, 245 | help='Disable data flash verification.') 246 | def uploadlogo(inputfile, invert, noverify): 247 | """Upload a logo to the device.""" 248 | 249 | dev = evic.HIDTransfer() 250 | 251 | # Connect the device 252 | connect(dev) 253 | 254 | # Print the USB info of the device 255 | print_usb_info(dev) 256 | 257 | # Read the data flash 258 | dataflash = read_dataflash(dev, noverify) 259 | dataflash_original = copy.deepcopy(dataflash) 260 | 261 | # Get the device info 262 | device_info = dev.devices.get(dataflash.product_id, 263 | DeviceInfo("Unknown device", None, None)) 264 | 265 | # Print the device information 266 | print_device_info(device_info, dataflash) 267 | 268 | # Convert the image 269 | with handle_exceptions(evic.LogoConversionError): 270 | click.echo("Converting logo...", nl=False) 271 | 272 | # Check supported logo dimensions 273 | logo_dimensions = device_info.logo_dimensions 274 | if not logo_dimensions: 275 | raise evic.LogoConversionError("Device doesn't support logos.") 276 | 277 | # Perform the actual conversion 278 | logo = evic.logo.fromimage(inputfile, invert) 279 | if (logo.width, logo.height) != logo_dimensions: 280 | raise evic.LogoConversionError("Device only supports {}x{} logos." 281 | .format(*logo_dimensions)) 282 | 283 | # We want to boot to LDROM on restart 284 | if not dev.ldrom: 285 | dataflash.bootflag = 1 286 | 287 | # Write data flash to the device 288 | with handle_exceptions(IOError): 289 | if dataflash.array != dataflash_original.array: 290 | click.echo("Writing data flash...", nl=False) 291 | sleep(0.1) 292 | dev.write_dataflash(dataflash) 293 | click.secho("OK", fg='green', bold=True) 294 | 295 | # We should only restart if we're not in LDROM 296 | if not dev.ldrom: 297 | # Restart 298 | click.echo("Restarting the device...", nl=False) 299 | dev.reset() 300 | sleep(2) 301 | click.secho("OK", fg='green', nl=False, bold=True) 302 | # Reconnect 303 | connect(dev) 304 | 305 | # Write logo to the device 306 | click.echo("Writing logo...", nl=False) 307 | dev.write_logo(logo) 308 | 309 | 310 | @usb.command('dump-dataflash') 311 | @click.option('--output', '-o', type=click.File('wb'), required=True) 312 | @click.option('--no-verify', 'noverify', is_flag=True, 313 | help='Disable verification.') 314 | def dumpdataflash(output, noverify): 315 | """Write device data flash to a file.""" 316 | 317 | dev = evic.HIDTransfer() 318 | 319 | # Connect the device 320 | connect(dev) 321 | 322 | # Print the USB info of the device 323 | print_usb_info(dev) 324 | 325 | # Read the data flash 326 | dataflash = read_dataflash(dev, noverify) 327 | 328 | # Get the device info 329 | device_info = dev.devices.get(dataflash.product_id, 330 | DeviceInfo("Unknown device", None, None)) 331 | 332 | # Print the device information 333 | print_device_info(device_info, dataflash) 334 | 335 | # Write the data flash to the file 336 | with handle_exceptions(IOError): 337 | click.echo("Writing data flash to the file...", nl=False) 338 | output.write(dataflash.array) 339 | 340 | 341 | @usb.command('reset-dataflash') 342 | def resetdataflash(): 343 | """Reset device data flash.""" 344 | 345 | dev = evic.HIDTransfer() 346 | 347 | # Connect the device 348 | connect(dev) 349 | 350 | # Print the USB info of the device 351 | print_usb_info(dev) 352 | 353 | # Reset data flash 354 | with handle_exceptions(IOError): 355 | click.echo("Resetting data flash...", nl=False) 356 | dev.reset_dataflash() 357 | 358 | 359 | @click.group() 360 | def main(): 361 | """A USB programmer for devices based on the Joyetech Evic VTC Mini.""" 362 | 363 | pass 364 | 365 | 366 | @main.command() 367 | @click.argument('inputfile', type=click.File('rb')) 368 | @click.option('--output', '-o', type=click.File('wb'), required=True) 369 | def convert(inputfile, output): 370 | """Decrypt/encrypt an APROM image.""" 371 | 372 | binfile = evic.APROM(inputfile.read()) 373 | 374 | with handle_exceptions(IOError): 375 | click.echo("Writing APROM image...", nl=False) 376 | output.write(binfile.convert()) 377 | os.chmod(output.name, os.stat(inputfile.name).st_mode) 378 | -------------------------------------------------------------------------------- /evic/dataflash.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import binstruct 21 | 22 | 23 | class DataFlashError(Exception): 24 | """Data flash verification error.""" 25 | 26 | pass 27 | 28 | 29 | class DataFlash(binstruct.StructTemplate): 30 | """Device data flash class. 31 | 32 | Attributes: 33 | hw_version: An integer hardware version number. 34 | bootflag: 0 or 1. Controls whether APROM or LDROM is booted 35 | when the device is restarted. 36 | 0 = APROM 37 | 1 = LDROM 38 | product_id: Product ID string. 39 | fw_version: An integer firmware version number. 40 | ldrom_version: An integer LDROM versrion number. 41 | """ 42 | 43 | hw_version = binstruct.Int32Field(4) 44 | bootflag = binstruct.Int8Field(9) 45 | product_id = binstruct.StringField(312, 4) 46 | fw_version = binstruct.Int32Field(256) 47 | ldrom_version = binstruct.Int32Field(260) 48 | 49 | def verify(self, checksum): 50 | """Verifies the data flash against given checksum. 51 | 52 | Args: 53 | checksum: Checksum of the data. 54 | 55 | Raises: 56 | DataFlashError: Data flash verification failed. 57 | """ 58 | 59 | if sum(self.array) != checksum: 60 | raise DataFlashError("Data flash verification failed.") 61 | -------------------------------------------------------------------------------- /evic/device.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import struct 21 | from collections import namedtuple 22 | 23 | try: 24 | import hid 25 | HIDAPI_AVAILABLE = True 26 | except ImportError: 27 | HIDAPI_AVAILABLE = False 28 | 29 | from .dataflash import DataFlash 30 | 31 | DeviceInfo = namedtuple('DeviceInfo', 32 | 'name supported_product_ids logo_dimensions') 33 | 34 | class HIDTransfer(object): 35 | """Generic Nuvoton HID Transfer device class. 36 | 37 | Attributes: 38 | vid: USB vendor ID. 39 | pid: USB product ID. 40 | devices: A dictionary mapping product IDs to DeviceInfo tuples. 41 | hid_signature: A bytearray containing the HID command signature 42 | (4 bytes). 43 | device: A HIDAPI device. 44 | manufacturer: A string containing the device manufacturer. 45 | product: A string containing the product name. 46 | serial: A string conraining the product serial number. 47 | ldrom: A Boolean value set to True if the device is booted to LDROM. 48 | """ 49 | 50 | vid = 0x0416 51 | pid = 0x5020 52 | devices = {'E043': DeviceInfo("eVic VTwo", None, (64, 40)), 53 | 'E052': DeviceInfo("eVic-VTC Mini", ['W007'], (64, 40)), 54 | 'E056': DeviceInfo("CUBOID MINI", None, (64, 40)), 55 | 'E060': DeviceInfo("Cuboid", None, (64, 40)), 56 | 'E079': DeviceInfo("eVic VTC Dual", None, (64, 40)), 57 | 'E083': DeviceInfo("eGrip II", None, (64, 40)), 58 | 'E092': DeviceInfo("eVic AIO", None, (64, 40)), 59 | 'E115': DeviceInfo("eVic VTwo mini", None, (64, 40)), 60 | 'E150': DeviceInfo("eVic Basic", None, (64, 40)), 61 | 'M011': DeviceInfo("iStick TC100W", None, None), 62 | 'M037': DeviceInfo("ASTER", None, (96, 16)), 63 | 'M041': DeviceInfo("iStick Pico", None, (96, 16)), 64 | 'M045': DeviceInfo("iStick Pico Mega", None, (96, 16)), 65 | 'M046': DeviceInfo("iPower", None, (96, 16)), 66 | 'W007': DeviceInfo("Presa TC75W", ['E052'], None), 67 | 'W010': DeviceInfo("Classic", None, None), 68 | 'W011': DeviceInfo("Lite", None, None), 69 | 'W013': DeviceInfo("Stout", None, None), 70 | 'W014': DeviceInfo("Reuleaux RX200", None, None), 71 | 'W016': DeviceInfo("CENTURION", None, None), 72 | 'W018': DeviceInfo("Reuleaux RX2/3", None, (64, 48)), 73 | 'W026': DeviceInfo("Reuleaux RX75", None, (64, 48)), 74 | 'W033': DeviceInfo("Reuleaux RX200S", None, None) 75 | } 76 | 77 | # 0x43444948 78 | hid_signature = bytearray(b'HIDC') 79 | 80 | def __init__(self): 81 | if HIDAPI_AVAILABLE: 82 | self.device = hid.device() 83 | else: 84 | self.device = None 85 | self.manufacturer = None 86 | self.product = None 87 | self.serial = None 88 | self.ldrom = False 89 | 90 | @classmethod 91 | def hidcmd(cls, cmdcode, arg1, arg2): 92 | """Generates a Nuvoton HID command. 93 | 94 | Args: 95 | cmdcode: A byte long HID command. 96 | arg1: First HID command argument. 97 | arg2: Second HID command argument. 98 | 99 | Returns: 100 | A bytearray containing the full HID command. 101 | """ 102 | 103 | # Do not count the last 4 bytes (checksum) 104 | length = bytearray([14]) 105 | 106 | # Construct the command 107 | cmdcode = bytearray(struct.pack('=B', cmdcode)) 108 | arg1 = bytearray(struct.pack('=I', arg1)) 109 | arg2 = bytearray(struct.pack('=I', arg2)) 110 | cmd = cmdcode + length + arg1 + arg2 + cls.hid_signature 111 | 112 | # Return the command with checksum tacked at the end 113 | return cmd + bytearray(struct.pack('=I', sum(cmd))) 114 | 115 | def connect(self): 116 | """Connects the USB device. 117 | 118 | Connects the device and saves the USB device info attributes. 119 | """ 120 | 121 | self.device.open(self.vid, self.pid) 122 | if not self.manufacturer: 123 | self.manufacturer = self.device.get_manufacturer_string() 124 | self.product = self.device.get_product_string() 125 | self.serial = self.device.get_serial_number_string() 126 | 127 | def send_command(self, cmd, arg1, arg2): 128 | """Sends a HID command to the device. 129 | 130 | Args: 131 | cmd: Byte long HID command 132 | arg1: First argument to the command (integer) 133 | arg2: Second argument to the command (integer) 134 | """ 135 | 136 | command = self.hidcmd(cmd, arg1, arg2) 137 | self.write(command) 138 | 139 | def read_dataflash(self): 140 | """Reads the device data flash. 141 | 142 | ldrom attribute will be set to to True if the device is in LDROM. 143 | 144 | Returns: 145 | A tuple containing the data flash and its checksum. 146 | """ 147 | 148 | start = 0 149 | end = 2048 150 | 151 | # Send the command for reading the data flash 152 | self.send_command(0x35, start, end) 153 | 154 | # Read the dataflash 155 | buf = self.read(end) 156 | dataflash = DataFlash(buf[4:], 0) 157 | 158 | # Get the checksum from the beginning of the data flash transfer 159 | checksum = struct.unpack('=I', bytes(buf[0:4]))[0] 160 | 161 | # Are we booted to LDROM? 162 | self.ldrom = dataflash.ldrom_version or not dataflash.fw_version 163 | 164 | return (dataflash, checksum) 165 | 166 | def write(self, data): 167 | """Writes data to the device. 168 | 169 | Args: 170 | data: An iterable containing the binary data. 171 | 172 | Raises: 173 | IOError: Incorrect amount of bytes was written. 174 | """ 175 | 176 | bytes_written = 0 177 | 178 | # Split the data into 64 byte long chunks 179 | chunks = [bytearray(data[i:i+64]) for i in range(0, len(data), 64)] 180 | 181 | # Write the chunks to the device 182 | for chunk in chunks: 183 | buf = bytearray([0]) + chunk # First byte is the report number 184 | bytes_written += self.device.write(buf) - 1 185 | 186 | # Windows always writes full pages 187 | if bytes_written > len(data): 188 | bytes_written -= 64 - (len(data) % 64) 189 | 190 | # Raise IOerror if the amount sent doesn't match what we wanted 191 | if bytes_written != len(data): 192 | raise IOError("HID Write failed.") 193 | 194 | def read(self, length): 195 | """Reads data from the device. 196 | 197 | Args: 198 | length: Amount of bytes to read. 199 | 200 | Returns: 201 | A bytearray containing the binary data. 202 | 203 | Raises: 204 | IOError: Incorrect amount of bytes was read. 205 | """ 206 | 207 | data = [] 208 | pages, rem = divmod(length, 64) 209 | for _ in range(0, pages): 210 | data += self.device.read(64) 211 | if rem: 212 | data += self.device.read(rem) 213 | 214 | # Windows always reads full pages 215 | if len(data) > length: 216 | data = data[:length] 217 | 218 | # Raise IOerror if the amount read doesn't match what we wanted 219 | if len(data) != length: 220 | raise IOError("HID read failed") 221 | 222 | return bytearray(data) 223 | 224 | def write_dataflash(self, dataflash): 225 | """Writes the data flash to the device. 226 | 227 | Args: 228 | dataflash: A DataFlash object. 229 | """ 230 | 231 | # We want 2048 bytes 232 | start = 0 233 | end = 2048 234 | 235 | # Send the command for writing the data flash 236 | self.send_command(0x53, start, end) 237 | 238 | # Add checksum of the data in front of it 239 | buf = bytearray(struct.pack("=I", sum(dataflash.array))) + \ 240 | dataflash.array 241 | 242 | self.write(buf) 243 | 244 | def reset_dataflash(self): 245 | """Resets the device data flash. 246 | 247 | Sends a data flash reset request to the firmware. 248 | """ 249 | 250 | self.send_command(0x7C, 0, 0) 251 | 252 | def reset(self): 253 | """Sends the HID command for resetting the system (0xB4)""" 254 | 255 | self.send_command(0xB4, 0, 0) 256 | 257 | def write_flash(self, data, start): 258 | """Writes data to the flash memory. 259 | 260 | Args: 261 | start: Start address. 262 | """ 263 | 264 | end = len(data) 265 | 266 | # Send the command for writing the data 267 | self.send_command(0xC3, start, end) 268 | 269 | self.write(data) 270 | 271 | def write_aprom(self, aprom): 272 | """Writes the APROM to the device. 273 | 274 | Args: 275 | aprom: A BinFile object containing an unencrypted APROM image. 276 | """ 277 | 278 | self.write_flash(aprom.data, 0) 279 | 280 | def write_logo(self, logo): 281 | """Writes the logo to the the device. 282 | 283 | Args: 284 | logo: A Logo object. 285 | """ 286 | 287 | self.write_flash(logo.array, 102400) 288 | -------------------------------------------------------------------------------- /evic/logo.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import binstruct 21 | from bitarray import bitarray 22 | from PIL import Image 23 | 24 | 25 | class LogoConversionError(Exception): 26 | """Logo conversion error.""" 27 | 28 | pass 29 | 30 | 31 | class Logo(binstruct.StructTemplate): 32 | """Logo class. 33 | 34 | Attributes: 35 | width: Logo width (integer). 36 | height: Logo height (integer). 37 | """ 38 | 39 | width = binstruct.Int8Field(0) 40 | height = binstruct.Int8Field(1) 41 | 42 | 43 | def fromimage(image, invert=False): 44 | """Converts an image file to a Logo object. 45 | 46 | Args: 47 | image: The image that will be converted (file). 48 | invert: True will invert colors from the source image (boolean). 49 | 50 | Returns: 51 | An instance of Logo class containing the converted image. 52 | """ 53 | 54 | img = Image.open(image) 55 | 56 | width, height = img.size 57 | 58 | if width % 8 != 0 or height % 8 != 0: 59 | raise LogoConversionError("Image dimensions must be multiples of 8.") 60 | if width * height > 4080: 61 | raise LogoConversionError("Image is too big.") 62 | 63 | # Convert to b/w 64 | if img.mode != '1': 65 | img = img.convert('L') 66 | img = img.point(lambda x: 0 if x < 32 else 255, '1') 67 | 68 | # 1 bit per pixel 69 | bits = bitarray(list(img.getdata())) 70 | 71 | # Convert to paged column-major order 72 | # 1 bit per pixel, 8 rows per page, LSB topmost 73 | imgpixels = img.load() 74 | pagedbits = bitarray(endian='little') 75 | for page in range(0, height // 8): 76 | for x in range(0, width): 77 | for y in range(0, 8): 78 | pagedbits.append(imgpixels[x, page*8 + y]) 79 | 80 | # Invert colors 81 | if invert: 82 | bits.invert() 83 | pagedbits.invert() 84 | 85 | # Convert the bitarrays to bytes 86 | imgbytes = bits.tobytes() if hasattr( 87 | bits, 'tobytes') else bits.tostring() 88 | pagedbytes = pagedbits.tobytes() if hasattr( 89 | pagedbits, 'tobytes') else pagedbits.tostring() 90 | 91 | # Create a buffer for the logo 92 | buff = bytearray(1024) 93 | buff[0], buff[512] = (width,)*2 94 | buff[1], buff[513] = (height,)*2 95 | 96 | # Copy logo to the buffer 97 | buff[2:len(imgbytes) + 2] = imgbytes 98 | buff[514:len(pagedbytes) + 514] = pagedbytes 99 | 100 | return Logo(buff, 0) 101 | -------------------------------------------------------------------------------- /ez_setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | """ 4 | Setuptools bootstrapping installer. 5 | 6 | Run this script to install or upgrade setuptools. 7 | """ 8 | 9 | import os 10 | import shutil 11 | import sys 12 | import tempfile 13 | import zipfile 14 | import optparse 15 | import subprocess 16 | import platform 17 | import textwrap 18 | import contextlib 19 | import json 20 | import codecs 21 | 22 | from distutils import log 23 | 24 | try: 25 | from urllib.request import urlopen 26 | except ImportError: 27 | from urllib2 import urlopen 28 | 29 | try: 30 | from site import USER_SITE 31 | except ImportError: 32 | USER_SITE = None 33 | 34 | LATEST = object() 35 | DEFAULT_VERSION = LATEST 36 | DEFAULT_URL = "https://pypi.python.org/packages/source/s/setuptools/" 37 | DEFAULT_SAVE_DIR = os.curdir 38 | 39 | 40 | def _python_cmd(*args): 41 | """ 42 | Execute a command. 43 | 44 | Return True if the command succeeded. 45 | """ 46 | args = (sys.executable,) + args 47 | return subprocess.call(args) == 0 48 | 49 | 50 | def _install(archive_filename, install_args=()): 51 | """Install Setuptools.""" 52 | with archive_context(archive_filename): 53 | # installing 54 | log.warn('Installing Setuptools') 55 | if not _python_cmd('setup.py', 'install', *install_args): 56 | log.warn('Something went wrong during the installation.') 57 | log.warn('See the error message above.') 58 | # exitcode will be 2 59 | return 2 60 | 61 | 62 | def _build_egg(egg, archive_filename, to_dir): 63 | """Build Setuptools egg.""" 64 | with archive_context(archive_filename): 65 | # building an egg 66 | log.warn('Building a Setuptools egg in %s', to_dir) 67 | _python_cmd('setup.py', '-q', 'bdist_egg', '--dist-dir', to_dir) 68 | # returning the result 69 | log.warn(egg) 70 | if not os.path.exists(egg): 71 | raise IOError('Could not build the egg.') 72 | 73 | 74 | class ContextualZipFile(zipfile.ZipFile): 75 | 76 | """Supplement ZipFile class to support context manager for Python 2.6.""" 77 | 78 | def __enter__(self): 79 | return self 80 | 81 | def __exit__(self, type, value, traceback): 82 | self.close() 83 | 84 | def __new__(cls, *args, **kwargs): 85 | """Construct a ZipFile or ContextualZipFile as appropriate.""" 86 | if hasattr(zipfile.ZipFile, '__exit__'): 87 | return zipfile.ZipFile(*args, **kwargs) 88 | return super(ContextualZipFile, cls).__new__(cls) 89 | 90 | 91 | @contextlib.contextmanager 92 | def archive_context(filename): 93 | """ 94 | Unzip filename to a temporary directory, set to the cwd. 95 | 96 | The unzipped target is cleaned up after. 97 | """ 98 | tmpdir = tempfile.mkdtemp() 99 | log.warn('Extracting in %s', tmpdir) 100 | old_wd = os.getcwd() 101 | try: 102 | os.chdir(tmpdir) 103 | with ContextualZipFile(filename) as archive: 104 | archive.extractall() 105 | 106 | # going in the directory 107 | subdir = os.path.join(tmpdir, os.listdir(tmpdir)[0]) 108 | os.chdir(subdir) 109 | log.warn('Now working in %s', subdir) 110 | yield 111 | 112 | finally: 113 | os.chdir(old_wd) 114 | shutil.rmtree(tmpdir) 115 | 116 | 117 | def _do_download(version, download_base, to_dir, download_delay): 118 | """Download Setuptools.""" 119 | egg = os.path.join(to_dir, 'setuptools-%s-py%d.%d.egg' 120 | % (version, sys.version_info[0], sys.version_info[1])) 121 | if not os.path.exists(egg): 122 | archive = download_setuptools(version, download_base, 123 | to_dir, download_delay) 124 | _build_egg(egg, archive, to_dir) 125 | sys.path.insert(0, egg) 126 | 127 | # Remove previously-imported pkg_resources if present (see 128 | # https://bitbucket.org/pypa/setuptools/pull-request/7/ for details). 129 | if 'pkg_resources' in sys.modules: 130 | _unload_pkg_resources() 131 | 132 | import setuptools 133 | setuptools.bootstrap_install_from = egg 134 | 135 | 136 | def use_setuptools( 137 | version=DEFAULT_VERSION, download_base=DEFAULT_URL, 138 | to_dir=DEFAULT_SAVE_DIR, download_delay=15): 139 | """ 140 | Ensure that a setuptools version is installed. 141 | 142 | Return None. Raise SystemExit if the requested version 143 | or later cannot be installed. 144 | """ 145 | version = _resolve_version(version) 146 | to_dir = os.path.abspath(to_dir) 147 | 148 | # prior to importing, capture the module state for 149 | # representative modules. 150 | rep_modules = 'pkg_resources', 'setuptools' 151 | imported = set(sys.modules).intersection(rep_modules) 152 | 153 | try: 154 | import pkg_resources 155 | pkg_resources.require("setuptools>=" + version) 156 | # a suitable version is already installed 157 | return 158 | except ImportError: 159 | # pkg_resources not available; setuptools is not installed; download 160 | pass 161 | except pkg_resources.DistributionNotFound: 162 | # no version of setuptools was found; allow download 163 | pass 164 | except pkg_resources.VersionConflict as VC_err: 165 | if imported: 166 | _conflict_bail(VC_err, version) 167 | 168 | # otherwise, unload pkg_resources to allow the downloaded version to 169 | # take precedence. 170 | del pkg_resources 171 | _unload_pkg_resources() 172 | 173 | return _do_download(version, download_base, to_dir, download_delay) 174 | 175 | 176 | def _conflict_bail(VC_err, version): 177 | """ 178 | Setuptools was imported prior to invocation, so it is 179 | unsafe to unload it. Bail out. 180 | """ 181 | conflict_tmpl = textwrap.dedent(""" 182 | The required version of setuptools (>={version}) is not available, 183 | and can't be installed while this script is running. Please 184 | install a more recent version first, using 185 | 'easy_install -U setuptools'. 186 | 187 | (Currently using {VC_err.args[0]!r}) 188 | """) 189 | msg = conflict_tmpl.format(**locals()) 190 | sys.stderr.write(msg) 191 | sys.exit(2) 192 | 193 | 194 | def _unload_pkg_resources(): 195 | del_modules = [ 196 | name for name in sys.modules 197 | if name.startswith('pkg_resources') 198 | ] 199 | for mod_name in del_modules: 200 | del sys.modules[mod_name] 201 | 202 | 203 | def _clean_check(cmd, target): 204 | """ 205 | Run the command to download target. 206 | 207 | If the command fails, clean up before re-raising the error. 208 | """ 209 | try: 210 | subprocess.check_call(cmd) 211 | except subprocess.CalledProcessError: 212 | if os.access(target, os.F_OK): 213 | os.unlink(target) 214 | raise 215 | 216 | 217 | def download_file_powershell(url, target): 218 | """ 219 | Download the file at url to target using Powershell. 220 | 221 | Powershell will validate trust. 222 | Raise an exception if the command cannot complete. 223 | """ 224 | target = os.path.abspath(target) 225 | ps_cmd = ( 226 | "[System.Net.WebRequest]::DefaultWebProxy.Credentials = " 227 | "[System.Net.CredentialCache]::DefaultCredentials; " 228 | '(new-object System.Net.WebClient).DownloadFile("%(url)s", "%(target)s")' 229 | % locals() 230 | ) 231 | cmd = [ 232 | 'powershell', 233 | '-Command', 234 | ps_cmd, 235 | ] 236 | _clean_check(cmd, target) 237 | 238 | 239 | def has_powershell(): 240 | """Determine if Powershell is available.""" 241 | if platform.system() != 'Windows': 242 | return False 243 | cmd = ['powershell', '-Command', 'echo test'] 244 | with open(os.path.devnull, 'wb') as devnull: 245 | try: 246 | subprocess.check_call(cmd, stdout=devnull, stderr=devnull) 247 | except Exception: 248 | return False 249 | return True 250 | download_file_powershell.viable = has_powershell 251 | 252 | 253 | def download_file_curl(url, target): 254 | cmd = ['curl', url, '--silent', '--output', target] 255 | _clean_check(cmd, target) 256 | 257 | 258 | def has_curl(): 259 | cmd = ['curl', '--version'] 260 | with open(os.path.devnull, 'wb') as devnull: 261 | try: 262 | subprocess.check_call(cmd, stdout=devnull, stderr=devnull) 263 | except Exception: 264 | return False 265 | return True 266 | download_file_curl.viable = has_curl 267 | 268 | 269 | def download_file_wget(url, target): 270 | cmd = ['wget', url, '--quiet', '--output-document', target] 271 | _clean_check(cmd, target) 272 | 273 | 274 | def has_wget(): 275 | cmd = ['wget', '--version'] 276 | with open(os.path.devnull, 'wb') as devnull: 277 | try: 278 | subprocess.check_call(cmd, stdout=devnull, stderr=devnull) 279 | except Exception: 280 | return False 281 | return True 282 | download_file_wget.viable = has_wget 283 | 284 | 285 | def download_file_insecure(url, target): 286 | """Use Python to download the file, without connection authentication.""" 287 | src = urlopen(url) 288 | try: 289 | # Read all the data in one block. 290 | data = src.read() 291 | finally: 292 | src.close() 293 | 294 | # Write all the data in one block to avoid creating a partial file. 295 | with open(target, "wb") as dst: 296 | dst.write(data) 297 | download_file_insecure.viable = lambda: True 298 | 299 | 300 | def get_best_downloader(): 301 | downloaders = ( 302 | download_file_powershell, 303 | download_file_curl, 304 | download_file_wget, 305 | download_file_insecure, 306 | ) 307 | viable_downloaders = (dl for dl in downloaders if dl.viable()) 308 | return next(viable_downloaders, None) 309 | 310 | 311 | def download_setuptools( 312 | version=DEFAULT_VERSION, download_base=DEFAULT_URL, 313 | to_dir=DEFAULT_SAVE_DIR, delay=15, 314 | downloader_factory=get_best_downloader): 315 | """ 316 | Download setuptools from a specified location and return its filename. 317 | 318 | `version` should be a valid setuptools version number that is available 319 | as an sdist for download under the `download_base` URL (which should end 320 | with a '/'). `to_dir` is the directory where the egg will be downloaded. 321 | `delay` is the number of seconds to pause before an actual download 322 | attempt. 323 | 324 | ``downloader_factory`` should be a function taking no arguments and 325 | returning a function for downloading a URL to a target. 326 | """ 327 | version = _resolve_version(version) 328 | # making sure we use the absolute path 329 | to_dir = os.path.abspath(to_dir) 330 | zip_name = "setuptools-%s.zip" % version 331 | url = download_base + zip_name 332 | saveto = os.path.join(to_dir, zip_name) 333 | if not os.path.exists(saveto): # Avoid repeated downloads 334 | log.warn("Downloading %s", url) 335 | downloader = downloader_factory() 336 | downloader(url, saveto) 337 | return os.path.realpath(saveto) 338 | 339 | 340 | def _resolve_version(version): 341 | """ 342 | Resolve LATEST version 343 | """ 344 | if version is not LATEST: 345 | return version 346 | 347 | resp = urlopen('https://pypi.python.org/pypi/setuptools/json') 348 | with contextlib.closing(resp): 349 | try: 350 | charset = resp.info().get_content_charset() 351 | except Exception: 352 | # Python 2 compat; assume UTF-8 353 | charset = 'UTF-8' 354 | reader = codecs.getreader(charset) 355 | doc = json.load(reader(resp)) 356 | 357 | return str(doc['info']['version']) 358 | 359 | 360 | def _build_install_args(options): 361 | """ 362 | Build the arguments to 'python setup.py install' on the setuptools package. 363 | 364 | Returns list of command line arguments. 365 | """ 366 | return ['--user'] if options.user_install else [] 367 | 368 | 369 | def _parse_args(): 370 | """Parse the command line for options.""" 371 | parser = optparse.OptionParser() 372 | parser.add_option( 373 | '--user', dest='user_install', action='store_true', default=False, 374 | help='install in user site package (requires Python 2.6 or later)') 375 | parser.add_option( 376 | '--download-base', dest='download_base', metavar="URL", 377 | default=DEFAULT_URL, 378 | help='alternative URL from where to download the setuptools package') 379 | parser.add_option( 380 | '--insecure', dest='downloader_factory', action='store_const', 381 | const=lambda: download_file_insecure, default=get_best_downloader, 382 | help='Use internal, non-validating downloader' 383 | ) 384 | parser.add_option( 385 | '--version', help="Specify which version to download", 386 | default=DEFAULT_VERSION, 387 | ) 388 | parser.add_option( 389 | '--to-dir', 390 | help="Directory to save (and re-use) package", 391 | default=DEFAULT_SAVE_DIR, 392 | ) 393 | options, args = parser.parse_args() 394 | # positional arguments are ignored 395 | return options 396 | 397 | 398 | def _download_args(options): 399 | """Return args for download_setuptools function from cmdline args.""" 400 | return dict( 401 | version=options.version, 402 | download_base=options.download_base, 403 | downloader_factory=options.downloader_factory, 404 | to_dir=options.to_dir, 405 | ) 406 | 407 | 408 | def main(): 409 | """Install or upgrade setuptools and EasyInstall.""" 410 | options = _parse_args() 411 | archive = download_setuptools(**_download_args(options)) 412 | return _install(archive, _build_install_args(options)) 413 | 414 | if __name__ == '__main__': 415 | sys.exit(main()) 416 | -------------------------------------------------------------------------------- /requirements_dev.txt: -------------------------------------------------------------------------------- 1 | wheel 2 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [aliases] 2 | test=pytest 3 | 4 | [bdist_wheel] 5 | universal=1 6 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 5 | Copyright © Jussi Timperi 6 | 7 | This program is free software: you can redistribute it and/or modify 8 | it under the terms of the GNU General Public License as published by 9 | the Free Software Foundation, either version 3 of the License, or 10 | (at your option) any later version. 11 | 12 | This program is distributed in the hope that it will be useful, 13 | but WITHOUT ANY WARRANTY; without even the implied warranty of 14 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 15 | GNU General Public License for more details. 16 | 17 | You should have received a copy of the GNU General Public License 18 | along 19 | """ 20 | 21 | try: 22 | from setuptools import setup 23 | except ImportError: 24 | import ez_setup 25 | ez_setup.use_setuptools() 26 | from setuptools import setup 27 | 28 | 29 | with open('README.rst') as readme_file: 30 | readme = readme_file.read() 31 | 32 | REQUIREMENTS = [ 33 | 'binstruct', 34 | 'bitarray', 35 | 'click', 36 | 'pillow' 37 | ] 38 | 39 | setup( 40 | name="evic", 41 | version="0.1", 42 | author="Jussi Timperi", 43 | author_email="jussi.timperi@iki.fi", 44 | description=("Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini."), 45 | license="GPL", 46 | keywords="ecig electronic cigarette evic joyetech presa wismec", 47 | url="https://github.com/Ban3/python-evic", 48 | packages=['evic'], 49 | setup_requires=['pytest-runner'], 50 | tests_require=['pytest'], 51 | install_requires=REQUIREMENTS, 52 | data_files=[('udev', ['udev/99-nuvoton-hid.rules'])], 53 | long_description=readme, 54 | classifiers=[ 55 | "Development Status :: 4 - Beta", 56 | "Topic :: Utilities", 57 | "License :: OSI Approved :: GNU General Public License v3 (GPLv3)", 58 | 'Programming Language :: Python :: 2.7', 59 | 'Programming Language :: Python :: 3', 60 | 'Programming Language :: Python :: 3.3', 61 | 'Programming Language :: Python :: 3.4', 62 | 'Programming Language :: Python :: 3.5', 63 | ], 64 | extras_require={ 65 | 'USB': ['hidapi>=0.7.99'], 66 | }, 67 | entry_points={ 68 | 'console_scripts': [ 69 | 'evic-convert=evic.cli:convert', 70 | 'evic=evic.cli:main', 71 | 'evic-usb=evic.cli:usb [USB]'], 72 | }, 73 | ) 74 | -------------------------------------------------------------------------------- /testdata/helloworld.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ban3/python-evic/176cf0b076db331cf79dcab4232abd1158b183fa/testdata/helloworld.bin -------------------------------------------------------------------------------- /testdata/src/helloworld/Makefile: -------------------------------------------------------------------------------- 1 | TARGET = helloworld 2 | 3 | OBJS = main.o 4 | 5 | include $(EVICSDK)/make/Base.mk 6 | -------------------------------------------------------------------------------- /testdata/src/helloworld/main.c: -------------------------------------------------------------------------------- 1 | /* 2 | * This file is part of eVic SDK. 3 | * 4 | * eVic SDK is free software: you can redistribute it and/or modify 5 | * it under the terms of the GNU General Public License as published by 6 | * the Free Software Foundation, either version 3 of the License, or 7 | * (at your option) any later version. 8 | * 9 | * eVic SDK 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 | * 14 | * You should have received a copy of the GNU General Public License 15 | * along with eVic SDK. If not, see . 16 | * 17 | * Copyright (C) 2015-2016 ReservedField 18 | */ 19 | 20 | #include 21 | #include 22 | #include 23 | 24 | int main() { 25 | // Blit text 26 | Display_PutText(8, 56, "Hello,\nWorld.", FONT_DEJAVU_8PT); 27 | 28 | // Update display 29 | Display_Update(); 30 | } 31 | -------------------------------------------------------------------------------- /testdata/test_dataflash.bin: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Ban3/python-evic/176cf0b076db331cf79dcab4232abd1158b183fa/testdata/test_dataflash.bin -------------------------------------------------------------------------------- /tests/test_aprom.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import pytest 21 | 22 | import evic 23 | 24 | 25 | class TestAPROM: 26 | 27 | def test_aprom_convert(self): 28 | with open("testdata/helloworld.bin", "rb") as apromfile: 29 | aprom_data = bytearray(apromfile.read()) 30 | aprom = evic.APROM(aprom_data) 31 | aprom_unencrypted = evic.APROM(aprom.convert()) 32 | 33 | assert aprom_data == aprom_unencrypted.convert() 34 | 35 | def test_aprom_verify(self): 36 | with open("testdata/helloworld.bin", "rb") as apromfile: 37 | aprom = evic.APROM(apromfile.read()) 38 | aprom_unencrypted = evic.APROM(aprom.convert()) 39 | 40 | aprom_unencrypted.verify(['E052'], 106) 41 | 42 | with pytest.raises(evic.APROMError): 43 | aprom_unencrypted.verify(['W007'], 106) 44 | aprom_unencrypted.verify(['E052'], 999) 45 | -------------------------------------------------------------------------------- /tests/test_cli.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | from click.testing import CliRunner 21 | 22 | from evic import cli 23 | 24 | 25 | class TestCli: 26 | 27 | def test_cli_convert(self): 28 | with open('testdata/helloworld.bin', 'rb') as apromfile: 29 | aprom_data = apromfile.read() 30 | 31 | runner = CliRunner() 32 | with runner.isolated_filesystem(): 33 | with open('test_aprom.bin', 'wb') as apromfile: 34 | apromfile.write(aprom_data) 35 | 36 | result = runner.invoke(cli.convert, ['test_aprom.bin', 37 | '-o', 38 | 'test_aprom_unencrypted.bin']) 39 | assert result.exit_code == 0 40 | 41 | result = runner.invoke(cli.convert, ['test_aprom_unencrypted.bin', 42 | '-o', 43 | 'test_aprom2.bin']) 44 | assert result.exit_code == 0 45 | 46 | with open('test_aprom2.bin', 'rb') as apromfile: 47 | assert aprom_data == apromfile.read() 48 | -------------------------------------------------------------------------------- /tests/test_dataflash.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import struct 21 | import pytest 22 | 23 | import evic 24 | 25 | 26 | class TestDataFlash: 27 | 28 | def test_dataflash_from_file(self): 29 | with open("testdata/test_dataflash.bin", "rb") as dataflashfile: 30 | dataflash = evic.DataFlash(bytearray(dataflashfile.read()), 0) 31 | assert dataflash.hw_version == 103 32 | assert dataflash.bootflag == 0 33 | assert dataflash.product_id == "E052" 34 | assert dataflash.fw_version == 300 35 | 36 | def test_set_dataflash_attributes(self): 37 | with open("testdata/test_dataflash.bin", "rb") as dataflashfile: 38 | dataflash = evic.DataFlash(bytearray(dataflashfile.read()), 0) 39 | dataflash.bootflag = 1 40 | dataflash.hw_version = 106 41 | 42 | assert dataflash.bootflag == 1 43 | assert dataflash.array[9] == 1 44 | assert dataflash.hw_version == 106 45 | assert struct.unpack("=I", bytes(dataflash.array[4:8]))[0] == 106 46 | 47 | def test_dataflash_verify(self): 48 | with open("testdata/test_dataflash.bin", "rb") as dataflashfile: 49 | dataflash = evic.DataFlash(bytearray(dataflashfile.read()), 0) 50 | checksum = sum(dataflash.array) 51 | 52 | dataflash.verify(checksum) 53 | 54 | with pytest.raises(evic.DataFlashError): 55 | dataflash.verify(0) 56 | -------------------------------------------------------------------------------- /tests/test_device.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | Evic is a USB programmer for devices based on the Joyetech Evic VTC Mini. 4 | Copyright © Jussi Timperi 5 | 6 | This program is free software: you can redistribute it and/or modify 7 | it under the terms of the GNU General Public License as published by 8 | the Free Software Foundation, either version 3 of the License, or 9 | (at your option) any later version. 10 | 11 | This program is distributed in the hope that it will be useful, 12 | but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | GNU General Public License for more details. 15 | 16 | You should have received a copy of the GNU General Public License 17 | along with this program. If not, see . 18 | """ 19 | 20 | import evic 21 | 22 | 23 | class TestDevice: 24 | 25 | def test_hidtransfer_hidcmd(self): 26 | read_df_cmd = bytearray(b'5\x0e\x00\x00\x00\x00\x00\x08\x00\x00HIDCc\x01\x00\x00') 27 | write_df_cmd = bytearray(b'S\x0e\x00\x00\x00\x00\x00\x08\x00\x00HIDC\x81\x01\x00\x00') 28 | reset_cmd = bytearray(b'\xb4\x0e\x00\x00\x00\x00\x00\x00\x00\x00HIDC\xda\x01\x00\x00') 29 | write_aprom_cmd = bytearray(b'\xc3\x0e\x00\x00\x00\x00\x00\x00\x00\x00HIDC\xe9\x01\x00\x00') 30 | 31 | assert evic.HIDTransfer.hidcmd(0xC3, 0, 0) == write_aprom_cmd 32 | assert evic.HIDTransfer.hidcmd(0xB4, 0, 0) == reset_cmd 33 | assert evic.HIDTransfer.hidcmd(0x35, 0, 2048) == read_df_cmd 34 | assert evic.HIDTransfer.hidcmd(0x53, 0, 2048) == write_df_cmd 35 | -------------------------------------------------------------------------------- /tox.ini: -------------------------------------------------------------------------------- 1 | [tox] 2 | envlist = py26, py27, py33, py34, py35 3 | 4 | [testenv] 5 | deps = 6 | setuptools>=19.6 7 | setenv = 8 | PYTHONPATH = {toxinidir}:{toxinidir}/evic 9 | commands = python setup.py test 10 | -------------------------------------------------------------------------------- /udev/99-nuvoton-hid.rules: -------------------------------------------------------------------------------- 1 | # HIDAPI/libusb 2 | SUBSYSTEM=="usb", ATTRS{idVendor}=="0416", ATTRS{idProduct}=="5020", MODE="0666" 3 | 4 | # HIDAPI/hidraw 5 | KERNEL=="hidraw*", ATTRS{busnum}=="1", ATTRS{idVendor}=="0416", ATTRS{idProduct}=="5020", MODE="0666" 6 | --------------------------------------------------------------------------------