├── .github └── workflows │ └── python-package.yaml ├── .gitignore ├── LICENSE.md ├── Pipfile ├── README.md ├── examples ├── basic_usage.py ├── custom_ssl_session.py ├── download_motions.py ├── download_playback_video.py ├── network_config.py ├── response │ ├── GetAlarmMotion.json │ ├── GetDSTInfo.json │ ├── GetDevInfo.json │ ├── GetEnc.json │ ├── GetGeneralSystem.json │ ├── GetHddInfo.json │ ├── GetMask.json │ ├── GetNetworkAdvanced.json │ ├── GetNetworkDDNS.json │ ├── GetNetworkEmail.json │ ├── GetNetworkFtp.json │ ├── GetNetworkGeneral.json │ ├── GetNetworkNTP.json │ ├── GetNetworkPush.json │ ├── GetOnline.json │ ├── GetOsd.json │ ├── GetPerformance.json │ ├── GetPtzCheckState.json │ ├── GetPtzPresets.json │ ├── GetRec.json │ ├── GetUser.json │ ├── Login.json │ ├── Logout.json │ ├── PtzCheck.json │ ├── PtzCtrl.json │ ├── Reboot.json │ ├── SetAdvImageSettings.json │ ├── SetImageSettings.json │ └── SetPtzPreset.json ├── stream_gui.py ├── streaming_video.py └── video_review_gui.py ├── make-and-publish-package.sh ├── reolinkapi ├── __init__.py ├── camera.py ├── handlers │ ├── __init__.py │ ├── api_handler.py │ └── rest_handler.py ├── mixins │ ├── __init__.py │ ├── alarm.py │ ├── device.py │ ├── display.py │ ├── download.py │ ├── image.py │ ├── motion.py │ ├── network.py │ ├── nvrdownload.py │ ├── ptz.py │ ├── record.py │ ├── stream.py │ ├── system.py │ ├── user.py │ └── zoom.py └── utils │ ├── __init__.py │ ├── rtsp_client.py │ └── util.py ├── requirements.txt ├── setup.py └── tests └── test_camera.py /.github/workflows/python-package.yaml: -------------------------------------------------------------------------------- 1 | # This workflow will install Python dependencies, run tests and lint with a variety of Python versions 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python 3 | 4 | name: Python package 5 | 6 | on: 7 | push: 8 | branches: [ "master" ] 9 | pull_request: 10 | branches: [ "master" ] 11 | 12 | jobs: 13 | build: 14 | 15 | runs-on: ubuntu-latest 16 | strategy: 17 | fail-fast: false 18 | matrix: 19 | python-version: ["3.12", "3.13"] 20 | 21 | steps: 22 | - uses: actions/checkout@v4 23 | - name: Set up Python ${{ matrix.python-version }} 24 | uses: actions/setup-python@v3 25 | with: 26 | python-version: ${{ matrix.python-version }} 27 | - name: Install dependencies 28 | run: | 29 | python -m pip install --upgrade pip 30 | python -m pip install flake8 pytest build 31 | if [ -f requirements.txt ]; then pip install -r requirements.txt; fi 32 | - name: Lint with flake8 33 | run: | 34 | # stop the build if there are Python syntax errors or undefined names 35 | flake8 . --count --select=E9,F63,F7,F82 --show-source --statistics 36 | # exit-zero treats all errors as warnings. The GitHub editor is 127 chars wide 37 | # flake8 . --count --exit-zero --max-complexity=10 --max-line-length=127 --statistics 38 | - name: Build 39 | run: | 40 | python -m build 41 | # - name: Test with pytest 42 | # run: | 43 | # pytest 44 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | secrets.cfg 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *,cover 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | 55 | # Sphinx documentation 56 | docs/_build/ 57 | 58 | # PyBuilder 59 | target/ 60 | 61 | .idea/ 62 | venv/ -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | 2 | GNU GENERAL PUBLIC LICENSE 3 | Version 3, 29 June 2007 4 | 5 | Copyright (C) 2007 Free Software Foundation, Inc. 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The GNU General Public License is a free, copyleft license for 12 | software and other kinds of works. 13 | 14 | The licenses for most software and other practical works are designed 15 | to take away your freedom to share and change the works. By contrast, 16 | the GNU General Public License is intended to guarantee your freedom to 17 | share and change all versions of a program--to make sure it remains free 18 | software for all its users. We, the Free Software Foundation, use the 19 | GNU General Public License for most of our software; it applies also to 20 | any other work released this way by its authors. You can apply it to 21 | your programs, too. 22 | 23 | When we speak of free software, we are referring to freedom, not 24 | price. Our General Public Licenses are designed to make sure that you 25 | have the freedom to distribute copies of free software (and charge for 26 | them if you wish), that you receive source code or can get it if you 27 | want it, that you can change the software or use pieces of it in new 28 | free programs, and that you know you can do these things. 29 | 30 | To protect your rights, we need to prevent others from denying you 31 | these rights or asking you to surrender the rights. Therefore, you have 32 | certain responsibilities if you distribute copies of the software, or if 33 | you modify it: responsibilities to respect the freedom of others. 34 | 35 | For example, if you distribute copies of such a program, whether 36 | gratis or for a fee, you must pass on to the recipients the same 37 | freedoms that you received. You must make sure that they, too, receive 38 | or can get the source code. And you must show them these terms so they 39 | know their rights. 40 | 41 | Developers that use the GNU GPL protect your rights with two steps: 42 | (1) assert copyright on the software, and (2) offer you this License 43 | giving you legal permission to copy, distribute and/or modify it. 44 | 45 | For the developers' and authors' protection, the GPL clearly explains 46 | that there is no warranty for this free software. For both users' and 47 | authors' sake, the GPL requires that modified versions be marked as 48 | changed, so that their problems will not be attributed erroneously to 49 | authors of previous versions. 50 | 51 | Some devices are designed to deny users access to install or run 52 | modified versions of the software inside them, although the manufacturer 53 | can do so. This is fundamentally incompatible with the aim of 54 | protecting users' freedom to change the software. The systematic 55 | pattern of such abuse occurs in the area of products for individuals to 56 | use, which is precisely where it is most unacceptable. Therefore, we 57 | have designed this version of the GPL to prohibit the practice for those 58 | products. If such problems arise substantially in other domains, we 59 | stand ready to extend this provision to those domains in future versions 60 | of the GPL, as needed to protect the freedom of users. 61 | 62 | Finally, every program is threatened constantly by software patents. 63 | States should not allow patents to restrict development and use of 64 | software on general-purpose computers, but in those that do, we wish to 65 | avoid the special danger that patents applied to a free program could 66 | make it effectively proprietary. To prevent this, the GPL assures that 67 | patents cannot be used to render the program non-free. 68 | 69 | The precise terms and conditions for copying, distribution and 70 | modification follow. 71 | 72 | TERMS AND CONDITIONS 73 | 74 | 0. Definitions. 75 | 76 | "This License" refers to version 3 of the GNU General Public License. 77 | 78 | "Copyright" also means copyright-like laws that apply to other kinds of 79 | works, such as semiconductor masks. 80 | 81 | "The Program" refers to any copyrightable work licensed under this 82 | License. Each licensee is addressed as "you". "Licensees" and 83 | "recipients" may be individuals or organizations. 84 | 85 | To "modify" a work means to copy from or adapt all or part of the work 86 | in a fashion requiring copyright permission, other than the making of an 87 | exact copy. The resulting work is called a "modified version" of the 88 | earlier work or a work "based on" the earlier work. 89 | 90 | A "covered work" means either the unmodified Program or a work based 91 | on the Program. 92 | 93 | To "propagate" a work means to do anything with it that, without 94 | permission, would make you directly or secondarily liable for 95 | infringement under applicable copyright law, except executing it on a 96 | computer or modifying a private copy. Propagation includes copying, 97 | distribution (with or without modification), making available to the 98 | public, and in some countries other activities as well. 99 | 100 | To "convey" a work means any kind of propagation that enables other 101 | parties to make or receive copies. Mere interaction with a user through 102 | a computer network, with no transfer of a copy, is not conveying. 103 | 104 | An interactive user interface displays "Appropriate Legal Notices" 105 | to the extent that it includes a convenient and prominently visible 106 | feature that (1) displays an appropriate copyright notice, and (2) 107 | tells the user that there is no warranty for the work (except to the 108 | extent that warranties are provided), that licensees may convey the 109 | work under this License, and how to view a copy of this License. If 110 | the interface presents a list of user commands or options, such as a 111 | menu, a prominent item in the list meets this criterion. 112 | 113 | 1. Source Code. 114 | 115 | The "source code" for a work means the preferred form of the work 116 | for making modifications to it. "Object code" means any non-source 117 | form of a work. 118 | 119 | A "Standard Interface" means an interface that either is an official 120 | standard defined by a recognized standards body, or, in the case of 121 | interfaces specified for a particular programming language, one that 122 | is widely used among developers working in that language. 123 | 124 | The "System Libraries" of an executable work include anything, other 125 | than the work as a whole, that (a) is included in the normal form of 126 | packaging a Major Component, but which is not part of that Major 127 | Component, and (b) serves only to enable use of the work with that 128 | Major Component, or to implement a Standard Interface for which an 129 | implementation is available to the public in source code form. A 130 | "Major Component", in this context, means a major essential component 131 | (kernel, window system, and so on) of the specific operating system 132 | (if any) on which the executable work runs, or a compiler used to 133 | produce the work, or an object code interpreter used to run it. 134 | 135 | The "Corresponding Source" for a work in object code form means all 136 | the source code needed to generate, install, and (for an executable 137 | work) run the object code and to modify the work, including scripts to 138 | control those activities. However, it does not include the work's 139 | System Libraries, or general-purpose tools or generally available free 140 | programs which are used unmodified in performing those activities but 141 | which are not part of the work. For example, Corresponding Source 142 | includes interface definition files associated with source files for 143 | the work, and the source code for shared libraries and dynamically 144 | linked subprograms that the work is specifically designed to require, 145 | such as by intimate data communication or control flow between those 146 | subprograms and other parts of the work. 147 | 148 | The Corresponding Source need not include anything that users 149 | can regenerate automatically from other parts of the Corresponding 150 | Source. 151 | 152 | The Corresponding Source for a work in source code form is that 153 | same work. 154 | 155 | 2. Basic Permissions. 156 | 157 | All rights granted under this License are granted for the term of 158 | copyright on the Program, and are irrevocable provided the stated 159 | conditions are met. This License explicitly affirms your unlimited 160 | permission to run the unmodified Program. The output from running a 161 | covered work is covered by this License only if the output, given its 162 | content, constitutes a covered work. This License acknowledges your 163 | rights of fair use or other equivalent, as provided by copyright law. 164 | 165 | You may make, run and propagate covered works that you do not 166 | convey, without conditions so long as your license otherwise remains 167 | in force. You may convey covered works to others for the sole purpose 168 | of having them make modifications exclusively for you, or provide you 169 | with facilities for running those works, provided that you comply with 170 | the terms of this License in conveying all material for which you do 171 | not control copyright. Those thus making or running the covered works 172 | for you must do so exclusively on your behalf, under your direction 173 | and control, on terms that prohibit them from making any copies of 174 | your copyrighted material outside their relationship with you. 175 | 176 | Conveying under any other circumstances is permitted solely under 177 | the conditions stated below. Sublicensing is not allowed; section 10 178 | makes it unnecessary. 179 | 180 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 181 | 182 | No covered work shall be deemed part of an effective technological 183 | measure under any applicable law fulfilling obligations under article 184 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 185 | similar laws prohibiting or restricting circumvention of such 186 | measures. 187 | 188 | When you convey a covered work, you waive any legal power to forbid 189 | circumvention of technological measures to the extent such circumvention 190 | is effected by exercising rights under this License with respect to 191 | the covered work, and you disclaim any intention to limit operation or 192 | modification of the work as a means of enforcing, against the work's 193 | users, your or third parties' legal rights to forbid circumvention of 194 | technological measures. 195 | 196 | 4. Conveying Verbatim Copies. 197 | 198 | You may convey verbatim copies of the Program's source code as you 199 | receive it, in any medium, provided that you conspicuously and 200 | appropriately publish on each copy an appropriate copyright notice; 201 | keep intact all notices stating that this License and any 202 | non-permissive terms added in accord with section 7 apply to the code; 203 | keep intact all notices of the absence of any warranty; and give all 204 | recipients a copy of this License along with the Program. 205 | 206 | You may charge any price or no price for each copy that you convey, 207 | and you may offer support or warranty protection for a fee. 208 | 209 | 5. Conveying Modified Source Versions. 210 | 211 | You may convey a work based on the Program, or the modifications to 212 | produce it from the Program, in the form of source code under the 213 | terms of section 4, provided that you also meet all of these conditions: 214 | 215 | a) The work must carry prominent notices stating that you modified 216 | it, and giving a relevant date. 217 | 218 | b) The work must carry prominent notices stating that it is 219 | released under this License and any conditions added under section 220 | 7. This requirement modifies the requirement in section 4 to 221 | "keep intact all notices". 222 | 223 | c) You must license the entire work, as a whole, under this 224 | License to anyone who comes into possession of a copy. This 225 | License will therefore apply, along with any applicable section 7 226 | additional terms, to the whole of the work, and all its parts, 227 | regardless of how they are packaged. This License gives no 228 | permission to license the work in any other way, but it does not 229 | invalidate such permission if you have separately received it. 230 | 231 | d) If the work has interactive user interfaces, each must display 232 | Appropriate Legal Notices; however, if the Program has interactive 233 | interfaces that do not display Appropriate Legal Notices, your 234 | work need not make them do so. 235 | 236 | A compilation of a covered work with other separate and independent 237 | works, which are not by their nature extensions of the covered work, 238 | and which are not combined with it such as to form a larger program, 239 | in or on a volume of a storage or distribution medium, is called an 240 | "aggregate" if the compilation and its resulting copyright are not 241 | used to limit the access or legal rights of the compilation's users 242 | beyond what the individual works permit. Inclusion of a covered work 243 | in an aggregate does not cause this License to apply to the other 244 | parts of the aggregate. 245 | 246 | 6. Conveying Non-Source Forms. 247 | 248 | You may convey a covered work in object code form under the terms 249 | of sections 4 and 5, provided that you also convey the 250 | machine-readable Corresponding Source under the terms of this License, 251 | in one of these ways: 252 | 253 | a) Convey the object code in, or embodied in, a physical product 254 | (including a physical distribution medium), accompanied by the 255 | Corresponding Source fixed on a durable physical medium 256 | customarily used for software interchange. 257 | 258 | b) Convey the object code in, or embodied in, a physical product 259 | (including a physical distribution medium), accompanied by a 260 | written offer, valid for at least three years and valid for as 261 | long as you offer spare parts or customer support for that product 262 | model, to give anyone who possesses the object code either (1) a 263 | copy of the Corresponding Source for all the software in the 264 | product that is covered by this License, on a durable physical 265 | medium customarily used for software interchange, for a price no 266 | more than your reasonable cost of physically performing this 267 | conveying of source, or (2) access to copy the 268 | Corresponding Source from a network server at no charge. 269 | 270 | c) Convey individual copies of the object code with a copy of the 271 | written offer to provide the Corresponding Source. This 272 | alternative is allowed only occasionally and noncommercially, and 273 | only if you received the object code with such an offer, in accord 274 | with subsection 6b. 275 | 276 | d) Convey the object code by offering access from a designated 277 | place (gratis or for a charge), and offer equivalent access to the 278 | Corresponding Source in the same way through the same place at no 279 | further charge. You need not require recipients to copy the 280 | Corresponding Source along with the object code. If the place to 281 | copy the object code is a network server, the Corresponding Source 282 | may be on a different server (operated by you or a third party) 283 | that supports equivalent copying facilities, provided you maintain 284 | clear directions next to the object code saying where to find the 285 | Corresponding Source. Regardless of what server hosts the 286 | Corresponding Source, you remain obligated to ensure that it is 287 | available for as long as needed to satisfy these requirements. 288 | 289 | e) Convey the object code using peer-to-peer transmission, provided 290 | you inform other peers where the object code and Corresponding 291 | Source of the work are being offered to the general public at no 292 | charge under subsection 6d. 293 | 294 | A separable portion of the object code, whose source code is excluded 295 | from the Corresponding Source as a System Library, need not be 296 | included in conveying the object code work. 297 | 298 | A "User Product" is either (1) a "consumer product", which means any 299 | tangible personal property which is normally used for personal, family, 300 | or household purposes, or (2) anything designed or sold for incorporation 301 | into a dwelling. In determining whether a product is a consumer product, 302 | doubtful cases shall be resolved in favor of coverage. For a particular 303 | product received by a particular user, "normally used" refers to a 304 | typical or common use of that class of product, regardless of the status 305 | of the particular user or of the way in which the particular user 306 | actually uses, or expects or is expected to use, the product. A product 307 | is a consumer product regardless of whether the product has substantial 308 | commercial, industrial or non-consumer uses, unless such uses represent 309 | the only significant mode of use of the product. 310 | 311 | "Installation Information" for a User Product means any methods, 312 | procedures, authorization keys, or other information required to install 313 | and execute modified versions of a covered work in that User Product from 314 | a modified version of its Corresponding Source. The information must 315 | suffice to ensure that the continued functioning of the modified object 316 | code is in no case prevented or interfered with solely because 317 | modification has been made. 318 | 319 | If you convey an object code work under this section in, or with, or 320 | specifically for use in, a User Product, and the conveying occurs as 321 | part of a transaction in which the right of possession and use of the 322 | User Product is transferred to the recipient in perpetuity or for a 323 | fixed term (regardless of how the transaction is characterized), the 324 | Corresponding Source conveyed under this section must be accompanied 325 | by the Installation Information. But this requirement does not apply 326 | if neither you nor any third party retains the ability to install 327 | modified object code on the User Product (for example, the work has 328 | been installed in ROM). 329 | 330 | The requirement to provide Installation Information does not include a 331 | requirement to continue to provide support service, warranty, or updates 332 | for a work that has been modified or installed by the recipient, or for 333 | the User Product in which it has been modified or installed. Access to a 334 | network may be denied when the modification itself materially and 335 | adversely affects the operation of the network or violates the rules and 336 | protocols for communication across the network. 337 | 338 | Corresponding Source conveyed, and Installation Information provided, 339 | in accord with this section must be in a format that is publicly 340 | documented (and with an implementation available to the public in 341 | source code form), and must require no special password or key for 342 | unpacking, reading or copying. 343 | 344 | 7. Additional Terms. 345 | 346 | "Additional permissions" are terms that supplement the terms of this 347 | License by making exceptions from one or more of its conditions. 348 | Additional permissions that are applicable to the entire Program shall 349 | be treated as though they were included in this License, to the extent 350 | that they are valid under applicable law. If additional permissions 351 | apply only to part of the Program, that part may be used separately 352 | under those permissions, but the entire Program remains governed by 353 | this License without regard to the additional permissions. 354 | 355 | When you convey a copy of a covered work, you may at your option 356 | remove any additional permissions from that copy, or from any part of 357 | it. (Additional permissions may be written to require their own 358 | removal in certain cases when you modify the work.) You may place 359 | additional permissions on material, added by you to a covered work, 360 | for which you have or can give appropriate copyright permission. 361 | 362 | Notwithstanding any other provision of this License, for material you 363 | add to a covered work, you may (if authorized by the copyright holders of 364 | that material) supplement the terms of this License with terms: 365 | 366 | a) Disclaiming warranty or limiting liability differently from the 367 | terms of sections 15 and 16 of this License; or 368 | 369 | b) Requiring preservation of specified reasonable legal notices or 370 | author attributions in that material or in the Appropriate Legal 371 | Notices displayed by works containing it; or 372 | 373 | c) Prohibiting misrepresentation of the origin of that material, or 374 | requiring that modified versions of such material be marked in 375 | reasonable ways as different from the original version; or 376 | 377 | d) Limiting the use for publicity purposes of names of licensors or 378 | authors of the material; or 379 | 380 | e) Declining to grant rights under trademark law for use of some 381 | trade names, trademarks, or service marks; or 382 | 383 | f) Requiring indemnification of licensors and authors of that 384 | material by anyone who conveys the material (or modified versions of 385 | it) with contractual assumptions of liability to the recipient, for 386 | any liability that these contractual assumptions directly impose on 387 | those licensors and authors. 388 | 389 | All other non-permissive additional terms are considered "further 390 | restrictions" within the meaning of section 10. If the Program as you 391 | received it, or any part of it, contains a notice stating that it is 392 | governed by this License along with a term that is a further 393 | restriction, you may remove that term. If a license document contains 394 | a further restriction but permits relicensing or conveying under this 395 | License, you may add to a covered work material governed by the terms 396 | of that license document, provided that the further restriction does 397 | not survive such relicensing or conveying. 398 | 399 | If you add terms to a covered work in accord with this section, you 400 | must place, in the relevant source files, a statement of the 401 | additional terms that apply to those files, or a notice indicating 402 | where to find the applicable terms. 403 | 404 | Additional terms, permissive or non-permissive, may be stated in the 405 | form of a separately written license, or stated as exceptions; 406 | the above requirements apply either way. 407 | 408 | 8. Termination. 409 | 410 | You may not propagate or modify a covered work except as expressly 411 | provided under this License. Any attempt otherwise to propagate or 412 | modify it is void, and will automatically terminate your rights under 413 | this License (including any patent licenses granted under the third 414 | paragraph of section 11). 415 | 416 | However, if you cease all violation of this License, then your 417 | license from a particular copyright holder is reinstated (a) 418 | provisionally, unless and until the copyright holder explicitly and 419 | finally terminates your license, and (b) permanently, if the copyright 420 | holder fails to notify you of the violation by some reasonable means 421 | prior to 60 days after the cessation. 422 | 423 | Moreover, your license from a particular copyright holder is 424 | reinstated permanently if the copyright holder notifies you of the 425 | violation by some reasonable means, this is the first time you have 426 | received notice of violation of this License (for any work) from that 427 | copyright holder, and you cure the violation prior to 30 days after 428 | your receipt of the notice. 429 | 430 | Termination of your rights under this section does not terminate the 431 | licenses of parties who have received copies or rights from you under 432 | this License. If your rights have been terminated and not permanently 433 | reinstated, you do not qualify to receive new licenses for the same 434 | material under section 10. 435 | 436 | 9. Acceptance Not Required for Having Copies. 437 | 438 | You are not required to accept this License in order to receive or 439 | run a copy of the Program. Ancillary propagation of a covered work 440 | occurring solely as a consequence of using peer-to-peer transmission 441 | to receive a copy likewise does not require acceptance. However, 442 | nothing other than this License grants you permission to propagate or 443 | modify any covered work. These actions infringe copyright if you do 444 | not accept this License. Therefore, by modifying or propagating a 445 | covered work, you indicate your acceptance of this License to do so. 446 | 447 | 10. Automatic Licensing of Downstream Recipients. 448 | 449 | Each time you convey a covered work, the recipient automatically 450 | receives a license from the original licensors, to run, modify and 451 | propagate that work, subject to this License. You are not responsible 452 | for enforcing compliance by third parties with this License. 453 | 454 | An "entity transaction" is a transaction transferring control of an 455 | organization, or substantially all assets of one, or subdividing an 456 | organization, or merging organizations. If propagation of a covered 457 | work results from an entity transaction, each party to that 458 | transaction who receives a copy of the work also receives whatever 459 | licenses to the work the party's predecessor in interest had or could 460 | give under the previous paragraph, plus a right to possession of the 461 | Corresponding Source of the work from the predecessor in interest, if 462 | the predecessor has it or can get it with reasonable efforts. 463 | 464 | You may not impose any further restrictions on the exercise of the 465 | rights granted or affirmed under this License. For example, you may 466 | not impose a license fee, royalty, or other charge for exercise of 467 | rights granted under this License, and you may not initiate litigation 468 | (including a cross-claim or counterclaim in a lawsuit) alleging that 469 | any patent claim is infringed by making, using, selling, offering for 470 | sale, or importing the Program or any portion of it. 471 | 472 | 11. Patents. 473 | 474 | A "contributor" is a copyright holder who authorizes use under this 475 | License of the Program or a work on which the Program is based. The 476 | work thus licensed is called the contributor's "contributor version". 477 | 478 | A contributor's "essential patent claims" are all patent claims 479 | owned or controlled by the contributor, whether already acquired or 480 | hereafter acquired, that would be infringed by some manner, permitted 481 | by this License, of making, using, or selling its contributor version, 482 | but do not include claims that would be infringed only as a 483 | consequence of further modification of the contributor version. For 484 | purposes of this definition, "control" includes the right to grant 485 | patent sublicenses in a manner consistent with the requirements of 486 | this License. 487 | 488 | Each contributor grants you a non-exclusive, worldwide, royalty-free 489 | patent license under the contributor's essential patent claims, to 490 | make, use, sell, offer for sale, import and otherwise run, modify and 491 | propagate the contents of its contributor version. 492 | 493 | In the following three paragraphs, a "patent license" is any express 494 | agreement or commitment, however denominated, not to enforce a patent 495 | (such as an express permission to practice a patent or covenant not to 496 | sue for patent infringement). To "grant" such a patent license to a 497 | party means to make such an agreement or commitment not to enforce a 498 | patent against the party. 499 | 500 | If you convey a covered work, knowingly relying on a patent license, 501 | and the Corresponding Source of the work is not available for anyone 502 | to copy, free of charge and under the terms of this License, through a 503 | publicly available network server or other readily accessible means, 504 | then you must either (1) cause the Corresponding Source to be so 505 | available, or (2) arrange to deprive yourself of the benefit of the 506 | patent license for this particular work, or (3) arrange, in a manner 507 | consistent with the requirements of this License, to extend the patent 508 | license to downstream recipients. "Knowingly relying" means you have 509 | actual knowledge that, but for the patent license, your conveying the 510 | covered work in a country, or your recipient's use of the covered work 511 | in a country, would infringe one or more identifiable patents in that 512 | country that you have reason to believe are valid. 513 | 514 | If, pursuant to or in connection with a single transaction or 515 | arrangement, you convey, or propagate by procuring conveyance of, a 516 | covered work, and grant a patent license to some of the parties 517 | receiving the covered work authorizing them to use, propagate, modify 518 | or convey a specific copy of the covered work, then the patent license 519 | you grant is automatically extended to all recipients of the covered 520 | work and works based on it. 521 | 522 | A patent license is "discriminatory" if it does not include within 523 | the scope of its coverage, prohibits the exercise of, or is 524 | conditioned on the non-exercise of one or more of the rights that are 525 | specifically granted under this License. You may not convey a covered 526 | work if you are a party to an arrangement with a third party that is 527 | in the business of distributing software, under which you make payment 528 | to the third party based on the extent of your activity of conveying 529 | the work, and under which the third party grants, to any of the 530 | parties who would receive the covered work from you, a discriminatory 531 | patent license (a) in connection with copies of the covered work 532 | conveyed by you (or copies made from those copies), or (b) primarily 533 | for and in connection with specific products or compilations that 534 | contain the covered work, unless you entered into that arrangement, 535 | or that patent license was granted, prior to 28 March 2007. 536 | 537 | Nothing in this License shall be construed as excluding or limiting 538 | any implied license or other defenses to infringement that may 539 | otherwise be available to you under applicable patent law. 540 | 541 | 12. No Surrender of Others' Freedom. 542 | 543 | If conditions are imposed on you (whether by court order, agreement or 544 | otherwise) that contradict the conditions of this License, they do not 545 | excuse you from the conditions of this License. If you cannot convey a 546 | covered work so as to satisfy simultaneously your obligations under this 547 | License and any other pertinent obligations, then as a consequence you may 548 | not convey it at all. For example, if you agree to terms that obligate you 549 | to collect a royalty for further conveying from those to whom you convey 550 | the Program, the only way you could satisfy both those terms and this 551 | License would be to refrain entirely from conveying the Program. 552 | 553 | 13. Use with the GNU Affero General Public License. 554 | 555 | Notwithstanding any other provision of this License, you have 556 | permission to link or combine any covered work with a work licensed 557 | under version 3 of the GNU Affero General Public License into a single 558 | combined work, and to convey the resulting work. The terms of this 559 | License will continue to apply to the part which is the covered work, 560 | but the special requirements of the GNU Affero General Public License, 561 | section 13, concerning interaction through a network will apply to the 562 | combination as such. 563 | 564 | 14. Revised Versions of this License. 565 | 566 | The Free Software Foundation may publish revised and/or new versions of 567 | the GNU General Public License from time to time. Such new versions will 568 | be similar in spirit to the present version, but may differ in detail to 569 | address new problems or concerns. 570 | 571 | Each version is given a distinguishing version number. If the 572 | Program specifies that a certain numbered version of the GNU General 573 | Public License "or any later version" applies to it, you have the 574 | option of following the terms and conditions either of that numbered 575 | version or of any later version published by the Free Software 576 | Foundation. If the Program does not specify a version number of the 577 | GNU General Public License, you may choose any version ever published 578 | by the Free Software Foundation. 579 | 580 | If the Program specifies that a proxy can decide which future 581 | versions of the GNU General Public License can be used, that proxy's 582 | public statement of acceptance of a version permanently authorizes you 583 | to choose that version for the Program. 584 | 585 | Later license versions may give you additional or different 586 | permissions. However, no additional obligations are imposed on any 587 | author or copyright holder as a result of your choosing to follow a 588 | later version. 589 | 590 | 15. Disclaimer of Warranty. 591 | 592 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 593 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 594 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 595 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 596 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 597 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 598 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 599 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 600 | 601 | 16. Limitation of Liability. 602 | 603 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 604 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 605 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 606 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 607 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 608 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 609 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 610 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 611 | SUCH DAMAGES. 612 | 613 | 17. Interpretation of Sections 15 and 16. 614 | 615 | If the disclaimer of warranty and limitation of liability provided 616 | above cannot be given local legal effect according to their terms, 617 | reviewing courts shall apply local law that most closely approximates 618 | an absolute waiver of all civil liability in connection with the 619 | Program, unless a warranty or assumption of liability accompanies a 620 | copy of the Program in return for a fee. 621 | 622 | END OF TERMS AND CONDITIONS 623 | 624 | How to Apply These Terms to Your New Programs 625 | 626 | If you develop a new program, and you want it to be of the greatest 627 | possible use to the public, the best way to achieve this is to make it 628 | free software which everyone can redistribute and change under these terms. 629 | 630 | To do so, attach the following notices to the program. It is safest 631 | to attach them to the start of each source file to most effectively 632 | state the exclusion of warranty; and each file should have at least 633 | the "copyright" line and a pointer to where the full notice is found. 634 | 635 | 636 | Copyright (C) 637 | 638 | This program is free software: you can redistribute it and/or modify 639 | it under the terms of the GNU General Public License as published by 640 | the Free Software Foundation, either version 3 of the License, or 641 | (at your option) any later version. 642 | 643 | This program is distributed in the hope that it will be useful, 644 | but WITHOUT ANY WARRANTY; without even the implied warranty of 645 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 646 | GNU General Public License for more details. 647 | 648 | You should have received a copy of the GNU General Public License 649 | along with this program. If not, see . 650 | 651 | Also add information on how to contact you by electronic and paper mail. 652 | 653 | If the program does terminal interaction, make it output a short 654 | notice like this when it starts in an interactive mode: 655 | 656 | {project} Copyright (C) {year} {fullname} 657 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 658 | This is free software, and you are welcome to redistribute it 659 | under certain conditions; type `show c' for details. 660 | 661 | The hypothetical commands `show w' and `show c' should show the appropriate 662 | parts of the General Public License. Of course, your program's commands 663 | might be different; for a GUI interface, you would use an "about box". 664 | 665 | You should also get your employer (if you work as a programmer) or school, 666 | if any, to sign a "copyright disclaimer" for the program, if necessary. 667 | For more information on this, and how to apply and follow the GNU GPL, see 668 | . 669 | 670 | The GNU General Public License does not permit incorporating your program 671 | into proprietary programs. If your program is a subroutine library, you 672 | may consider it more useful to permit linking proprietary applications with 673 | the library. If this is what you want to do, use the GNU Lesser General 674 | Public License instead of this License. But first, please read 675 | . 676 | -------------------------------------------------------------------------------- /Pipfile: -------------------------------------------------------------------------------- 1 | [[source]] 2 | name = "pypi" 3 | url = "https://pypi.org/simple" 4 | verify_ssl = true 5 | 6 | [dev-packages] 7 | 8 | [packages] 9 | pillow = "*" 10 | pyyaml = "*" 11 | requests = "*" 12 | numpy = "*" 13 | opencv-python = "*" 14 | pysocks = "*" 15 | 16 | [requires] 17 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

Reolink Python Api Client

2 | 3 |

4 | Reolink Approval 5 | GitHub 6 | GitHub tag (latest SemVer) 7 | PyPI 8 | Discord 9 |

10 | 11 | --- 12 | 13 | A Reolink Camera client written in Python. This repository's purpose **(with Reolink's full support)** is to deliver a complete API for the Reolink Cameras, 14 | although they have a basic API document - it does not satisfy the need for extensive camera communication. 15 | 16 | Check out our documentation for more information on how to use the software at [https://reolink.oleaintueri.com](https://reolink.oleaintueri.com) 17 | 18 | 19 | Other Supported Languages: 20 | - Go: [reolinkapigo](https://github.com/ReolinkCameraAPI/reolinkapigo) 21 | 22 | ### Join us on Discord 23 | 24 | https://discord.gg/8z3fdAmZJP 25 | 26 | 27 | ### Sponsorship 28 | 29 | 30 | 31 | [Oleaintueri](https://oleaintueri.com) is sponsoring the development and maintenance of these projects within their organisation. 32 | 33 | 34 | --- 35 | 36 | ### Get started 37 | 38 | Implement a "Camera" object by passing it an IP address, Username and Password. By instantiating the object, it will try retrieve a login token from the Reolink Camera. This token is necessary to interact with the Camera using other commands. 39 | 40 | See the `examples` directory. 41 | 42 | ### Using the library as a Python Module 43 | 44 | Install the package via PyPi 45 | 46 | pip install reolinkapi 47 | 48 | Install from GitHub 49 | 50 | pip install git+https://github.com/ReolinkCameraAPI/reolinkapipy.git 51 | 52 | If you want to include the video streaming functionality you need to include the streaming "extra" dependencies 53 | 54 | pip install 'reolinkapi[streaming]' 55 | 56 | ## Contributors 57 | 58 | --- 59 | 60 | ### Styling and Standards 61 | 62 | This project intends to stick with [PEP8](https://www.python.org/dev/peps/pep-0008/) 63 | 64 | ### How can I become a contributor? 65 | 66 | #### Step 1 67 | 68 | Get the Restful API calls by looking through the HTTP Requests made in the camera's web UI. I use Google Chrome developer mode (ctr + shift + i) -> Network. 69 | 70 | #### Step 2 71 | 72 | - Fork the repository 73 | - pip install -r requirements.txt 74 | - Make your changes 75 | 76 | #### Step 3 77 | 78 | Make a pull request. 79 | 80 | ### API Requests Implementation Plan: 81 | 82 | Stream: 83 | - [X] Blocking RTSP stream 84 | - [X] Non-Blocking RTSP stream 85 | 86 | GET: 87 | - [X] Login 88 | - [X] Logout 89 | - [X] Display -> OSD 90 | - [X] Recording -> Encode (Clear and Fluent Stream) 91 | - [X] Recording -> Advance (Scheduling) 92 | - [X] Network -> General 93 | - [X] Network -> Advanced 94 | - [X] Network -> DDNS 95 | - [X] Network -> NTP 96 | - [X] Network -> E-mail 97 | - [X] Network -> FTP 98 | - [X] Network -> Push 99 | - [X] Network -> WIFI 100 | - [X] Alarm -> Motion 101 | - [X] System -> General 102 | - [X] System -> DST 103 | - [X] System -> Information 104 | - [ ] System -> Maintenance 105 | - [X] System -> Performance 106 | - [ ] System -> Reboot 107 | - [X] User -> Online User 108 | - [X] User -> Add User 109 | - [X] User -> Manage User 110 | - [X] Device -> HDD/SD Card 111 | - [x] PTZ -> Presets, Calibration Status 112 | - [x] Zoom 113 | - [x] Focus 114 | - [ ] Image (Brightness, Contrast, Saturation, Hue, Sharp, Mirror, Rotate) 115 | - [ ] Advanced Image (Anti-flicker, Exposure, White Balance, DayNight, Backlight, LED light, 3D-NR) 116 | - [X] Image Data -> "Snap" Frame from Video Stream 117 | 118 | SET: 119 | - [X] Display -> OSD 120 | - [X] Recording -> Encode (Clear and Fluent Stream) 121 | - [ ] Recording -> Advance (Scheduling) 122 | - [X] Network -> General 123 | - [X] Network -> Advanced 124 | - [ ] Network -> DDNS 125 | - [ ] Network -> NTP 126 | - [ ] Network -> E-mail 127 | - [ ] Network -> FTP 128 | - [ ] Network -> Push 129 | - [X] Network -> WIFI 130 | - [ ] Alarm -> Motion 131 | - [ ] System -> General 132 | - [ ] System -> DST 133 | - [X] System -> Reboot 134 | - [X] User -> Online User 135 | - [X] User -> Add User 136 | - [X] User -> Manage User 137 | - [X] Device -> HDD/SD Card (Format) 138 | - [x] PTZ (including calibrate) 139 | - [x] Zoom 140 | - [x] Focus 141 | - [X] Image (Brightness, Contrast, Saturation, Hue, Sharp, Mirror, Rotate) 142 | - [X] Advanced Image (Anti-flicker, Exposure, White Balance, DayNight, Backlight, LED light, 3D-NR) 143 | 144 | ### Supported Cameras 145 | 146 | Any Reolink camera that has a web UI should work. The other's requiring special Reolink clients 147 | do not work and is not supported here. 148 | 149 | - RLC-411WS 150 | - RLC-423 151 | - RLC-420-5MP 152 | - RLC-410-5MP 153 | - RLC-510A 154 | - RLC-520 155 | - RLC-823A 156 | - C1-Pro 157 | - D400 158 | - E1 Zoom 159 | 160 | -------------------------------------------------------------------------------- /examples/basic_usage.py: -------------------------------------------------------------------------------- 1 | import reolinkapi 2 | 3 | if __name__ == "__main__": 4 | cam = reolinkapi.Camera("192.168.0.102", defer_login=True) 5 | 6 | # must first login since I defer have deferred the login process 7 | cam.login() 8 | 9 | dst = cam.get_dst() 10 | ok = cam.add_user("foo", "bar", "admin") 11 | alarm = cam.get_alarm_motion() 12 | cam.set_device_name(name='my_camera') -------------------------------------------------------------------------------- /examples/custom_ssl_session.py: -------------------------------------------------------------------------------- 1 | from reolinkapi import Camera 2 | 3 | import urllib3 4 | import requests 5 | from urllib3.util import create_urllib3_context 6 | 7 | class CustomSSLContextHTTPAdapter(requests.adapters.HTTPAdapter): 8 | def __init__(self, ssl_context=None, **kwargs): 9 | self.ssl_context = ssl_context 10 | super().__init__(**kwargs) 11 | 12 | def init_poolmanager(self, connections, maxsize, block=False): 13 | self.poolmanager = urllib3.poolmanager.PoolManager( 14 | num_pools=connections, maxsize=maxsize, 15 | block=block, ssl_context=self.ssl_context) 16 | 17 | urllib3.disable_warnings() 18 | ctx = create_urllib3_context() 19 | ctx.load_default_certs() 20 | ctx.set_ciphers("AES128-GCM-SHA256") 21 | ctx.check_hostname = False 22 | 23 | session = requests.session() 24 | session.adapters.pop("https://", None) 25 | session.mount("https://", CustomSSLContextHTTPAdapter(ctx)) 26 | 27 | ## Add a custom http handler to add in different ciphers that may 28 | ## not be aloud by default in openssl which urlib uses 29 | cam = Camera("url", "user", "password", https=True, session=session) 30 | cam.reboot_camera() 31 | -------------------------------------------------------------------------------- /examples/download_motions.py: -------------------------------------------------------------------------------- 1 | """Downloads all motion events from camera from the past hour.""" 2 | import os 3 | from configparser import RawConfigParser 4 | from datetime import datetime as dt, timedelta 5 | from reolinkapi import Camera 6 | 7 | 8 | def read_config(props_path: str) -> dict: 9 | """Reads in a properties file into variables. 10 | 11 | NB! this config file is kept out of commits with .gitignore. The structure of this file is such: 12 | # secrets.cfg 13 | [camera] 14 | ip={ip_address} 15 | username={username} 16 | password={password} 17 | """ 18 | config = RawConfigParser() 19 | assert os.path.exists(props_path), f"Path does not exist: {props_path}" 20 | config.read(props_path) 21 | return config 22 | 23 | 24 | # Read in your ip, username, & password 25 | # (NB! you'll likely have to create this file. See tests/test_camera.py for details on structure) 26 | config = read_config('camera.cfg') 27 | 28 | ip = config.get('camera', 'ip') 29 | un = config.get('camera', 'username') 30 | pw = config.get('camera', 'password') 31 | 32 | # Connect to camera 33 | cam = Camera(ip, un, pw, https=True) 34 | 35 | start = dt.combine(dt.now(), dt.min.time()) 36 | end = dt.now() 37 | # Collect motion events between these timestamps for substream 38 | processed_motions = cam.get_motion_files(start=start, end=end, streamtype='main', channel=0) 39 | processed_motions += cam.get_motion_files(start=start, end=end, streamtype='main', channel=1) 40 | 41 | start = dt.now() - timedelta(days=1) 42 | end = dt.combine(start, dt.max.time()) 43 | processed_motions += cam.get_motion_files(start=start, end=end, streamtype='main', channel=1) 44 | 45 | 46 | output_files = [] 47 | for i, motion in enumerate(processed_motions): 48 | fname = motion['filename'] 49 | # Download the mp4 50 | print("Getting %s" % (fname)) 51 | output_path = os.path.join('/tmp/', fname.replace('/','_')) 52 | output_files += output_path 53 | if not os.path.isfile(output_path): 54 | resp = cam.get_file(fname, output_path=output_path) 55 | -------------------------------------------------------------------------------- /examples/download_playback_video.py: -------------------------------------------------------------------------------- 1 | """Downloads a video from camera from start to end time.""" 2 | import os 3 | from configparser import RawConfigParser 4 | from datetime import datetime as dt, timedelta 5 | from reolinkapi import Camera 6 | import requests 7 | import pandas as pd 8 | 9 | def read_config(props_path: str) -> dict: 10 | """Reads in a properties file into variables. 11 | 12 | NB! this config file is kept out of commits with .gitignore. The structure of this file is such: 13 | # secrets.cfg 14 | [camera] 15 | ip={ip_address} 16 | username={username} 17 | password={password} 18 | """ 19 | config = RawConfigParser() 20 | assert os.path.exists(props_path), f"Path does not exist: {props_path}" 21 | config.read(props_path) 22 | return config 23 | 24 | 25 | # Read in your ip, username, & password 26 | # (NB! you'll likely have to create this file. See tests/test_camera.py for details on structure) 27 | config = read_config('camera.cfg') 28 | 29 | ip = config.get('camera', 'ip') 30 | un = config.get('camera', 'username') 31 | pw = config.get('camera', 'password') 32 | 33 | # Connect to camera 34 | cam = Camera(ip, un, pw) 35 | 36 | start = dt.now() - timedelta(minutes=10) 37 | end = dt.now() - timedelta(minutes=9) 38 | channel = 0 39 | 40 | files = cam.get_playback_files(start=start, end=end, channel= channel) 41 | print(files) 42 | dl_dir = os.path.join(os.path.expanduser('~'), 'Downloads') 43 | for fname in files: 44 | print(fname) 45 | # Download the mp4 46 | cam.get_file(fname, output_path=os.path.join(dl_dir, fname)) 47 | -------------------------------------------------------------------------------- /examples/network_config.py: -------------------------------------------------------------------------------- 1 | import os 2 | from configparser import RawConfigParser 3 | from reolinkapi import Camera 4 | 5 | 6 | def read_config(props_path: str) -> dict: 7 | """Reads in a properties file into variables. 8 | 9 | NB! this config file is kept out of commits with .gitignore. The structure of this file is such: 10 | # secrets.cfg 11 | [camera] 12 | ip={ip_address} 13 | username={username} 14 | password={password} 15 | """ 16 | config = RawConfigParser() 17 | assert os.path.exists(props_path), f"Path does not exist: {props_path}" 18 | config.read(props_path) 19 | return config 20 | 21 | 22 | # Read in your ip, username, & password 23 | # (NB! you'll likely have to create this file. See tests/test_camera.py for details on structure) 24 | config = read_config('camera.cfg') 25 | 26 | ip = config.get('camera', 'ip') 27 | un = config.get('camera', 'username') 28 | pw = config.get('camera', 'password') 29 | 30 | # Connect to camera 31 | cam = Camera(ip, un, pw) 32 | 33 | # Set NTP 34 | cam.set_ntp(enable=True, interval=1440, port=123, server="time-b.nist.gov") 35 | 36 | # Get current network settings 37 | current_settings = cam.get_network_general() 38 | print("Current settings:", current_settings) 39 | 40 | # Configure DHCP 41 | cam.set_network_settings( 42 | ip="", 43 | gateway="", 44 | mask="", 45 | dns1="", 46 | dns2="", 47 | mac=current_settings[0]['value']['LocalLink']['mac'], 48 | use_dhcp=True, 49 | auto_dns=True 50 | ) 51 | 52 | # Configure static IP 53 | # cam.set_network_settings( 54 | # ip="192.168.1.102", 55 | # gateway="192.168.1.1", 56 | # mask="255.255.255.0", 57 | # dns1="8.8.8.8", 58 | # dns2="8.8.4.4", 59 | # mac=current_settings[0]['value']['LocalLink']['mac'], 60 | # use_dhcp=False, 61 | # auto_dns=False 62 | # ) -------------------------------------------------------------------------------- /examples/response/GetAlarmMotion.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetAlarm", 4 | "code": 0, 5 | "initial": { 6 | "Alarm": { 7 | "action": { "mail": 1, "push": 1, "recChannel": [0] }, 8 | "channel": 0, 9 | "enable": 1, 10 | "schedule": { 11 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 12 | }, 13 | "scope": { 14 | "cols": 80, 15 | "rows": 45, 16 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 17 | }, 18 | "sens": [ 19 | { 20 | "beginHour": 0, 21 | "beginMin": 0, 22 | "endHour": 6, 23 | "endMin": 0, 24 | "sensitivity": 10 25 | }, 26 | { 27 | "beginHour": 6, 28 | "beginMin": 0, 29 | "endHour": 12, 30 | "endMin": 0, 31 | "sensitivity": 10 32 | }, 33 | { 34 | "beginHour": 12, 35 | "beginMin": 0, 36 | "endHour": 18, 37 | "endMin": 0, 38 | "sensitivity": 10 39 | }, 40 | { 41 | "beginHour": 18, 42 | "beginMin": 0, 43 | "endHour": 23, 44 | "endMin": 59, 45 | "sensitivity": 10 46 | } 47 | ], 48 | "type": "md" 49 | } 50 | }, 51 | "range": { 52 | "Alarm": { 53 | "action": { "mail": "boolean", "push": "boolean", "recChannel": [0] }, 54 | "channel": 0, 55 | "enable": "boolean", 56 | "schedule": { "table": { "maxLen": 168, "minLen": 168 } }, 57 | "scope": { 58 | "cols": { "max": 80, "min": 80 }, 59 | "rows": { "max": 45, "min": 45 }, 60 | "table": { "maxLen": 8159 } 61 | }, 62 | "sens": [ 63 | { 64 | "beginHour": { "max": 23, "min": 0 }, 65 | "beginMin": { "max": 59, "min": 0 }, 66 | "endHour": { "max": 23, "min": 0 }, 67 | "endMin": { "max": 59, "min": 0 }, 68 | "id": 0, 69 | "sensitivity": { "max": 50, "min": 1 } 70 | }, 71 | { 72 | "beginHour": { "max": 23, "min": 0 }, 73 | "beginMin": { "max": 59, "min": 0 }, 74 | "endHour": { "max": 23, "min": 0 }, 75 | "endMin": { "max": 59, "min": 0 }, 76 | "id": 1, 77 | "sensitivity": { "max": 50, "min": 1 } 78 | }, 79 | { 80 | "beginHour": { "max": 23, "min": 0 }, 81 | "beginMin": { "max": 59, "min": 0 }, 82 | "endHour": { "max": 23, "min": 0 }, 83 | "endMin": { "max": 59, "min": 0 }, 84 | "id": 2, 85 | "sensitivity": { "max": 50, "min": 1 } 86 | }, 87 | { 88 | "beginHour": { "max": 23, "min": 0 }, 89 | "beginMin": { "max": 59, "min": 0 }, 90 | "endHour": { "max": 23, "min": 0 }, 91 | "endMin": { "max": 59, "min": 0 }, 92 | "id": 3, 93 | "sensitivity": { "max": 50, "min": 1 } 94 | } 95 | ], 96 | "type": "md" 97 | } 98 | }, 99 | "value": { 100 | "Alarm": { 101 | "action": { "mail": 1, "push": 1, "recChannel": [0] }, 102 | "channel": 0, 103 | "enable": 1, 104 | "schedule": { 105 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 106 | }, 107 | "scope": { 108 | "cols": 80, 109 | "rows": 45, 110 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 111 | }, 112 | "sens": [ 113 | { 114 | "beginHour": 0, 115 | "beginMin": 0, 116 | "endHour": 6, 117 | "endMin": 0, 118 | "id": 0, 119 | "sensitivity": 10 120 | }, 121 | { 122 | "beginHour": 6, 123 | "beginMin": 0, 124 | "endHour": 12, 125 | "endMin": 0, 126 | "id": 1, 127 | "sensitivity": 10 128 | }, 129 | { 130 | "beginHour": 12, 131 | "beginMin": 0, 132 | "endHour": 18, 133 | "endMin": 0, 134 | "id": 2, 135 | "sensitivity": 10 136 | }, 137 | { 138 | "beginHour": 18, 139 | "beginMin": 0, 140 | "endHour": 23, 141 | "endMin": 59, 142 | "id": 3, 143 | "sensitivity": 10 144 | } 145 | ], 146 | "type": "md" 147 | } 148 | } 149 | } 150 | ] 151 | -------------------------------------------------------------------------------- /examples/response/GetDSTInfo.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetTime", 4 | "code": 0, 5 | "value": { 6 | "Dst": { 7 | "enable": 1, 8 | "endHour": 2, 9 | "endMin": 0, 10 | "endMon": 11, 11 | "endSec": 0, 12 | "endWeek": 1, 13 | "endWeekday": 0, 14 | "offset": 1, 15 | "startHour": 2, 16 | "startMin": 0, 17 | "startMon": 3, 18 | "startSec": 0, 19 | "startWeek": 1, 20 | "startWeekday": 0 21 | }, 22 | "Time": { 23 | "day": 27, 24 | "hour": 18, 25 | "hourFmt": 0, 26 | "min": 50, 27 | "mon": 10, 28 | "sec": 46, 29 | "timeFmt": "MM/DD/YYYY", 30 | "timeZone": 21600, 31 | "year": 2020 32 | } 33 | } 34 | } 35 | ] 36 | -------------------------------------------------------------------------------- /examples/response/GetDevInfo.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetDevInfo", 4 | "code": 0, 5 | "value": { 6 | "DevInfo": { 7 | "B485": 0, 8 | "IOInputNum": 0, 9 | "IOOutputNum": 0, 10 | "audioNum": 0, 11 | "buildDay": "build 18081408", 12 | "cfgVer": "v2.0.0.0", 13 | "channelNum": 1, 14 | "detail": "IPC_3816M100000000100000", 15 | "diskNum": 1, 16 | "firmVer": "v2.0.0.1389_18081408", 17 | "hardVer": "IPC_3816M", 18 | "model": "RLC-411WS", 19 | "name": "Camera1_withpersonality", 20 | "serial": "00000000000000", 21 | "type": "IPC", 22 | "wifi": 1 23 | } 24 | } 25 | } 26 | ] 27 | -------------------------------------------------------------------------------- /examples/response/GetEnc.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetEnc", 4 | "code": 0, 5 | "initial": { 6 | "Enc": { 7 | "audio": 0, 8 | "channel": 0, 9 | "mainStream": { 10 | "bitRate": 4096, 11 | "frameRate": 15, 12 | "profile": "High", 13 | "size": "3072*1728" 14 | }, 15 | "subStream": { 16 | "bitRate": 160, 17 | "frameRate": 7, 18 | "profile": "High", 19 | "size": "640*360" 20 | } 21 | } 22 | }, 23 | "range": { 24 | "Enc": [ 25 | { 26 | "audio": "boolean", 27 | "mainStream": { 28 | "bitRate": [ 29 | 1024, 30 | 1536, 31 | 2048, 32 | 3072, 33 | 4096, 34 | 5120, 35 | 6144, 36 | 7168, 37 | 8192 38 | ], 39 | "default": { 40 | "bitRate": 4096, 41 | "frameRate": 15 42 | }, 43 | "frameRate": [ 44 | 20, 45 | 18, 46 | 16, 47 | 15, 48 | 12, 49 | 10, 50 | 8, 51 | 6, 52 | 4, 53 | 2 54 | ], 55 | "profile": [ 56 | "Base", 57 | "Main", 58 | "High" 59 | ], 60 | "size": "3072*1728" 61 | }, 62 | "subStream": { 63 | "bitRate": [ 64 | 64, 65 | 128, 66 | 160, 67 | 192, 68 | 256, 69 | 384, 70 | 512 71 | ], 72 | "default": { 73 | "bitRate": 160, 74 | "frameRate": 7 75 | }, 76 | "frameRate": [ 77 | 15, 78 | 10, 79 | 7, 80 | 4 81 | ], 82 | "profile": [ 83 | "Base", 84 | "Main", 85 | "High" 86 | ], 87 | "size": "640*360" 88 | } 89 | }, 90 | { 91 | "audio": "boolean", 92 | "mainStream": { 93 | "bitRate": [ 94 | 1024, 95 | 1536, 96 | 2048, 97 | 3072, 98 | 4096, 99 | 5120, 100 | 6144, 101 | 7168, 102 | 8192 103 | ], 104 | "default": { 105 | "bitRate": 4096, 106 | "frameRate": 15 107 | }, 108 | "frameRate": [ 109 | 20, 110 | 18, 111 | 16, 112 | 15, 113 | 12, 114 | 10, 115 | 8, 116 | 6, 117 | 4, 118 | 2 119 | ], 120 | "profile": [ 121 | "Base", 122 | "Main", 123 | "High" 124 | ], 125 | "size": "2592*1944" 126 | }, 127 | "subStream": { 128 | "bitRate": [ 129 | 64, 130 | 128, 131 | 160, 132 | 192, 133 | 256, 134 | 384, 135 | 512 136 | ], 137 | "default": { 138 | "bitRate": 160, 139 | "frameRate": 7 140 | }, 141 | "frameRate": [ 142 | 15, 143 | 10, 144 | 7, 145 | 4 146 | ], 147 | "profile": [ 148 | "Base", 149 | "Main", 150 | "High" 151 | ], 152 | "size": "640*360" 153 | } 154 | }, 155 | { 156 | "audio": "boolean", 157 | "mainStream": { 158 | "bitRate": [ 159 | 1024, 160 | 1536, 161 | 2048, 162 | 3072, 163 | 4096, 164 | 5120, 165 | 6144, 166 | 7168, 167 | 8192 168 | ], 169 | "default": { 170 | "bitRate": 3072, 171 | "frameRate": 15 172 | }, 173 | "frameRate": [ 174 | 30, 175 | 22, 176 | 20, 177 | 18, 178 | 16, 179 | 15, 180 | 12, 181 | 10, 182 | 8, 183 | 6, 184 | 4, 185 | 2 186 | ], 187 | "profile": [ 188 | "Base", 189 | "Main", 190 | "High" 191 | ], 192 | "size": "2560*1440" 193 | }, 194 | "subStream": { 195 | "bitRate": [ 196 | 64, 197 | 128, 198 | 160, 199 | 192, 200 | 256, 201 | 384, 202 | 512 203 | ], 204 | "default": { 205 | "bitRate": 160, 206 | "frameRate": 7 207 | }, 208 | "frameRate": [ 209 | 15, 210 | 10, 211 | 7, 212 | 4 213 | ], 214 | "profile": [ 215 | "Base", 216 | "Main", 217 | "High" 218 | ], 219 | "size": "640*360" 220 | } 221 | }, 222 | { 223 | "audio": "boolean", 224 | "mainStream": { 225 | "bitRate": [ 226 | 1024, 227 | 1536, 228 | 2048, 229 | 3072, 230 | 4096, 231 | 5120, 232 | 6144, 233 | 7168, 234 | 8192 235 | ], 236 | "default": { 237 | "bitRate": 3072, 238 | "frameRate": 15 239 | }, 240 | "frameRate": [ 241 | 30, 242 | 22, 243 | 20, 244 | 18, 245 | 16, 246 | 15, 247 | 12, 248 | 10, 249 | 8, 250 | 6, 251 | 4, 252 | 2 253 | ], 254 | "profile": [ 255 | "Base", 256 | "Main", 257 | "High" 258 | ], 259 | "size": "2048*1536" 260 | }, 261 | "subStream": { 262 | "bitRate": [ 263 | 64, 264 | 128, 265 | 160, 266 | 192, 267 | 256, 268 | 384, 269 | 512 270 | ], 271 | "default": { 272 | "bitRate": 160, 273 | "frameRate": 7 274 | }, 275 | "frameRate": [ 276 | 15, 277 | 10, 278 | 7, 279 | 4 280 | ], 281 | "profile": [ 282 | "Base", 283 | "Main", 284 | "High" 285 | ], 286 | "size": "640*360" 287 | } 288 | }, 289 | { 290 | "audio": "boolean", 291 | "mainStream": { 292 | "bitRate": [ 293 | 1024, 294 | 1536, 295 | 2048, 296 | 3072, 297 | 4096, 298 | 5120, 299 | 6144, 300 | 7168, 301 | 8192 302 | ], 303 | "default": { 304 | "bitRate": 3072, 305 | "frameRate": 15 306 | }, 307 | "frameRate": [ 308 | 30, 309 | 22, 310 | 20, 311 | 18, 312 | 16, 313 | 15, 314 | 12, 315 | 10, 316 | 8, 317 | 6, 318 | 4, 319 | 2 320 | ], 321 | "profile": [ 322 | "Base", 323 | "Main", 324 | "High" 325 | ], 326 | "size": "2304*1296" 327 | }, 328 | "subStream": { 329 | "bitRate": [ 330 | 64, 331 | 128, 332 | 160, 333 | 192, 334 | 256, 335 | 384, 336 | 512 337 | ], 338 | "default": { 339 | "bitRate": 160, 340 | "frameRate": 7 341 | }, 342 | "frameRate": [ 343 | 15, 344 | 10, 345 | 7, 346 | 4 347 | ], 348 | "profile": [ 349 | "Base", 350 | "Main", 351 | "High" 352 | ], 353 | "size": "640*360" 354 | } 355 | } 356 | ] 357 | }, 358 | "value": { 359 | "Enc": { 360 | "audio": 0, 361 | "channel": 0, 362 | "mainStream": { 363 | "bitRate": 2048, 364 | "frameRate": 20, 365 | "profile": "Main", 366 | "size": "3072*1728" 367 | }, 368 | "subStream": { 369 | "bitRate": 64, 370 | "frameRate": 4, 371 | "profile": "High", 372 | "size": "640*360" 373 | } 374 | } 375 | } 376 | } 377 | ] 378 | -------------------------------------------------------------------------------- /examples/response/GetGeneralSystem.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetTime", 4 | "code": 0, 5 | "initial": { 6 | "Dst": { 7 | "enable": 0, 8 | "endHour": 2, 9 | "endMin": 0, 10 | "endMon": 10, 11 | "endSec": 0, 12 | "endWeek": 5, 13 | "endWeekday": 0, 14 | "offset": 1, 15 | "startHour": 2, 16 | "startMin": 0, 17 | "startMon": 3, 18 | "startSec": 0, 19 | "startWeek": 2, 20 | "startWeekday": 0 21 | }, 22 | "Time": { 23 | "day": 1, 24 | "hour": 0, 25 | "hourFmt": 0, 26 | "min": 0, 27 | "mon": 0, 28 | "sec": 0, 29 | "timeFmt": "DD/MM/YYYY", 30 | "timeZone": 28800, 31 | "year": 0 32 | } 33 | }, 34 | "range": { 35 | "Dst": { 36 | "enable": "boolean", 37 | "endHour": { "max": 23, "min": 0 }, 38 | "endMin": { "max": 59, "min": 0 }, 39 | "endMon": { "max": 12, "min": 1 }, 40 | "endSec": { "max": 59, "min": 0 }, 41 | "endWeek": { "max": 5, "min": 1 }, 42 | "endWeekday": { "max": 6, "min": 0 }, 43 | "offset": { "max": 2, "min": 1 }, 44 | "startHour": { "max": 23, "min": 0 }, 45 | "startMin": { "max": 59, "min": 0 }, 46 | "startMon": { "max": 12, "min": 1 }, 47 | "startSec": { "max": 59, "min": 0 }, 48 | "startWeek": { "max": 5, "min": 1 }, 49 | "startWeekday": { "max": 6, "min": 0 } 50 | }, 51 | "Time": { 52 | "day": { "max": 31, "min": 1 }, 53 | "hour": { "max": 23, "min": 0 }, 54 | "hourFmt": { "max": 1, "min": 0 }, 55 | "min": { "max": 59, "min": 0 }, 56 | "mon": { "max": 12, "min": 1 }, 57 | "sec": { "max": 59, "min": 0 }, 58 | "timeFmt": ["MM/DD/YYYY", "YYYY/MM/DD", "DD/MM/YYYY"], 59 | "timeZone": { "max": 43200, "min": -46800 }, 60 | "year": { "max": 2100, "min": 1900 } 61 | } 62 | }, 63 | "value": { 64 | "Dst": { 65 | "enable": 1, 66 | "endHour": 2, 67 | "endMin": 0, 68 | "endMon": 11, 69 | "endSec": 0, 70 | "endWeek": 1, 71 | "endWeekday": 0, 72 | "offset": 1, 73 | "startHour": 2, 74 | "startMin": 0, 75 | "startMon": 3, 76 | "startSec": 0, 77 | "startWeek": 1, 78 | "startWeekday": 0 79 | }, 80 | "Time": { 81 | "day": 9, 82 | "hour": 15, 83 | "hourFmt": 0, 84 | "min": 33, 85 | "mon": 12, 86 | "sec": 58, 87 | "timeFmt": "MM/DD/YYYY", 88 | "timeZone": 21600, 89 | "year": 2020 90 | } 91 | } 92 | }, 93 | { 94 | "cmd": "GetNorm", 95 | "code": 0, 96 | "initial": { "norm": "NTSC" }, 97 | "range": { "norm": ["PAL", "NTSC"] }, 98 | "value": { "norm": "NTSC" } 99 | } 100 | ] 101 | -------------------------------------------------------------------------------- /examples/response/GetHddInfo.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetHddInfo", 4 | "code": 0, 5 | "value": { 6 | "HddInfo": [ 7 | { 8 | "capacity": 15181, 9 | "format": 1, 10 | "id": 0, 11 | "mount": 1, 12 | "size": 15181 13 | } 14 | ] 15 | } 16 | } 17 | ] 18 | -------------------------------------------------------------------------------- /examples/response/GetMask.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetMask", 4 | "code": 0, 5 | "initial": { 6 | "Mask": { 7 | "area": [ 8 | { 9 | "block": { 10 | "height": 0, 11 | "width": 0, 12 | "x": 0, 13 | "y": 0 14 | }, 15 | "screen": { 16 | "height": 0, 17 | "width": 0 18 | } 19 | } 20 | ], 21 | "channel": 0, 22 | "enable": 0 23 | } 24 | }, 25 | "range": { 26 | "Mask": { 27 | "channel": 0, 28 | "enable": "boolean", 29 | "maxAreas": 4 30 | } 31 | }, 32 | "value": { 33 | "Mask": { 34 | "area": null, 35 | "channel": 0, 36 | "enable": 0 37 | } 38 | } 39 | } 40 | ] 41 | -------------------------------------------------------------------------------- /examples/response/GetNetworkAdvanced.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetNetPort", 4 | "code": 0, 5 | "initial": { 6 | "NetPort": { 7 | "httpPort": 80, 8 | "httpsPort": 443, 9 | "mediaPort": 9000, 10 | "onvifPort": 8000, 11 | "rtmpPort": 1935, 12 | "rtspPort": 554 13 | } 14 | }, 15 | "range": { 16 | "NetPort": { 17 | "httpPort": { "max": 65535, "min": 1 }, 18 | "httpsPort": { "max": 65535, "min": 1 }, 19 | "mediaPort": { "max": 65535, "min": 1 }, 20 | "onvifPort": { "max": 65535, "min": 1 }, 21 | "rtmpPort": { "max": 65535, "min": 1 }, 22 | "rtspPort": { "max": 65535, "min": 1 } 23 | } 24 | }, 25 | "value": { 26 | "NetPort": { 27 | "httpPort": 80, 28 | "httpsPort": 443, 29 | "mediaPort": 9000, 30 | "onvifPort": 8000, 31 | "rtmpPort": 1935, 32 | "rtspPort": 554 33 | } 34 | } 35 | }, 36 | { "cmd": "GetUpnp", "code": 0, "value": { "Upnp": { "enable": 0 } } }, 37 | { 38 | "cmd": "GetP2p", 39 | "code": 0, 40 | "value": { "P2p": { "enable": 0, "uid": "99999999999999" } } 41 | } 42 | ] 43 | -------------------------------------------------------------------------------- /examples/response/GetNetworkDDNS.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetDdns", 4 | "code": 0, 5 | "value": { 6 | "Ddns": { 7 | "domain": "", 8 | "enable": 0, 9 | "password": "", 10 | "type": "no-ip", 11 | "userName": "" 12 | } 13 | } 14 | } 15 | ] 16 | -------------------------------------------------------------------------------- /examples/response/GetNetworkEmail.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetEmail", 4 | "code": 0, 5 | "value": { 6 | "Email": { 7 | "addr1": "", 8 | "addr2": "", 9 | "addr3": "", 10 | "attachment": "picture", 11 | "interval": "5 Minutes", 12 | "nickName": "", 13 | "password": "", 14 | "schedule": { 15 | "enable": 1, 16 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 17 | }, 18 | "smtpPort": 465, 19 | "smtpServer": "smtp.gmail.com", 20 | "ssl": 1, 21 | "userName": "" 22 | } 23 | } 24 | } 25 | ] 26 | -------------------------------------------------------------------------------- /examples/response/GetNetworkFtp.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetFtp", 4 | "code": 0, 5 | "value": { 6 | "Ftp": { 7 | "anonymous": 0, 8 | "interval": 30, 9 | "maxSize": 100, 10 | "mode": 0, 11 | "password": "", 12 | "port": 21, 13 | "remoteDir": "", 14 | "schedule": { 15 | "enable": 1, 16 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 17 | }, 18 | "server": "", 19 | "streamType": 0, 20 | "userName": "" 21 | } 22 | } 23 | } 24 | ] 25 | -------------------------------------------------------------------------------- /examples/response/GetNetworkGeneral.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetLocalLink", 4 | "code": 0, 5 | "value": { 6 | "LocalLink": { 7 | "activeLink": "LAN", 8 | "dns": { "auto": 1, "dns1": "192.168.255.4", "dns2": "192.168.255.4" }, 9 | "mac": "EC:71:DB:AA:59:CF", 10 | "static": { 11 | "gateway": "192.168.255.1", 12 | "ip": "192.168.255.58", 13 | "mask": "255.255.255.0" 14 | }, 15 | "type": "DHCP" 16 | } 17 | } 18 | } 19 | ] 20 | -------------------------------------------------------------------------------- /examples/response/GetNetworkNTP.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetNtp", 4 | "code": 0, 5 | "value": { 6 | "Ntp": { 7 | "enable": 1, 8 | "interval": 1440, 9 | "port": 123, 10 | "server": "ntp.moos.xyz" 11 | } 12 | } 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /examples/response/GetNetworkPush.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetPush", 4 | "code": 0, 5 | "value": { 6 | "Push": { 7 | "schedule": { 8 | "enable": 1, 9 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 10 | } 11 | } 12 | } 13 | } 14 | ] 15 | -------------------------------------------------------------------------------- /examples/response/GetOnline.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetOnline", 4 | "code": 0, 5 | "value": { 6 | "User": [ 7 | { 8 | "canbeDisconn": 0, 9 | "ip": "192.168.1.100", 10 | "level": "admin", 11 | "sessionId": 1000, 12 | "userName": "admin" 13 | } 14 | ] 15 | } 16 | } 17 | ] 18 | -------------------------------------------------------------------------------- /examples/response/GetOsd.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetOsd", 4 | "code": 0, 5 | "initial": { 6 | "Osd": { 7 | "bgcolor": 0, 8 | "channel": 0, 9 | "osdChannel": { 10 | "enable": 1, 11 | "name": "Camera1", 12 | "pos": "Lower Right" 13 | }, 14 | "osdTime": { 15 | "enable": 1, 16 | "pos": "Top Center" 17 | } 18 | } 19 | }, 20 | "range": { 21 | "Osd": { 22 | "bgcolor": "boolean", 23 | "channel": 0, 24 | "osdChannel": { 25 | "enable": "boolean", 26 | "name": { 27 | "maxLen": 31 28 | }, 29 | "pos": [ 30 | "Upper Left", 31 | "Top Center", 32 | "Upper Right", 33 | "Lower Left", 34 | "Bottom Center", 35 | "Lower Right" 36 | ] 37 | }, 38 | "osdTime": { 39 | "enable": "boolean", 40 | "pos": [ 41 | "Upper Left", 42 | "Top Center", 43 | "Upper Right", 44 | "Lower Left", 45 | "Bottom Center", 46 | "Lower Right" 47 | ] 48 | } 49 | } 50 | }, 51 | "value": { 52 | "Osd": { 53 | "bgcolor": 0, 54 | "channel": 0, 55 | "osdChannel": { 56 | "enable": 0, 57 | "name": "FarRight", 58 | "pos": "Lower Right" 59 | }, 60 | "osdTime": { 61 | "enable": 0, 62 | "pos": "Top Center" 63 | } 64 | } 65 | } 66 | } 67 | ] -------------------------------------------------------------------------------- /examples/response/GetPerformance.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetPerformance", 4 | "code": 0, 5 | "value": { 6 | "Performance": { 7 | "codecRate": 2154, 8 | "cpuUsed": 14, 9 | "netThroughput": 0 10 | } 11 | } 12 | } 13 | ] 14 | -------------------------------------------------------------------------------- /examples/response/GetPtzCheckState.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetPtzCheckState", 4 | "code": 0, 5 | "initial": { 6 | "PtzCheckState": 2 7 | }, 8 | "range": { 9 | "PtzCheckState": [ 10 | 0, 11 | 1, 12 | 2 13 | ] 14 | }, 15 | "value": { 16 | "PtzCheckState": 2 17 | } 18 | } 19 | ] 20 | -------------------------------------------------------------------------------- /examples/response/GetPtzPresets.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetPtzPreset", 4 | "code": 0, 5 | "initial": { 6 | "PtzPreset": [ 7 | { 8 | "channel": 0, 9 | "enable": 1, 10 | "id": 0, 11 | "imgName": "preset_00", 12 | "name": "namepos0" 13 | }, 14 | { 15 | "channel": 0, 16 | "enable": 1, 17 | "id": 1, 18 | "imgName": "preset_01", 19 | "name": "othernamepos1" 20 | }, 21 | { 22 | "channel": 0, 23 | "enable": 0, 24 | "id": 2, 25 | "imgName": "", 26 | "name": "pos3" 27 | }, 28 | { 29 | "channel": 0, 30 | "enable": 0, 31 | "id": 3, 32 | "imgName": "", 33 | "name": "pos4" 34 | }, 35 | { 36 | "channel": 0, 37 | "enable": 0, 38 | "id": 4, 39 | "imgName": "", 40 | "name": "pos5" 41 | }, 42 | { 43 | "channel": 0, 44 | "enable": 0, 45 | "id": 5, 46 | "imgName": "", 47 | "name": "pos6" 48 | }, 49 | { 50 | "channel": 0, 51 | "enable": 0, 52 | "id": 6, 53 | "imgName": "", 54 | "name": "pos7" 55 | }, 56 | { 57 | "channel": 0, 58 | "enable": 0, 59 | "id": 7, 60 | "imgName": "", 61 | "name": "pos8" 62 | }, 63 | { 64 | "channel": 0, 65 | "enable": 0, 66 | "id": 8, 67 | "imgName": "", 68 | "name": "pos9" 69 | }, 70 | { 71 | "channel": 0, 72 | "enable": 0, 73 | "id": 9, 74 | "imgName": "", 75 | "name": "pos10" 76 | }, 77 | { 78 | "channel": 0, 79 | "enable": 0, 80 | "id": 10, 81 | "imgName": "", 82 | "name": "pos11" 83 | }, 84 | { 85 | "channel": 0, 86 | "enable": 0, 87 | "id": 11, 88 | "imgName": "", 89 | "name": "pos12" 90 | }, 91 | { 92 | "channel": 0, 93 | "enable": 0, 94 | "id": 12, 95 | "imgName": "", 96 | "name": "pos13" 97 | }, 98 | { 99 | "channel": 0, 100 | "enable": 0, 101 | "id": 13, 102 | "imgName": "", 103 | "name": "pos14" 104 | }, 105 | { 106 | "channel": 0, 107 | "enable": 0, 108 | "id": 14, 109 | "imgName": "", 110 | "name": "pos15" 111 | }, 112 | { 113 | "channel": 0, 114 | "enable": 0, 115 | "id": 15, 116 | "imgName": "", 117 | "name": "pos16" 118 | }, 119 | { 120 | "channel": 0, 121 | "enable": 0, 122 | "id": 16, 123 | "imgName": "", 124 | "name": "pos17" 125 | }, 126 | { 127 | "channel": 0, 128 | "enable": 0, 129 | "id": 17, 130 | "imgName": "", 131 | "name": "pos18" 132 | }, 133 | { 134 | "channel": 0, 135 | "enable": 0, 136 | "id": 18, 137 | "imgName": "", 138 | "name": "pos19" 139 | }, 140 | { 141 | "channel": 0, 142 | "enable": 0, 143 | "id": 19, 144 | "imgName": "", 145 | "name": "pos20" 146 | }, 147 | { 148 | "channel": 0, 149 | "enable": 0, 150 | "id": 20, 151 | "imgName": "", 152 | "name": "pos21" 153 | }, 154 | { 155 | "channel": 0, 156 | "enable": 0, 157 | "id": 21, 158 | "imgName": "", 159 | "name": "pos22" 160 | }, 161 | { 162 | "channel": 0, 163 | "enable": 0, 164 | "id": 22, 165 | "imgName": "", 166 | "name": "pos23" 167 | }, 168 | { 169 | "channel": 0, 170 | "enable": 0, 171 | "id": 23, 172 | "imgName": "", 173 | "name": "pos24" 174 | }, 175 | { 176 | "channel": 0, 177 | "enable": 0, 178 | "id": 24, 179 | "imgName": "", 180 | "name": "pos25" 181 | }, 182 | { 183 | "channel": 0, 184 | "enable": 0, 185 | "id": 25, 186 | "imgName": "", 187 | "name": "pos26" 188 | }, 189 | { 190 | "channel": 0, 191 | "enable": 0, 192 | "id": 26, 193 | "imgName": "", 194 | "name": "pos27" 195 | }, 196 | { 197 | "channel": 0, 198 | "enable": 0, 199 | "id": 27, 200 | "imgName": "", 201 | "name": "pos28" 202 | }, 203 | { 204 | "channel": 0, 205 | "enable": 0, 206 | "id": 28, 207 | "imgName": "", 208 | "name": "pos29" 209 | }, 210 | { 211 | "channel": 0, 212 | "enable": 0, 213 | "id": 29, 214 | "imgName": "", 215 | "name": "pos30" 216 | }, 217 | { 218 | "channel": 0, 219 | "enable": 0, 220 | "id": 30, 221 | "imgName": "", 222 | "name": "pos31" 223 | }, 224 | { 225 | "channel": 0, 226 | "enable": 0, 227 | "id": 31, 228 | "imgName": "", 229 | "name": "pos32" 230 | }, 231 | { 232 | "channel": 0, 233 | "enable": 0, 234 | "id": 32, 235 | "imgName": "", 236 | "name": "pos33" 237 | }, 238 | { 239 | "channel": 0, 240 | "enable": 0, 241 | "id": 33, 242 | "imgName": "", 243 | "name": "pos34" 244 | }, 245 | { 246 | "channel": 0, 247 | "enable": 0, 248 | "id": 34, 249 | "imgName": "", 250 | "name": "pos35" 251 | }, 252 | { 253 | "channel": 0, 254 | "enable": 0, 255 | "id": 35, 256 | "imgName": "", 257 | "name": "pos36" 258 | }, 259 | { 260 | "channel": 0, 261 | "enable": 0, 262 | "id": 36, 263 | "imgName": "", 264 | "name": "pos37" 265 | }, 266 | { 267 | "channel": 0, 268 | "enable": 0, 269 | "id": 37, 270 | "imgName": "", 271 | "name": "pos38" 272 | }, 273 | { 274 | "channel": 0, 275 | "enable": 0, 276 | "id": 38, 277 | "imgName": "", 278 | "name": "pos39" 279 | }, 280 | { 281 | "channel": 0, 282 | "enable": 0, 283 | "id": 39, 284 | "imgName": "", 285 | "name": "pos40" 286 | }, 287 | { 288 | "channel": 0, 289 | "enable": 0, 290 | "id": 40, 291 | "imgName": "", 292 | "name": "pos41" 293 | }, 294 | { 295 | "channel": 0, 296 | "enable": 0, 297 | "id": 41, 298 | "imgName": "", 299 | "name": "pos42" 300 | }, 301 | { 302 | "channel": 0, 303 | "enable": 0, 304 | "id": 42, 305 | "imgName": "", 306 | "name": "pos43" 307 | }, 308 | { 309 | "channel": 0, 310 | "enable": 0, 311 | "id": 43, 312 | "imgName": "", 313 | "name": "pos44" 314 | }, 315 | { 316 | "channel": 0, 317 | "enable": 0, 318 | "id": 44, 319 | "imgName": "", 320 | "name": "pos45" 321 | }, 322 | { 323 | "channel": 0, 324 | "enable": 0, 325 | "id": 45, 326 | "imgName": "", 327 | "name": "pos46" 328 | }, 329 | { 330 | "channel": 0, 331 | "enable": 0, 332 | "id": 46, 333 | "imgName": "", 334 | "name": "pos47" 335 | }, 336 | { 337 | "channel": 0, 338 | "enable": 0, 339 | "id": 47, 340 | "imgName": "", 341 | "name": "pos48" 342 | }, 343 | { 344 | "channel": 0, 345 | "enable": 0, 346 | "id": 48, 347 | "imgName": "", 348 | "name": "pos49" 349 | }, 350 | { 351 | "channel": 0, 352 | "enable": 0, 353 | "id": 49, 354 | "imgName": "", 355 | "name": "pos50" 356 | }, 357 | { 358 | "channel": 0, 359 | "enable": 0, 360 | "id": 50, 361 | "imgName": "", 362 | "name": "pos51" 363 | }, 364 | { 365 | "channel": 0, 366 | "enable": 0, 367 | "id": 51, 368 | "imgName": "", 369 | "name": "pos52" 370 | }, 371 | { 372 | "channel": 0, 373 | "enable": 0, 374 | "id": 52, 375 | "imgName": "", 376 | "name": "pos53" 377 | }, 378 | { 379 | "channel": 0, 380 | "enable": 0, 381 | "id": 53, 382 | "imgName": "", 383 | "name": "pos54" 384 | }, 385 | { 386 | "channel": 0, 387 | "enable": 0, 388 | "id": 54, 389 | "imgName": "", 390 | "name": "pos55" 391 | }, 392 | { 393 | "channel": 0, 394 | "enable": 0, 395 | "id": 55, 396 | "imgName": "", 397 | "name": "pos56" 398 | }, 399 | { 400 | "channel": 0, 401 | "enable": 0, 402 | "id": 56, 403 | "imgName": "", 404 | "name": "pos57" 405 | }, 406 | { 407 | "channel": 0, 408 | "enable": 0, 409 | "id": 57, 410 | "imgName": "", 411 | "name": "pos58" 412 | }, 413 | { 414 | "channel": 0, 415 | "enable": 0, 416 | "id": 58, 417 | "imgName": "", 418 | "name": "pos59" 419 | }, 420 | { 421 | "channel": 0, 422 | "enable": 0, 423 | "id": 59, 424 | "imgName": "", 425 | "name": "pos60" 426 | }, 427 | { 428 | "channel": 0, 429 | "enable": 0, 430 | "id": 60, 431 | "imgName": "", 432 | "name": "pos61" 433 | }, 434 | { 435 | "channel": 0, 436 | "enable": 0, 437 | "id": 61, 438 | "imgName": "", 439 | "name": "pos62" 440 | }, 441 | { 442 | "channel": 0, 443 | "enable": 0, 444 | "id": 62, 445 | "imgName": "", 446 | "name": "pos63" 447 | }, 448 | { 449 | "channel": 0, 450 | "enable": 0, 451 | "id": 63, 452 | "imgName": "", 453 | "name": "pos64" 454 | } 455 | ] 456 | }, 457 | "range": { 458 | "PtzPreset": { 459 | "channel": 0, 460 | "enable": "boolean", 461 | "id": { 462 | "max": 64, 463 | "min": 1 464 | }, 465 | "imgName": { 466 | "maxLen": 31 467 | }, 468 | "name": { 469 | "maxLen": 31 470 | } 471 | } 472 | }, 473 | "value": { 474 | "PtzPreset": [ 475 | { 476 | "channel": 0, 477 | "enable": 1, 478 | "id": 0, 479 | "imgName": "preset_00", 480 | "name": "0" 481 | }, 482 | { 483 | "channel": 0, 484 | "enable": 1, 485 | "id": 1, 486 | "imgName": "preset_01", 487 | "name": "1" 488 | }, 489 | { 490 | "channel": 0, 491 | "enable": 0, 492 | "id": 2, 493 | "imgName": "", 494 | "name": "pos3" 495 | }, 496 | { 497 | "channel": 0, 498 | "enable": 0, 499 | "id": 3, 500 | "imgName": "", 501 | "name": "pos4" 502 | }, 503 | { 504 | "channel": 0, 505 | "enable": 0, 506 | "id": 4, 507 | "imgName": "", 508 | "name": "pos5" 509 | }, 510 | { 511 | "channel": 0, 512 | "enable": 0, 513 | "id": 5, 514 | "imgName": "", 515 | "name": "pos6" 516 | }, 517 | { 518 | "channel": 0, 519 | "enable": 0, 520 | "id": 6, 521 | "imgName": "", 522 | "name": "pos7" 523 | }, 524 | { 525 | "channel": 0, 526 | "enable": 0, 527 | "id": 7, 528 | "imgName": "", 529 | "name": "pos8" 530 | }, 531 | { 532 | "channel": 0, 533 | "enable": 0, 534 | "id": 8, 535 | "imgName": "", 536 | "name": "pos9" 537 | }, 538 | { 539 | "channel": 0, 540 | "enable": 0, 541 | "id": 9, 542 | "imgName": "", 543 | "name": "pos10" 544 | }, 545 | { 546 | "channel": 0, 547 | "enable": 0, 548 | "id": 10, 549 | "imgName": "", 550 | "name": "pos11" 551 | }, 552 | { 553 | "channel": 0, 554 | "enable": 0, 555 | "id": 11, 556 | "imgName": "", 557 | "name": "pos12" 558 | }, 559 | { 560 | "channel": 0, 561 | "enable": 0, 562 | "id": 12, 563 | "imgName": "", 564 | "name": "pos13" 565 | }, 566 | { 567 | "channel": 0, 568 | "enable": 0, 569 | "id": 13, 570 | "imgName": "", 571 | "name": "pos14" 572 | }, 573 | { 574 | "channel": 0, 575 | "enable": 0, 576 | "id": 14, 577 | "imgName": "", 578 | "name": "pos15" 579 | }, 580 | { 581 | "channel": 0, 582 | "enable": 0, 583 | "id": 15, 584 | "imgName": "", 585 | "name": "pos16" 586 | }, 587 | { 588 | "channel": 0, 589 | "enable": 0, 590 | "id": 16, 591 | "imgName": "", 592 | "name": "pos17" 593 | }, 594 | { 595 | "channel": 0, 596 | "enable": 0, 597 | "id": 17, 598 | "imgName": "", 599 | "name": "pos18" 600 | }, 601 | { 602 | "channel": 0, 603 | "enable": 0, 604 | "id": 18, 605 | "imgName": "", 606 | "name": "pos19" 607 | }, 608 | { 609 | "channel": 0, 610 | "enable": 0, 611 | "id": 19, 612 | "imgName": "", 613 | "name": "pos20" 614 | }, 615 | { 616 | "channel": 0, 617 | "enable": 0, 618 | "id": 20, 619 | "imgName": "", 620 | "name": "pos21" 621 | }, 622 | { 623 | "channel": 0, 624 | "enable": 0, 625 | "id": 21, 626 | "imgName": "", 627 | "name": "pos22" 628 | }, 629 | { 630 | "channel": 0, 631 | "enable": 0, 632 | "id": 22, 633 | "imgName": "", 634 | "name": "pos23" 635 | }, 636 | { 637 | "channel": 0, 638 | "enable": 0, 639 | "id": 23, 640 | "imgName": "", 641 | "name": "pos24" 642 | }, 643 | { 644 | "channel": 0, 645 | "enable": 0, 646 | "id": 24, 647 | "imgName": "", 648 | "name": "pos25" 649 | }, 650 | { 651 | "channel": 0, 652 | "enable": 0, 653 | "id": 25, 654 | "imgName": "", 655 | "name": "pos26" 656 | }, 657 | { 658 | "channel": 0, 659 | "enable": 0, 660 | "id": 26, 661 | "imgName": "", 662 | "name": "pos27" 663 | }, 664 | { 665 | "channel": 0, 666 | "enable": 0, 667 | "id": 27, 668 | "imgName": "", 669 | "name": "pos28" 670 | }, 671 | { 672 | "channel": 0, 673 | "enable": 0, 674 | "id": 28, 675 | "imgName": "", 676 | "name": "pos29" 677 | }, 678 | { 679 | "channel": 0, 680 | "enable": 0, 681 | "id": 29, 682 | "imgName": "", 683 | "name": "pos30" 684 | }, 685 | { 686 | "channel": 0, 687 | "enable": 0, 688 | "id": 30, 689 | "imgName": "", 690 | "name": "pos31" 691 | }, 692 | { 693 | "channel": 0, 694 | "enable": 0, 695 | "id": 31, 696 | "imgName": "", 697 | "name": "pos32" 698 | }, 699 | { 700 | "channel": 0, 701 | "enable": 0, 702 | "id": 32, 703 | "imgName": "", 704 | "name": "pos33" 705 | }, 706 | { 707 | "channel": 0, 708 | "enable": 0, 709 | "id": 33, 710 | "imgName": "", 711 | "name": "pos34" 712 | }, 713 | { 714 | "channel": 0, 715 | "enable": 0, 716 | "id": 34, 717 | "imgName": "", 718 | "name": "pos35" 719 | }, 720 | { 721 | "channel": 0, 722 | "enable": 0, 723 | "id": 35, 724 | "imgName": "", 725 | "name": "pos36" 726 | }, 727 | { 728 | "channel": 0, 729 | "enable": 0, 730 | "id": 36, 731 | "imgName": "", 732 | "name": "pos37" 733 | }, 734 | { 735 | "channel": 0, 736 | "enable": 0, 737 | "id": 37, 738 | "imgName": "", 739 | "name": "pos38" 740 | }, 741 | { 742 | "channel": 0, 743 | "enable": 0, 744 | "id": 38, 745 | "imgName": "", 746 | "name": "pos39" 747 | }, 748 | { 749 | "channel": 0, 750 | "enable": 0, 751 | "id": 39, 752 | "imgName": "", 753 | "name": "pos40" 754 | }, 755 | { 756 | "channel": 0, 757 | "enable": 0, 758 | "id": 40, 759 | "imgName": "", 760 | "name": "pos41" 761 | }, 762 | { 763 | "channel": 0, 764 | "enable": 0, 765 | "id": 41, 766 | "imgName": "", 767 | "name": "pos42" 768 | }, 769 | { 770 | "channel": 0, 771 | "enable": 0, 772 | "id": 42, 773 | "imgName": "", 774 | "name": "pos43" 775 | }, 776 | { 777 | "channel": 0, 778 | "enable": 0, 779 | "id": 43, 780 | "imgName": "", 781 | "name": "pos44" 782 | }, 783 | { 784 | "channel": 0, 785 | "enable": 0, 786 | "id": 44, 787 | "imgName": "", 788 | "name": "pos45" 789 | }, 790 | { 791 | "channel": 0, 792 | "enable": 0, 793 | "id": 45, 794 | "imgName": "", 795 | "name": "pos46" 796 | }, 797 | { 798 | "channel": 0, 799 | "enable": 0, 800 | "id": 46, 801 | "imgName": "", 802 | "name": "pos47" 803 | }, 804 | { 805 | "channel": 0, 806 | "enable": 0, 807 | "id": 47, 808 | "imgName": "", 809 | "name": "pos48" 810 | }, 811 | { 812 | "channel": 0, 813 | "enable": 0, 814 | "id": 48, 815 | "imgName": "", 816 | "name": "pos49" 817 | }, 818 | { 819 | "channel": 0, 820 | "enable": 0, 821 | "id": 49, 822 | "imgName": "", 823 | "name": "pos50" 824 | }, 825 | { 826 | "channel": 0, 827 | "enable": 0, 828 | "id": 50, 829 | "imgName": "", 830 | "name": "pos51" 831 | }, 832 | { 833 | "channel": 0, 834 | "enable": 0, 835 | "id": 51, 836 | "imgName": "", 837 | "name": "pos52" 838 | }, 839 | { 840 | "channel": 0, 841 | "enable": 0, 842 | "id": 52, 843 | "imgName": "", 844 | "name": "pos53" 845 | }, 846 | { 847 | "channel": 0, 848 | "enable": 0, 849 | "id": 53, 850 | "imgName": "", 851 | "name": "pos54" 852 | }, 853 | { 854 | "channel": 0, 855 | "enable": 0, 856 | "id": 54, 857 | "imgName": "", 858 | "name": "pos55" 859 | }, 860 | { 861 | "channel": 0, 862 | "enable": 0, 863 | "id": 55, 864 | "imgName": "", 865 | "name": "pos56" 866 | }, 867 | { 868 | "channel": 0, 869 | "enable": 0, 870 | "id": 56, 871 | "imgName": "", 872 | "name": "pos57" 873 | }, 874 | { 875 | "channel": 0, 876 | "enable": 0, 877 | "id": 57, 878 | "imgName": "", 879 | "name": "pos58" 880 | }, 881 | { 882 | "channel": 0, 883 | "enable": 0, 884 | "id": 58, 885 | "imgName": "", 886 | "name": "pos59" 887 | }, 888 | { 889 | "channel": 0, 890 | "enable": 0, 891 | "id": 59, 892 | "imgName": "", 893 | "name": "pos60" 894 | }, 895 | { 896 | "channel": 0, 897 | "enable": 0, 898 | "id": 60, 899 | "imgName": "", 900 | "name": "pos61" 901 | }, 902 | { 903 | "channel": 0, 904 | "enable": 0, 905 | "id": 61, 906 | "imgName": "", 907 | "name": "pos62" 908 | }, 909 | { 910 | "channel": 0, 911 | "enable": 0, 912 | "id": 62, 913 | "imgName": "", 914 | "name": "pos63" 915 | }, 916 | { 917 | "channel": 0, 918 | "enable": 0, 919 | "id": 63, 920 | "imgName": "", 921 | "name": "pos64" 922 | } 923 | ] 924 | } 925 | } 926 | ] 927 | -------------------------------------------------------------------------------- /examples/response/GetRec.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetRec", 4 | "code": 0, 5 | "initial": { 6 | "Rec": { 7 | "channel": 0, 8 | "overwrite": 1, 9 | "postRec": "15 Seconds", 10 | "preRec": 1, 11 | "schedule": { 12 | "enable": 1, 13 | "table": "111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111" 14 | } 15 | } 16 | }, 17 | "range": { 18 | "Rec": { 19 | "channel": 0, 20 | "overwrite": "boolean", 21 | "postRec": [ 22 | "15 Seconds", 23 | "30 Seconds", 24 | "1 Minute" 25 | ], 26 | "preRec": "boolean", 27 | "schedule": { 28 | "enable": "boolean" 29 | } 30 | } 31 | }, 32 | "value": { 33 | "Rec": { 34 | "channel": 0, 35 | "overwrite": 1, 36 | "postRec": "15 Seconds", 37 | "preRec": 1, 38 | "schedule": { 39 | "enable": 1, 40 | "table": "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" 41 | } 42 | } 43 | } 44 | } 45 | ] 46 | -------------------------------------------------------------------------------- /examples/response/GetUser.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "GetUser", 4 | "code": 0, 5 | "initial": { 6 | "User": { 7 | "level": "guest" 8 | } 9 | }, 10 | "range": { 11 | "User": { 12 | "level": [ 13 | "guest", 14 | "admin" 15 | ], 16 | "password": { 17 | "maxLen": 31, 18 | "minLen": 6 19 | }, 20 | "userName": { 21 | "maxLen": 31, 22 | "minLen": 1 23 | } 24 | } 25 | }, 26 | "value": { 27 | "User": [ 28 | { 29 | "level": "admin", 30 | "userName": "admin" 31 | } 32 | ] 33 | } 34 | } 35 | ] 36 | -------------------------------------------------------------------------------- /examples/response/Login.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "Login", 4 | "code": 0, 5 | "value": { "Token": { "leaseTime": 3600, "name": "xxxxxxxxxxxx" } } 6 | } 7 | ] 8 | -------------------------------------------------------------------------------- /examples/response/Logout.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "Logout", 4 | "code": 0, 5 | "value": { "rspCode": 200 } 6 | } 7 | ] 8 | -------------------------------------------------------------------------------- /examples/response/PtzCheck.json: -------------------------------------------------------------------------------- 1 | [{"cmd": "PtzCheck", "code": 0, "value": {"rspCode": 200}}] -------------------------------------------------------------------------------- /examples/response/PtzCtrl.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd" : "PtzCtrl", 4 | "code" : 0, 5 | "value" : { 6 | "rspCode" : 200 7 | } 8 | } 9 | ] -------------------------------------------------------------------------------- /examples/response/Reboot.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd": "Reboot", 4 | "code": 0, 5 | "value": { 6 | "rspCode": 200 7 | } 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /examples/response/SetAdvImageSettings.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd" : "SetIsp", 4 | "code" : 0, 5 | "value" : { 6 | "rspCode" : 200 7 | } 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /examples/response/SetImageSettings.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd" : "SetImage", 4 | "code" : 0, 5 | "value" : { 6 | "rspCode" : 200 7 | } 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /examples/response/SetPtzPreset.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "cmd" : "SetPtzPreset", 4 | "code" : 0, 5 | "value" : { 6 | "rspCode" : 200 7 | } 8 | } 9 | ] 10 | -------------------------------------------------------------------------------- /examples/stream_gui.py: -------------------------------------------------------------------------------- 1 | import sys 2 | import os 3 | from configparser import RawConfigParser 4 | from PyQt6.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QSlider 5 | from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput 6 | from PyQt6.QtMultimediaWidgets import QVideoWidget 7 | from PyQt6.QtCore import Qt, QUrl, QTimer 8 | from PyQt6.QtGui import QWheelEvent 9 | from reolinkapi import Camera 10 | from threading import Lock 11 | 12 | import urllib3 13 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 14 | 15 | def read_config(props_path: str) -> dict: 16 | config = RawConfigParser() 17 | assert os.path.exists(props_path), f"Path does not exist: {props_path}" 18 | config.read(props_path) 19 | return config 20 | 21 | class ZoomSlider(QSlider): 22 | def __init__(self, *args, **kwargs): 23 | super().__init__(*args, **kwargs) 24 | 25 | def keyPressEvent(self, event): 26 | if event.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down): 27 | event.ignore() 28 | else: 29 | super().keyPressEvent(event) 30 | 31 | class CameraPlayer(QWidget): 32 | def __init__(self, rtsp_url_wide, rtsp_url_telephoto, camera: Camera): 33 | super().__init__() 34 | self.setWindowTitle("Reolink PTZ Streamer") 35 | self.setGeometry(10, 10, 2400, 900) 36 | self.setFocusPolicy(Qt.FocusPolicy.StrongFocus) 37 | 38 | self.camera = camera 39 | self.zoom_timer = QTimer(self) 40 | self.zoom_timer.timeout.connect(self.stop_zoom) 41 | 42 | # Create media players 43 | self.media_player_wide = QMediaPlayer() 44 | self.media_player_telephoto = QMediaPlayer() 45 | 46 | # Create video widgets 47 | self.video_widget_wide = QVideoWidget() 48 | self.video_widget_telephoto = QVideoWidget() 49 | self.media_player_wide.setVideoOutput(self.video_widget_wide) 50 | self.media_player_telephoto.setVideoOutput(self.video_widget_telephoto) 51 | self.video_widget_wide.wheelEvent = self.handle_wheel_event 52 | self.video_widget_telephoto.wheelEvent = self.handle_wheel_event 53 | 54 | # Create layout 55 | layout = QHBoxLayout() 56 | layout.addWidget(self.video_widget_wide, 2) 57 | layout.addWidget(self.video_widget_telephoto, 2) 58 | self.setLayout(layout) 59 | 60 | # Start playing the streams 61 | self.media_player_wide.setSource(QUrl(rtsp_url_wide)) 62 | self.media_player_telephoto.setSource(QUrl(rtsp_url_telephoto)) 63 | self.media_player_wide.play() 64 | self.media_player_telephoto.play() 65 | 66 | 67 | def keyPressEvent(self, event): 68 | if event.isAutoRepeat(): 69 | return 70 | if event.key() == Qt.Key.Key_Escape: 71 | self.close() 72 | elif event.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down): 73 | self.start_move(event.key()) 74 | 75 | def keyReleaseEvent(self, event): 76 | if event.isAutoRepeat(): 77 | return 78 | if event.key() in (Qt.Key.Key_Left, Qt.Key.Key_Right, Qt.Key.Key_Up, Qt.Key.Key_Down): 79 | self.stop_move() 80 | 81 | def start_move(self, key): 82 | direction = { 83 | Qt.Key.Key_Left: "left", 84 | Qt.Key.Key_Right: "right", 85 | Qt.Key.Key_Up: "up", 86 | Qt.Key.Key_Down: "down" 87 | }.get(key) 88 | 89 | if direction: 90 | self.move_camera(direction) 91 | 92 | def stop_move(self): 93 | response = self.camera.stop_ptz() 94 | print("Stop PTZ") 95 | if response[0].get('code') != 0: 96 | self.show_error_message("Failed to stop camera movement", str(response[0])) 97 | 98 | def move_camera(self, direction): 99 | speed = 25 100 | if direction == "left": 101 | response = self.camera.move_left(speed) 102 | elif direction == "right": 103 | response = self.camera.move_right(speed) 104 | elif direction == "up": 105 | response = self.camera.move_up(speed) 106 | elif direction == "down": 107 | response = self.camera.move_down(speed) 108 | else: 109 | print(f"Invalid direction: {direction}") 110 | return 111 | 112 | if response[0].get('code') == 0: 113 | print(f"Moving camera {direction}") 114 | else: 115 | self.show_error_message(f"Failed to move camera {direction}", str(response[0])) 116 | 117 | def handle_wheel_event(self, event: QWheelEvent): 118 | delta = event.angleDelta().y() 119 | if delta > 0: 120 | self.zoom_in() 121 | elif delta < 0: 122 | self.zoom_out() 123 | 124 | def zoom_in(self): 125 | self.start_zoom('in') 126 | 127 | def zoom_out(self): 128 | self.start_zoom('out') 129 | 130 | def start_zoom(self, direction: str): 131 | self.zoom_timer.stop() # Stop any ongoing zoom timer 132 | speed = 60 # You can adjust this value as needed 133 | if direction == 'in': 134 | response = self.camera.start_zooming_in(speed) 135 | else: 136 | response = self.camera.start_zooming_out(speed) 137 | 138 | if response[0].get('code') == 0: 139 | print(f"Zooming {direction}") 140 | self.zoom_timer.start(200) # Stop zooming after 200ms 141 | else: 142 | self.show_error_message(f"Failed to start zooming {direction}", str(response[0])) 143 | 144 | def stop_zoom(self): 145 | response = self.camera.stop_zooming() 146 | if response[0].get('code') != 0: 147 | self.show_error_message("Failed to stop zooming", str(response[0])) 148 | 149 | def show_error_message(self, title, message): 150 | print(f"Error: {title} {message}") 151 | 152 | def handle_error(self, error): 153 | print(f"Media player error: {error}") 154 | 155 | 156 | if __name__ == '__main__': 157 | # Read in your ip, username, & password from the configuration file 158 | config = read_config('camera.cfg') 159 | ip = config.get('camera', 'ip') 160 | un = config.get('camera', 'username') 161 | pw = config.get('camera', 'password') 162 | 163 | # Connect to camera 164 | cam = Camera(ip, un, pw, https=True) 165 | 166 | rtsp_url_wide = f"rtsp://{un}:{pw}@{ip}/Preview_01_sub" 167 | rtsp_url_telephoto = f"rtsp://{un}:{pw}@{ip}/Preview_02_sub" 168 | 169 | # Connect to camera 170 | cam = Camera(ip, un, pw, https=True) 171 | 172 | app = QApplication(sys.argv) 173 | player = CameraPlayer(rtsp_url_wide, rtsp_url_telephoto, cam) 174 | player.show() 175 | sys.exit(app.exec()) 176 | -------------------------------------------------------------------------------- /examples/streaming_video.py: -------------------------------------------------------------------------------- 1 | import cv2 2 | from reolinkapi import Camera 3 | 4 | 5 | def non_blocking(): 6 | print("calling non-blocking") 7 | 8 | def inner_callback(img): 9 | cv2.imshow("name", maintain_aspect_ratio_resize(img, width=600)) 10 | print("got the image non-blocking") 11 | key = cv2.waitKey(1) 12 | if key == ord('q'): 13 | cv2.destroyAllWindows() 14 | exit(1) 15 | 16 | c = Camera("192.168.1.112", "admin", "jUa2kUzi") 17 | # t in this case is a thread 18 | t = c.open_video_stream(callback=inner_callback) 19 | 20 | print(t.is_alive()) 21 | while True: 22 | if not t.is_alive(): 23 | print("continuing") 24 | break 25 | # stop the stream 26 | # client.stop_stream() 27 | 28 | 29 | def blocking(): 30 | c = Camera("192.168.1.112", "admin", "jUa2kUzi") 31 | # stream in this case is a generator returning an image (in mat format) 32 | stream = c.open_video_stream() 33 | 34 | # using next() 35 | # while True: 36 | # img = next(stream) 37 | # cv2.imshow("name", maintain_aspect_ratio_resize(img, width=600)) 38 | # print("got the image blocking") 39 | # key = cv2.waitKey(1) 40 | # if key == ord('q'): 41 | # cv2.destroyAllWindows() 42 | # exit(1) 43 | 44 | # or using a for loop 45 | for img in stream: 46 | cv2.imshow("name", maintain_aspect_ratio_resize(img, width=600)) 47 | print("got the image blocking") 48 | key = cv2.waitKey(1) 49 | if key == ord('q'): 50 | cv2.destroyAllWindows() 51 | exit(1) 52 | 53 | 54 | # Resizes a image and maintains aspect ratio 55 | def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA): 56 | # Grab the image size and initialize dimensions 57 | dim = None 58 | (h, w) = image.shape[:2] 59 | 60 | # Return original image if no need to resize 61 | if width is None and height is None: 62 | return image 63 | 64 | # We are resizing height if width is none 65 | if width is None: 66 | # Calculate the ratio of the height and construct the dimensions 67 | r = height / float(h) 68 | dim = (int(w * r), height) 69 | # We are resizing width if height is none 70 | else: 71 | # Calculate the ratio of the 0idth and construct the dimensions 72 | r = width / float(w) 73 | dim = (width, int(h * r)) 74 | 75 | # Return the resized image 76 | return cv2.resize(image, dim, interpolation=inter) 77 | 78 | 79 | # Call the methods. Either Blocking (using generator) or Non-Blocking using threads 80 | # non_blocking() 81 | blocking() 82 | -------------------------------------------------------------------------------- /examples/video_review_gui.py: -------------------------------------------------------------------------------- 1 | # Video review GUI 2 | # https://github.com/sven337/ReolinkLinux/wiki#reolink-video-review-gui 3 | 4 | import os 5 | import signal 6 | import sys 7 | import re 8 | import datetime 9 | import subprocess 10 | import argparse 11 | from configparser import RawConfigParser 12 | from datetime import datetime as dt, timedelta 13 | from reolinkapi import Camera 14 | from PyQt6.QtWidgets import QApplication, QVBoxLayout, QHBoxLayout, QWidget, QTableWidget, QTableWidgetItem, QPushButton, QLabel, QFileDialog, QHeaderView, QStyle, QSlider, QStyleOptionSlider, QSplitter, QTreeWidget, QTreeWidgetItem, QTreeWidgetItemIterator 15 | from PyQt6.QtMultimedia import QMediaPlayer, QAudioOutput 16 | from PyQt6.QtMultimediaWidgets import QVideoWidget 17 | from PyQt6.QtCore import Qt, QUrl, QTimer, QThread, pyqtSignal, QMutex, QWaitCondition 18 | from PyQt6.QtGui import QColor, QBrush, QFont, QIcon 19 | from collections import deque 20 | 21 | import urllib3 22 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 23 | 24 | def path_name_from_camera_path(fname): 25 | # Mp4Record/2024-08-12/RecM13_DST20240812_214255_214348_1F1E828_4DDA4D.mp4 26 | return fname.replace('/', '_') 27 | 28 | # Function to decode hex values into individual flags 29 | def decode_hex_to_flags(hex_value): 30 | flags_mapping = { 31 | 'resolution_index': (21, 7), 32 | 'tv_system': (20, 1), 33 | 'framerate': (13, 7), 34 | 'audio_index': (11, 2), 35 | 'ai_pd': (10, 1), # person 36 | 'ai_fd': (9, 1), # face 37 | 'ai_vd': (8, 1), # vehicle 38 | 'ai_ad': (7, 1), # animal 39 | 'encoder_type_index': (5, 2), 40 | 'is_schedule_record': (4, 1), #scheduled 41 | 'is_motion_record': (3, 1), # motion detected 42 | 'is_rf_record': (2, 1), 43 | 'is_doorbell_press_record': (1, 1), 44 | 'ai_other': (0, 1) 45 | } 46 | hex_value = int(hex_value, 16) # Convert hex string to integer 47 | flag_values = {} 48 | for flag, (bit_position, bit_size) in flags_mapping.items(): 49 | mask = ((1 << bit_size) - 1) << bit_position 50 | flag_values[flag] = (hex_value & mask) >> bit_position 51 | return flag_values 52 | 53 | def parse_filename(file_name): 54 | # Mp4Record_2024-08-12_RecM13_DST20240812_214255_214348_1F1E828_4DDA4D.mp4 55 | # Mp4Record_2024-09-13-RecS09_DST20240907_084519_084612_0_55289080000000_307BC0.mp4 56 | # https://github.com/sven337/ReolinkLinux/wiki/Figuring-out-the-file-names#file-name-structure 57 | pattern = r'.*?Mp4Record_(\d{4}-\d{2}-\d{2})_Rec[MS](\d)(\d)_(DST)?(\d{8})_(\d{6})_(\d{6})' 58 | v3_suffix = r'.*_(\w{4,8})_(\w{4,8})\.mp4' 59 | v9_suffix = r'.*_(\d)_(\w{7})(\w{7})_(\w{1,8})\.mp4' 60 | match = re.match(pattern, file_name) 61 | 62 | out = {} 63 | version = 0 64 | 65 | if match: 66 | date = match.group(1) # YYYY-MM-DD 67 | channel = int(match.group(2)) 68 | version = int(match.group(3)) # version 69 | start_date = match.group(5) # YYYYMMDD 70 | start_time = match.group(6) # HHMMSS 71 | end_time = match.group(7) # HHMMSS 72 | 73 | # Combine date and start time into a datetime object 74 | start_datetime = datetime.datetime.strptime(f"{start_date} {start_time}", "%Y%m%d %H%M%S") 75 | 76 | out = {'start_datetime': start_datetime, 'channel': channel, 'end_time': end_time } 77 | else: 78 | print("parse error") 79 | return None 80 | 81 | if version == 9: 82 | match = re.match(v9_suffix, file_name) 83 | if not match: 84 | print(f"v9 parse error for {file_name}") 85 | return None 86 | 87 | animal_type = match.group(1) 88 | flags_hex1 = match.group(2) 89 | flags_hex2 = match.group(3) 90 | file_size = int(match.group(4), 16) 91 | 92 | triggers = decode_hex_to_flags(flags_hex1) 93 | 94 | out.update({'animal_type' : animal_type, 'file_size' : file_size, 'triggers' : triggers }) 95 | 96 | elif version == 2 or version == 3: 97 | match = re.match(v3_suffix, file_name) 98 | if not match: 99 | print(f"v3 parse error for {file_name}") 100 | return None 101 | 102 | flags_hex = match.group(1) 103 | file_size = int(match.group(2), 16) 104 | 105 | triggers = decode_hex_to_flags(flags_hex) 106 | 107 | out.update({'file_size' : file_size, 'triggers' : triggers }) 108 | 109 | return out 110 | 111 | class ClickableSlider(QSlider): 112 | def mousePressEvent(self, event): 113 | if event.button() == Qt.MouseButton.LeftButton: 114 | val = self.pixelPosToRangeValue(event.pos()) 115 | self.setValue(val) 116 | super().mousePressEvent(event) 117 | 118 | def pixelPosToRangeValue(self, pos): 119 | opt = QStyleOptionSlider() 120 | self.initStyleOption(opt) 121 | gr = self.style().subControlRect(QStyle.ComplexControl.CC_Slider, opt, QStyle.SubControl.SC_SliderGroove, self) 122 | sr = self.style().subControlRect(QStyle.ComplexControl.CC_Slider, opt, QStyle.SubControl.SC_SliderHandle, self) 123 | 124 | if self.orientation() == Qt.Orientation.Horizontal: 125 | sliderLength = sr.width() 126 | sliderMin = gr.x() 127 | sliderMax = gr.right() - sliderLength + 1 128 | pos = pos.x() 129 | else: 130 | sliderLength = sr.height() 131 | sliderMin = gr.y() 132 | sliderMax = gr.bottom() - sliderLength + 1 133 | pos = pos.y() 134 | 135 | return QStyle.sliderValueFromPosition(self.minimum(), self.maximum(), pos - sliderMin, sliderMax - sliderMin, opt.upsideDown) 136 | 137 | class DownloadThread(QThread): 138 | download_complete = pyqtSignal(str, bool) 139 | download_start = pyqtSignal(str) 140 | 141 | def __init__(self, download_queue, cam): 142 | super().__init__() 143 | self.download_queue = download_queue 144 | self.cam = cam 145 | self.mutex = QMutex() 146 | self.wait_condition = QWaitCondition() 147 | self.is_running = True 148 | 149 | def run(self): 150 | while self.is_running: 151 | self.mutex.lock() 152 | if len(self.download_queue) == 0: 153 | self.wait_condition.wait(self.mutex) 154 | self.mutex.unlock() 155 | 156 | if not self.is_running: 157 | break 158 | 159 | try: 160 | fname, output_path = self.download_queue.popleft() 161 | output_path = os.path.join(video_storage_dir, output_path) 162 | print(f"Downloading: {fname}") 163 | self.download_start.emit(output_path) 164 | resp = self.cam.get_file(fname, output_path=output_path) 165 | if resp: 166 | print(f"Download complete: {output_path}") 167 | self.download_complete.emit(output_path, True) 168 | else: 169 | print(f"Download failed: {fname}") 170 | self.download_complete.emit(output_path, False) 171 | except IndexError: 172 | pass 173 | 174 | def stop(self): 175 | self.mutex.lock() 176 | self.is_running = False 177 | self.mutex.unlock() 178 | self.wait_condition.wakeAll() 179 | 180 | def add_to_queue(self, fname, output_path, left=False): 181 | self.mutex.lock() 182 | if left: 183 | self.download_queue.appendleft((fname, output_path)) 184 | else: 185 | self.download_queue.append((fname, output_path)) 186 | self.wait_condition.wakeOne() 187 | self.mutex.unlock() 188 | 189 | 190 | class VideoPlayer(QWidget): 191 | file_exists_signal = pyqtSignal(str, bool) 192 | 193 | def __init__(self, video_files): 194 | super().__init__() 195 | self.setWindowTitle("Reolink Video Review GUI") 196 | self.cam = cam 197 | self.download_queue = deque() 198 | self.download_thread = DownloadThread(self.download_queue, self.cam) 199 | self.download_thread.download_start.connect(self.on_download_start) 200 | self.download_thread.download_complete.connect(self.on_download_complete) 201 | self.download_thread.start() 202 | 203 | # Create media player 204 | self.media_player = QMediaPlayer() 205 | self.media_player.errorOccurred.connect(self.handle_media_player_error) 206 | 207 | # Create video widget 208 | self.video_widget = QVideoWidget() 209 | self.media_player.setVideoOutput(self.video_widget) 210 | self.media_player.setPlaybackRate(1.5) 211 | 212 | # Create table widget to display video files 213 | self.video_tree = QTreeWidget() 214 | self.video_tree.setColumnCount(10) 215 | self.video_tree.setHeaderLabels(["Status", "Video Path", "Start Datetime", "End Time", "Channel", "Person", "Vehicle", "Pet", "Motion", "Timer"]) 216 | self.video_tree.setSortingEnabled(True) 217 | self.video_tree.itemClicked.connect(self.play_video) 218 | 219 | # Set smaller default column widths 220 | self.video_tree.setColumnWidth(0, 35) # Status 221 | self.video_tree.setColumnWidth(1, 120) # Video Path 222 | self.video_tree.setColumnWidth(2, 130) # Start Datetime 223 | self.video_tree.setColumnWidth(3, 70) # End Time 224 | self.video_tree.setColumnWidth(4, 35) # Channel 225 | self.video_tree.setColumnWidth(5, 35) # Person 226 | self.video_tree.setColumnWidth(6, 35) # Vehicle 227 | self.video_tree.setColumnWidth(7, 35) # Pet 228 | self.video_tree.setColumnWidth(8, 35) # Motion 229 | self.video_tree.setColumnWidth(9, 30) # Timer 230 | 231 | self.video_tree.setIndentation(10) 232 | 233 | QIcon.setThemeName("Adwaita") 234 | 235 | # Create open button to select video files 236 | self.open_button = QPushButton("Open Videos") 237 | self.open_button.clicked.connect(self.open_videos) 238 | 239 | self.play_button = QPushButton() 240 | self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay)) 241 | self.play_button.clicked.connect(self.play_pause) 242 | 243 | self.mpv_button = QPushButton("MPV") 244 | self.mpv_button.clicked.connect(self.open_in_mpv) 245 | 246 | self.get_highres_button = QPushButton("GetHighRes") 247 | self.get_highres_button.clicked.connect(self.get_highres_stream_for_file) 248 | self.get_highres_button.setEnabled(False) # Disable by default 249 | 250 | # Create seek slider 251 | self.seek_slider = ClickableSlider(Qt.Orientation.Horizontal) 252 | self.seek_slider.setRange(0, 0) 253 | self.seek_slider.sliderPressed.connect(self.seek_slider_pressed) 254 | self.seek_slider.sliderReleased.connect(self.seek_slider_released) 255 | self.seek_slider.sliderMoved.connect(self.seek_slider_moved) 256 | self.media_player.positionChanged.connect(self.update_position) 257 | self.media_player.durationChanged.connect(self.update_duration) 258 | 259 | # Create playback speed slider 260 | self.speed_slider = QSlider(Qt.Orientation.Horizontal) 261 | self.speed_slider.setRange(50, 300) 262 | self.speed_slider.setValue(200) 263 | self.speed_slider.valueChanged.connect(self.set_speed) 264 | speed_label = QLabel("Speed: 2.0x") 265 | self.speed_slider.valueChanged.connect(lambda v: speed_label.setText(f"Speed: {v/100:.1f}x")) 266 | 267 | main_layout = QHBoxLayout() 268 | # Create a splitter 269 | splitter = QSplitter(Qt.Orientation.Horizontal) 270 | 271 | # Left side (table and open button) 272 | left_widget = QWidget() 273 | left_layout = QVBoxLayout(left_widget) 274 | left_layout.addWidget(self.video_tree) 275 | left_layout.addWidget(self.open_button) 276 | splitter.addWidget(left_widget) 277 | 278 | # Right side (video player and controls) 279 | right_widget = QWidget() 280 | right_layout = QVBoxLayout(right_widget) 281 | right_layout.addWidget(self.video_widget, 1) 282 | 283 | controls_widget = QWidget() 284 | controls_layout = QVBoxLayout(controls_widget) 285 | 286 | control_layout = QHBoxLayout() 287 | control_layout.addWidget(self.play_button) 288 | control_layout.addWidget(self.seek_slider) 289 | control_layout.addWidget(self.mpv_button) 290 | control_layout.addWidget(self.get_highres_button) 291 | controls_layout.addLayout(control_layout) 292 | 293 | speed_layout = QHBoxLayout() 294 | speed_layout.addWidget(QLabel("Speed:")) 295 | speed_layout.addWidget(self.speed_slider) 296 | speed_layout.addWidget(speed_label) 297 | controls_layout.addLayout(speed_layout) 298 | right_layout.addWidget(controls_widget) 299 | splitter.addWidget(right_widget) 300 | 301 | # Set initial sizes 302 | splitter.setSizes([300, 700]) 303 | 304 | main_layout.addWidget(splitter) 305 | self.setLayout(main_layout) 306 | self.file_exists_signal.connect(self.on_download_complete) 307 | 308 | self.add_initial_videos(video_files) 309 | 310 | def add_initial_videos(self, video_files): 311 | for video_path in video_files: 312 | self.add_video(video_path) 313 | self.video_tree.sortItems(2, Qt.SortOrder.DescendingOrder) 314 | # self.video_tree.expandAll() 315 | 316 | def open_videos(self): 317 | file_dialog = QFileDialog(self) 318 | file_dialog.setNameFilters(["Videos (*.mp4 *.avi *.mov)"]) 319 | file_dialog.setFileMode(QFileDialog.FileMode.ExistingFiles) 320 | if file_dialog.exec(): 321 | self.video_tree.setSortingEnabled(False) 322 | for file in file_dialog.selectedFiles(): 323 | self.add_video(os.path.basename(file)) 324 | self.video_tree.setSortingEnabled(True) 325 | self.video_tree.sortItems(2, Qt.SortOrder.DescendingOrder) 326 | # self.video_tree.expandAll() 327 | 328 | def add_video(self, video_path): 329 | # We are passed the camera file name, e.g. Mp4Record/2024-08-12/RecM13_DST20240812_214255_214348_1F1E828_4DDA4D.mp4 330 | file_path = path_name_from_camera_path(video_path) 331 | base_file_name = file_path 332 | parsed_data = parse_filename(file_path) 333 | if not parsed_data: 334 | print(f"Could not parse file {video_path}") 335 | return 336 | 337 | start_datetime = parsed_data['start_datetime'] 338 | channel = parsed_data['channel'] 339 | 340 | end_time = datetime.datetime.strptime(parsed_data['end_time'], "%H%M%S") 341 | end_time_str = end_time.strftime("%H:%M:%S") 342 | 343 | video_item = QTreeWidgetItem() 344 | video_item.setText(0, "") # Status 345 | video_item.setTextAlignment(0, Qt.AlignmentFlag.AlignCenter) 346 | video_item.setText(1, base_file_name) 347 | video_item.setText(2, start_datetime.strftime("%Y-%m-%d %H:%M:%S")) 348 | video_item.setData(2, Qt.ItemDataRole.UserRole, parsed_data['start_datetime']) 349 | video_item.setText(3, end_time_str) 350 | video_item.setText(4, str(channel)) 351 | video_item.setText(5, "✓" if parsed_data['triggers']['ai_pd'] else "") 352 | video_item.setText(6, "✓" if parsed_data['triggers']['ai_vd'] else "") 353 | video_item.setText(7, "✓" if parsed_data['triggers']['ai_ad'] else "") 354 | video_item.setText(8, "✓" if parsed_data['triggers']['is_motion_record'] else "") 355 | video_item.setText(9, "✓" if parsed_data['triggers']['is_schedule_record'] else "") 356 | 357 | if parsed_data['triggers']['ai_other']: 358 | print(f"File {file_path} has ai_other flag!") 359 | 360 | video_item.setToolTip(1, base_file_name) 361 | # Set the style for queued status 362 | grey_color = QColor(200, 200, 200) # Light grey 363 | video_item.setForeground(1, QBrush(grey_color)) 364 | font = QFont() 365 | font.setItalic(True) 366 | video_item.setFont(1, font) 367 | 368 | # Make the fields non-editable 369 | iterator = QTreeWidgetItemIterator(self.video_tree) 370 | while iterator.value(): 371 | item = iterator.value() 372 | item.setFlags(item.flags() & ~Qt.ItemFlag.ItemIsEditable) 373 | iterator += 1 374 | 375 | # Find a potentially pre-existing channel0 item for this datetime, if so, add as a child 376 | # This lets channel1 appear as a child, but also main & sub videos appear in the same group 377 | channel_0_item = self.find_channel_0_item(start_datetime) 378 | 379 | if channel_0_item: 380 | # Check if the current item is a main stream and the existing channel_0_item is a sub stream 381 | if "RecM" in base_file_name and "RecS" in channel_0_item.text(1): 382 | # Make the current main stream item the new parent 383 | new_parent = video_item 384 | # Move all children of the sub stream item to the new main stream item 385 | while channel_0_item.childCount() > 0: 386 | child = channel_0_item.takeChild(0) 387 | new_parent.addChild(child) 388 | # Remove the old sub stream item 389 | parent = channel_0_item.parent() 390 | if parent: 391 | parent.removeChild(channel_0_item) 392 | else: 393 | index = self.video_tree.indexOfTopLevelItem(channel_0_item) 394 | self.video_tree.takeTopLevelItem(index) 395 | # Add the new main stream item as a top-level item 396 | self.video_tree.addTopLevelItem(new_parent) 397 | else: 398 | # If it's not a main stream replacing a sub stream, add as a child as before 399 | channel_0_item.addChild(video_item) 400 | else: 401 | self.video_tree.addTopLevelItem(video_item) 402 | 403 | output_path = os.path.join(video_storage_dir, base_file_name) 404 | expected_size = parsed_data['file_size'] 405 | 406 | need_download = True 407 | if os.path.isfile(output_path): 408 | actual_size = os.path.getsize(output_path) 409 | if actual_size == expected_size: 410 | need_download = False 411 | self.file_exists_signal.emit(output_path, True) 412 | else: 413 | print(f"File size mismatch for {output_path}. Expected: {expected_size}, Actual: {actual_size}. Downloading again") 414 | 415 | if need_download: 416 | video_item.setIcon(1, self.style().standardIcon(QStyle.StandardPixmap.SP_CommandLink)) 417 | self.download_thread.add_to_queue(video_path, base_file_name) 418 | 419 | def find_channel_0_item(self, datetime_obj): 420 | # Truncate seconds to nearest 10 421 | truncated_seconds = datetime_obj.second - (datetime_obj.second % 10) 422 | truncated_datetime = datetime_obj.replace(second=truncated_seconds) 423 | 424 | for i in range(self.video_tree.topLevelItemCount()): 425 | item = self.video_tree.topLevelItem(i) 426 | item_datetime = item.data(2, Qt.ItemDataRole.UserRole) 427 | item_truncated = item_datetime.replace(second=item_datetime.second - (item_datetime.second % 10)) 428 | if item_truncated == truncated_datetime: 429 | return item 430 | return None 431 | 432 | def find_item_by_path(self, path): 433 | iterator = QTreeWidgetItemIterator(self.video_tree) 434 | while iterator.value(): 435 | item = iterator.value() 436 | text = item.text(1) 437 | if text == path: 438 | return item 439 | iterator += 1 440 | print(f"Could not find item by path {path}") 441 | return None 442 | 443 | def on_download_complete(self, video_path, success): 444 | item = self.find_item_by_path(os.path.basename(video_path)) 445 | if not item: 446 | print(f"on_download_complete {video_path} did not find item?!") 447 | return 448 | item.setForeground(1, QBrush(QColor(0, 0, 0))) # Black color for normal text 449 | font = item.font(1) 450 | font.setItalic(False) 451 | font.setBold(False) 452 | item.setFont(1, font) 453 | if success: 454 | if "RecS" in item.text(1): 455 | # One day (hopefully) offer the option to download the 456 | # high-res version This is not trivial because we have to 457 | # re-do a camera search for the relevant time period and 458 | # match based on start and end dates (+/- one second in my 459 | # experience) 460 | # For now simply display that this is low-res. 461 | item.setText(0, "sub") 462 | item.setIcon(1, QIcon()) 463 | else: 464 | item.setIcon(1, self.style().standardIcon(QStyle.StandardPixmap.SP_MessageBoxCritical)) 465 | 466 | 467 | def on_download_start(self, video_path): 468 | item = self.find_item_by_path(os.path.basename(video_path)) 469 | if item: 470 | grey_color = QColor(200, 200, 200) # Light grey 471 | item.setForeground(1, QBrush(grey_color)) 472 | font = item.font(1) 473 | font.setBold(True) 474 | item.setFont(1, font) 475 | item.setIcon(1, QIcon.fromTheme("emblem-synchronizing")) 476 | else: 477 | print(f"Cannot find item for {video_path}") 478 | 479 | def play_video(self, file_name_item, column): 480 | video_path = os.path.join(video_storage_dir, file_name_item.text(1)) 481 | 482 | if file_name_item.font(1).italic() or file_name_item.foreground(1).color().lightness() >= 200: 483 | print(f"Video {video_path} is not yet downloaded. Moving it to top of queue. Please wait for download.") 484 | # Find the item in the download_queue that matches the base file name 485 | found_item = None 486 | for item in list(self.download_queue): 487 | if item[1] == file_name_item.text(1): 488 | found_item = item 489 | break 490 | 491 | if found_item: 492 | # Remove the item from its current position in the queue 493 | self.download_queue.remove(found_item) 494 | # Add the item to the end of the queue 495 | self.download_thread.add_to_queue(*found_item, left=True) 496 | return 497 | 498 | # Enable/disable GetHighRes button based on whether it's a sub stream 499 | self.get_highres_button.setEnabled("RecS" in file_name_item.text(1)) 500 | 501 | print(f"Playing video: {video_path}") 502 | url = QUrl.fromLocalFile(video_path) 503 | self.media_player.setSource(url) 504 | self.video_widget.show() 505 | def start_playback(): 506 | # Seek to 5 seconds (pre-record) 507 | self.media_player.setPosition(5000) 508 | self.media_player.play() 509 | self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause)) 510 | print(f"Media player state: {self.media_player.playbackState()}") 511 | 512 | # Timer needed to be able to play at seek offset in the video, otherwise setPosition seems ignored 513 | QTimer.singleShot(20, start_playback) 514 | 515 | def get_highres_stream_for_file(self): 516 | current_item = self.video_tree.currentItem() 517 | if not current_item or "RecS" not in current_item.text(1): 518 | return 519 | 520 | parsed_data = parse_filename(current_item.text(1)) 521 | if not parsed_data: 522 | print(f"Could not parse file {current_item.text(1)}") 523 | return 524 | 525 | start_time = parsed_data['start_datetime'] - timedelta(seconds=1) 526 | end_time = datetime.datetime.strptime(f"{parsed_data['start_datetime'].strftime('%Y%m%d')} {parsed_data['end_time']}", "%Y%m%d %H%M%S") + timedelta(seconds=1) 527 | 528 | main_files = self.cam.get_motion_files(start=start_time, end=end_time, streamtype='main', channel=parsed_data['channel']) 529 | 530 | if main_files: 531 | for main_file in main_files: 532 | self.add_video(main_file['filename']) 533 | self.video_tree.sortItems(2, Qt.SortOrder.DescendingOrder) 534 | else: 535 | print(f"No main stream file found for {current_item.text(1)}") 536 | 537 | def play_pause(self): 538 | if self.media_player.playbackState() == QMediaPlayer.PlaybackState.PlayingState: 539 | self.media_player.pause() 540 | self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay)) 541 | else: 542 | self.media_player.play() 543 | self.play_button.setIcon(self.style().standardIcon(QStyle.StandardPixmap.SP_MediaPause)) 544 | 545 | def handle_media_player_error(self, error): 546 | print(f"Media player error: {error}") 547 | 548 | def seek_slider_pressed(self): 549 | self.media_player.setPosition(self.seek_slider.value()) 550 | self.media_player.play() 551 | 552 | def seek_slider_released(self): 553 | self.media_player.setPosition(self.seek_slider.value()) 554 | self.media_player.play() 555 | 556 | def seek_slider_moved(self, position): 557 | # Update video frame while dragging 558 | self.media_player.setPosition(position) 559 | 560 | def update_position(self, position): 561 | self.seek_slider.setValue(position) 562 | 563 | def update_duration(self, duration): 564 | self.seek_slider.setRange(0, duration) 565 | 566 | def set_speed(self, speed): 567 | self.media_player.setPlaybackRate(speed / 100) 568 | 569 | def open_in_mpv(self): 570 | current_video = self.media_player.source().toString() 571 | if current_video: 572 | # Remove the 'file://' prefix if present 573 | video_path = current_video.replace('file://', '') 574 | try: 575 | subprocess.Popen(['mpv', video_path]) 576 | except FileNotFoundError: 577 | print("Error: MPV player not found. Make sure it's installed and in your system PATH.") 578 | else: 579 | print("No video is currently selected.") 580 | 581 | def closeEvent(self, event): 582 | self.download_thread.stop() 583 | self.download_thread.wait(1000) 584 | self.download_thread.terminate() 585 | self.cam.logout() 586 | super().closeEvent(event) 587 | 588 | def read_config(props_path: str) -> dict: 589 | """Reads in a properties file into variables. 590 | 591 | NB! this config file is kept out of commits with .gitignore. The structure of this file is such: 592 | # secrets.cfg 593 | [camera] 594 | ip={ip_address} 595 | username={username} 596 | password={password} 597 | """ 598 | config = RawConfigParser() 599 | assert os.path.exists(props_path), f"Path does not exist: {props_path}" 600 | config.read(props_path) 601 | return config 602 | 603 | 604 | def signal_handler(sig, frame): 605 | print("Exiting the application...") 606 | sys.exit(0) 607 | cam.logout() 608 | QApplication.quit() 609 | 610 | 611 | 612 | if __name__ == '__main__': 613 | signal.signal(signal.SIGINT, signal_handler) 614 | 615 | parser = argparse.ArgumentParser(description="Reolink Video Review GUI") 616 | parser.add_argument('--main', action='store_true', help="Search for main channel instead of sub channel") 617 | parser.add_argument('files', nargs='*', help="Optional video file names to process") 618 | args = parser.parse_args() 619 | 620 | config = read_config('camera.cfg') 621 | 622 | ip = config.get('camera', 'ip') 623 | un = config.get('camera', 'username') 624 | pw = config.get('camera', 'password') 625 | video_storage_dir = config.get('camera', 'video_storage_dir') 626 | 627 | # Connect to camera 628 | cam = Camera(ip, un, pw, https=True) 629 | 630 | start = dt.combine(dt.now(), dt.min.time()) 631 | end = dt.now() 632 | 633 | streamtype = 'sub' if not args.main else 'main' 634 | processed_motions = cam.get_motion_files(start=start, end=end, streamtype=streamtype, channel=0) 635 | processed_motions += cam.get_motion_files(start=start, end=end, streamtype=streamtype, channel=1) 636 | 637 | start = dt.now() - timedelta(days=1) 638 | end = dt.combine(start, dt.max.time()) 639 | processed_motions += cam.get_motion_files(start=start, end=end, streamtype=streamtype, channel=0) 640 | processed_motions += cam.get_motion_files(start=start, end=end, streamtype=streamtype, channel=1) 641 | 642 | 643 | if len(processed_motions) == 0: 644 | print("Camera did not return any video?!") 645 | 646 | video_files = [] 647 | for i, motion in enumerate(processed_motions): 648 | fname = motion['filename'] 649 | print("Processing %s" % (fname)) 650 | video_files.append(fname) 651 | 652 | video_files.extend([os.path.basename(file) for file in args.files]) 653 | app = QApplication(sys.argv) 654 | player = VideoPlayer(video_files) 655 | player.resize(2400, 1000) 656 | player.show() 657 | sys.exit(app.exec()) 658 | -------------------------------------------------------------------------------- /make-and-publish-package.sh: -------------------------------------------------------------------------------- 1 | rm -rf dist 2 | python setup.py sdist bdist_wheel 3 | twine upload dist/* -------------------------------------------------------------------------------- /reolinkapi/__init__.py: -------------------------------------------------------------------------------- 1 | from reolinkapi.handlers.api_handler import APIHandler 2 | from .camera import Camera 3 | 4 | __version__ = "0.4.1" 5 | -------------------------------------------------------------------------------- /reolinkapi/camera.py: -------------------------------------------------------------------------------- 1 | from reolinkapi.handlers.api_handler import APIHandler 2 | 3 | 4 | class Camera(APIHandler): 5 | 6 | def __init__(self, ip: str, 7 | username: str = "admin", 8 | password: str = "", 9 | https: bool = False, 10 | defer_login: bool = False, 11 | profile: str = "main", 12 | **kwargs): 13 | """ 14 | Initialise the Camera object by passing the ip address. 15 | The default details {"username":"admin", "password":""} will be used if nothing passed 16 | For deferring the login to the camera, just pass defer_login = True. 17 | For connecting to the camera behind a proxy pass a proxy argument: proxy={"http": "socks5://127.0.0.1:8000"} 18 | :param ip: 19 | :param username: 20 | :param password: 21 | :param https: connect to the camera over https 22 | :param defer_login: defer the login process 23 | :param proxy: Add a proxy dict for requests to consume. 24 | eg: {"http":"socks5://[username]:[password]@[host]:[port], "https": ...} 25 | More information on proxies in requests: https://stackoverflow.com/a/15661226/9313679 26 | """ 27 | if profile not in ["main", "sub"]: 28 | raise Exception("Profile argument must be either \"main\" or \"sub\"") 29 | 30 | # For when you need to connect to a camera behind a proxy, pass 31 | # a proxy argument: proxy={"http": "socks5://127.0.0.1:8000"} 32 | APIHandler.__init__(self, ip, username, password, https=https, **kwargs) 33 | 34 | # Normal call without proxy: 35 | # APIHandler.__init__(self, ip, username, password) 36 | 37 | self.ip = ip 38 | self.username = username 39 | self.password = password 40 | self.profile = profile 41 | 42 | if not defer_login: 43 | super().login() 44 | -------------------------------------------------------------------------------- /reolinkapi/handlers/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReolinkCameraAPI/reolinkapipy/e0fee8d9d31428791ff447a59f6fdf9d1e7d0682/reolinkapi/handlers/__init__.py -------------------------------------------------------------------------------- /reolinkapi/handlers/api_handler.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from typing import Dict, List, Optional, Union 3 | from reolinkapi.mixins.alarm import AlarmAPIMixin 4 | from reolinkapi.mixins.device import DeviceAPIMixin 5 | from reolinkapi.mixins.display import DisplayAPIMixin 6 | from reolinkapi.mixins.download import DownloadAPIMixin 7 | from reolinkapi.mixins.image import ImageAPIMixin 8 | from reolinkapi.mixins.motion import MotionAPIMixin 9 | from reolinkapi.mixins.network import NetworkAPIMixin 10 | from reolinkapi.mixins.ptz import PtzAPIMixin 11 | from reolinkapi.mixins.record import RecordAPIMixin 12 | from reolinkapi.handlers.rest_handler import Request 13 | from reolinkapi.mixins.stream import StreamAPIMixin 14 | from reolinkapi.mixins.system import SystemAPIMixin 15 | from reolinkapi.mixins.user import UserAPIMixin 16 | from reolinkapi.mixins.zoom import ZoomAPIMixin 17 | from reolinkapi.mixins.nvrdownload import NvrDownloadAPIMixin 18 | 19 | 20 | class APIHandler(AlarmAPIMixin, 21 | DeviceAPIMixin, 22 | DisplayAPIMixin, 23 | DownloadAPIMixin, 24 | ImageAPIMixin, 25 | MotionAPIMixin, 26 | NetworkAPIMixin, 27 | PtzAPIMixin, 28 | RecordAPIMixin, 29 | SystemAPIMixin, 30 | UserAPIMixin, 31 | ZoomAPIMixin, 32 | StreamAPIMixin, 33 | NvrDownloadAPIMixin): 34 | """ 35 | The APIHandler class is the backend part of the API, the actual API calls 36 | are implemented in Mixins. 37 | This handles communication directly with the camera. 38 | Current camera's tested: RLC-411WS 39 | 40 | All Code will try to follow the PEP 8 standard as described here: https://www.python.org/dev/peps/pep-0008/ 41 | """ 42 | 43 | def __init__(self, ip: str, username: str, password: str, https: bool = False, **kwargs): 44 | """ 45 | Initialise the Camera API Handler (maps api calls into python) 46 | :param ip: 47 | :param username: 48 | :param password: 49 | :param https: connect over https 50 | :param proxy: Add a proxy dict for requests to consume. 51 | eg: {"http":"socks5://[username]:[password]@[host]:[port], "https": ...} 52 | More information on proxies in requests: https://stackoverflow.com/a/15661226/9313679 53 | """ 54 | scheme = 'https' if https else 'http' 55 | self.url = f"{scheme}://{ip}/cgi-bin/api.cgi" 56 | self.ip = ip 57 | self.token = None 58 | self.username = username 59 | self.password = password 60 | Request.proxies = kwargs.get("proxy") # Defaults to None if key isn't found 61 | Request.session = kwargs.get("session") # Defaults to None if key isn't found 62 | 63 | def login(self) -> bool: 64 | """ 65 | Get login token 66 | Must be called first, before any other operation can be performed 67 | :return: bool 68 | """ 69 | try: 70 | body = [{"cmd": "Login", "action": 0, 71 | "param": {"User": {"userName": self.username, "password": self.password}}}] 72 | param = {"cmd": "Login", "token": "null"} 73 | response = Request.post(self.url, data=body, params=param) 74 | if response is not None: 75 | data = response.json()[0] 76 | code = data["code"] 77 | if int(code) == 0: 78 | self.token = data["value"]["Token"]["name"] 79 | print("Login success") 80 | return True 81 | print(self.token) 82 | return False 83 | else: 84 | # TODO: Verify this change w/ owner. Delete old code if acceptable. 85 | # A this point, response is NoneType. There won't be a status code property. 86 | # print("Failed to login\nStatus Code:", response.status_code) 87 | print("Failed to login\nResponse was null.") 88 | return False 89 | except Exception as e: 90 | print("Error Login\n", e) 91 | raise 92 | 93 | def logout(self) -> bool: 94 | """ 95 | Logout of the camera 96 | :return: bool 97 | """ 98 | try: 99 | data = [{"cmd": "Logout", "action": 0}] 100 | self._execute_command('Logout', data) 101 | # print(ret) 102 | return True 103 | except Exception as e: 104 | print("Error Logout\n", e) 105 | return False 106 | 107 | def _execute_command(self, command: str, data: List[Dict], multi: bool = False) -> \ 108 | Optional[Union[Dict, bool]]: 109 | """ 110 | Send a POST request to the IP camera with given data. 111 | :param command: name of the command to send 112 | :param data: object to send to the camera (send as json) 113 | :param multi: whether the given command name should be added to the 114 | url parameters of the request. Defaults to False. (Some multi-step 115 | commands seem to not have a single command name) 116 | :return: response JSON as python object 117 | """ 118 | params = {"token": self.token, 'cmd': command} 119 | if multi: 120 | del params['cmd'] 121 | try: 122 | if self.token is None: 123 | raise ValueError("Login first") 124 | if command == 'Download' or command == 'Playback': 125 | # Special handling for downloading an mp4 126 | # Pop the filepath from data 127 | tgt_filepath = data[0].pop('filepath') 128 | # Apply the data to the params 129 | params.update(data[0]) 130 | with requests.get(self.url, params=params, stream=True, verify=False, timeout=(1, None), proxies=Request.proxies) as req: 131 | if req.status_code == 200: 132 | with open(tgt_filepath, 'wb') as f: 133 | f.write(req.content) 134 | return True 135 | else: 136 | print(f'Error received: {req.status_code}') 137 | return False 138 | 139 | else: 140 | response = Request.post(self.url, data=data, params=params) 141 | return response.json() 142 | except Exception as e: 143 | print(f"Command {command} failed: {e}") 144 | raise 145 | -------------------------------------------------------------------------------- /reolinkapi/handlers/rest_handler.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from typing import List, Dict, Union, Optional 3 | 4 | 5 | class Request: 6 | proxies = None 7 | session = None 8 | 9 | @staticmethod 10 | def __getSession(): 11 | reqHandler = requests 12 | if Request.session is not None: 13 | reqHandler = Request.session 14 | return reqHandler 15 | 16 | @staticmethod 17 | def post(url: str, data: List[Dict], params: Dict[str, Union[str, float]] = None) -> \ 18 | Optional[requests.Response]: 19 | """ 20 | Post request 21 | :param params: 22 | :param url: 23 | :param data: 24 | :return: 25 | """ 26 | try: 27 | headers = {'content-type': 'application/json'} 28 | r = Request.__getSession().post(url, verify=False, params=params, json=data, headers=headers, 29 | proxies=Request.proxies) 30 | if r.status_code == 200: 31 | return r 32 | else: 33 | raise ValueError(f"Http Request had non-200 Status: {r.status_code}", r.status_code) 34 | except Exception as e: 35 | print("Post Error\n", e) 36 | raise 37 | 38 | @staticmethod 39 | def get(url: str, params: Dict[str, Union[str, float]], timeout: float = 1) -> Optional[requests.Response]: 40 | """ 41 | Get request 42 | :param url: 43 | :param params: 44 | :param timeout: 45 | :return: 46 | """ 47 | try: 48 | data = Request.__getSession().get(url=url, verify=False, params=params, timeout=timeout, proxies=Request.proxies) 49 | return data 50 | except Exception as e: 51 | print("Get Error\n", e) 52 | raise 53 | -------------------------------------------------------------------------------- /reolinkapi/mixins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReolinkCameraAPI/reolinkapipy/e0fee8d9d31428791ff447a59f6fdf9d1e7d0682/reolinkapi/mixins/__init__.py -------------------------------------------------------------------------------- /reolinkapi/mixins/alarm.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class AlarmAPIMixin: 5 | """API calls for getting device alarm information.""" 6 | 7 | def get_alarm_motion(self) -> Dict: 8 | """ 9 | Gets the device alarm motion 10 | See examples/response/GetAlarmMotion.json for example response data. 11 | :return: response json 12 | """ 13 | body = [{"cmd": "GetAlarm", "action": 1, "param": {"Alarm": {"channel": 0, "type": "md"}}}] 14 | return self._execute_command('GetAlarm', body) 15 | -------------------------------------------------------------------------------- /reolinkapi/mixins/device.py: -------------------------------------------------------------------------------- 1 | from typing import List, Dict 2 | 3 | 4 | class DeviceAPIMixin: 5 | """API calls for getting device information.""" 6 | DEFAULT_HDD_ID = [0] 7 | 8 | def set_device_name(self, name: str) -> bool: 9 | """ 10 | Set the device name of the camera. 11 | :param name: The new name for the device 12 | :return: bool indicating success 13 | """ 14 | body = [{"cmd": "SetDevName", "action": 0, "param": {"DevName": {"name": name}}}] 15 | self._execute_command('SetDevName', body) 16 | print(f"Successfully set device name to: {name}") 17 | return True 18 | 19 | def get_device_name(self) -> Dict: 20 | """ 21 | Get the device name of the camera. 22 | :return: Dict containing the device name 23 | """ 24 | body = [{"cmd": "GetDevName", "action": 0, "param": {}}] 25 | return self._execute_command('GetDevName', body) 26 | 27 | def get_hdd_info(self) -> Dict: 28 | """ 29 | Gets all HDD and SD card information from Camera 30 | See examples/response/GetHddInfo.json for example response data. 31 | :return: response json 32 | """ 33 | body = [{"cmd": "GetHddInfo", "action": 0, "param": {}}] 34 | return self._execute_command('GetHddInfo', body) 35 | 36 | def format_hdd(self, hdd_id: List[float] = None) -> bool: 37 | """ 38 | Format specified HDD/SD cards with their id's 39 | :param hdd_id: List of id's specified by the camera with get_hdd_info api. Default is 0 (SD card) 40 | :return: bool 41 | """ 42 | if hdd_id is None: 43 | hdd_id = self.DEFAULT_HDD_ID 44 | body = [{"cmd": "Format", "action": 0, "param": {"HddInfo": {"id": hdd_id}}}] 45 | r_data = self._execute_command('Format', body)[0] 46 | if r_data["value"]["rspCode"] == 200: 47 | return True 48 | print("Could not format HDD/SD. Camera responded with:", r_data["value"]) 49 | return False 50 | -------------------------------------------------------------------------------- /reolinkapi/mixins/display.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class DisplayAPIMixin: 5 | """API calls related to the current image (osd, on screen display).""" 6 | 7 | def get_osd(self) -> Dict: 8 | """ 9 | Get OSD information. 10 | See examples/response/GetOsd.json for example response data. 11 | :return: response json 12 | """ 13 | body = [{"cmd": "GetOsd", "action": 1, "param": {"channel": 0}}] 14 | return self._execute_command('GetOsd', body) 15 | 16 | def get_mask(self) -> Dict: 17 | """ 18 | Get the camera mask information. 19 | See examples/response/GetMask.json for example response data. 20 | :return: response json 21 | """ 22 | body = [{"cmd": "GetMask", "action": 1, "param": {"channel": 0}}] 23 | return self._execute_command('GetMask', body) 24 | 25 | def set_osd(self, bg_color: bool = 0, channel: float = 0, osd_channel_enabled: bool = 0, 26 | osd_channel_name: str = "", osd_channel_pos: str = "Lower Right", osd_time_enabled: bool = 0, 27 | osd_time_pos: str = "Lower Right", osd_watermark_enabled: bool = 0) -> bool: 28 | """ 29 | Set OSD 30 | :param bg_color: bool 31 | :param channel: int channel id 32 | :param osd_channel_enabled: bool 33 | :param osd_channel_name: string channel name 34 | :param osd_channel_pos: string channel position 35 | ["Upper Left","Top Center","Upper Right","Lower Left","Bottom Center","Lower Right"] 36 | :param osd_time_enabled: bool 37 | :param osd_time_pos: string time position 38 | ["Upper Left","Top Center","Upper Right","Lower Left","Bottom Center","Lower Right"] 39 | :return: whether the action was successful 40 | """ 41 | body = [{"cmd": "SetOsd", "action": 1, 42 | "param": { 43 | "Osd": { 44 | "bgcolor": bg_color, 45 | "channel": channel, 46 | "osdChannel": { 47 | "enable": osd_channel_enabled, "name": osd_channel_name, 48 | "pos": osd_channel_pos 49 | }, 50 | "osdTime": {"enable": osd_time_enabled, "pos": osd_time_pos}, 51 | "watermark": osd_watermark_enabled, 52 | }}}] 53 | r_data = self._execute_command('SetOsd', body)[0] 54 | if 'value' in r_data and r_data["value"]["rspCode"] == 200: 55 | return True 56 | print("Could not set OSD. Camera responded with status:", r_data["error"]) 57 | return False 58 | -------------------------------------------------------------------------------- /reolinkapi/mixins/download.py: -------------------------------------------------------------------------------- 1 | class DownloadAPIMixin: 2 | """API calls for downloading video files.""" 3 | def get_file(self, filename: str, output_path: str, method = 'Playback') -> bool: 4 | """ 5 | Download the selected video file 6 | On at least Trackmix Wifi, it was observed that the Playback method 7 | yields much improved download speeds over the Download method, for 8 | unknown reasons. 9 | :return: response json 10 | """ 11 | body = [ 12 | { 13 | "cmd": method, 14 | "source": filename, 15 | "output": filename, 16 | "filepath": output_path 17 | } 18 | ] 19 | resp = self._execute_command(method, body) 20 | 21 | return resp 22 | -------------------------------------------------------------------------------- /reolinkapi/mixins/image.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class ImageAPIMixin: 5 | """API calls for image settings.""" 6 | 7 | def set_adv_image_settings(self, 8 | anti_flicker: str = 'Outdoor', 9 | exposure: str = 'Auto', 10 | gain_min: float = 1, 11 | gain_max: float = 62, 12 | shutter_min: float = 1, 13 | shutter_max: float = 125, 14 | blue_gain: float = 128, 15 | red_gain: float = 128, 16 | white_balance: str = 'Auto', 17 | day_night: str = 'Auto', 18 | back_light: str = 'DynamicRangeControl', 19 | blc: float = 128, 20 | drc: float = 128, 21 | rotation: float = 0, 22 | mirroring: float = 0, 23 | nr3d: float = 1) -> Dict: 24 | """ 25 | Sets the advanced camera settings. 26 | 27 | :param anti_flicker: string 28 | :param exposure: string 29 | :param gain_min: int 30 | :param gain_max: string 31 | :param shutter_min: int 32 | :param shutter_max: int 33 | :param blue_gain: int 34 | :param red_gain: int 35 | :param white_balance: string 36 | :param day_night: string 37 | :param back_light: string 38 | :param blc: int 39 | :param drc: int 40 | :param rotation: int 41 | :param mirroring: int 42 | :param nr3d: int 43 | :return: response 44 | """ 45 | body = [{ 46 | "cmd": "SetIsp", 47 | "action": 0, 48 | "param": { 49 | "Isp": { 50 | "channel": 0, 51 | "antiFlicker": anti_flicker, 52 | "exposure": exposure, 53 | "gain": {"min": gain_min, "max": gain_max}, 54 | "shutter": {"min": shutter_min, "max": shutter_max}, 55 | "blueGain": blue_gain, 56 | "redGain": red_gain, 57 | "whiteBalance": white_balance, 58 | "dayNight": day_night, 59 | "backLight": back_light, 60 | "blc": blc, 61 | "drc": drc, 62 | "rotation": rotation, 63 | "mirroring": mirroring, 64 | "nr3d": nr3d 65 | } 66 | } 67 | }] 68 | return self._execute_command('SetIsp', body) 69 | 70 | def set_image_settings(self, 71 | brightness: float = 128, 72 | contrast: float = 62, 73 | hue: float = 1, 74 | saturation: float = 125, 75 | sharpness: float = 128) -> Dict: 76 | """ 77 | Sets the camera image settings. 78 | 79 | :param brightness: int 80 | :param contrast: string 81 | :param hue: int 82 | :param saturation: int 83 | :param sharpness: int 84 | :return: response 85 | """ 86 | body = [ 87 | { 88 | "cmd": "SetImage", 89 | "action": 0, 90 | "param": { 91 | "Image": { 92 | "bright": brightness, 93 | "channel": 0, 94 | "contrast": contrast, 95 | "hue": hue, 96 | "saturation": saturation, 97 | "sharpen": sharpness 98 | } 99 | } 100 | } 101 | ] 102 | 103 | return self._execute_command('SetImage', body) 104 | -------------------------------------------------------------------------------- /reolinkapi/mixins/motion.py: -------------------------------------------------------------------------------- 1 | from typing import Union, List, Dict 2 | from datetime import datetime as dt 3 | 4 | 5 | # Type hints for input and output of the motion api response 6 | RAW_MOTION_LIST_TYPE = List[Dict[str, Union[str, float, Dict[str, str]]]] 7 | PROCESSED_MOTION_LIST_TYPE = List[Dict[str, Union[str, dt]]] 8 | 9 | 10 | class MotionAPIMixin: 11 | """API calls for past motion alerts.""" 12 | def get_motion_files(self, start: dt, end: dt = dt.now(), 13 | streamtype: str = 'sub', channel = 0) -> PROCESSED_MOTION_LIST_TYPE: 14 | """ 15 | Get the timestamps and filenames of motion detection events for the time range provided. 16 | 17 | Args: 18 | start: the starting time range to examine 19 | end: the end time of the time range to examine 20 | streamtype: 'main' or 'sub' - the stream to examine 21 | :return: response json 22 | """ 23 | search_params = { 24 | 'Search': { 25 | 'channel': channel, 26 | 'streamType': streamtype, 27 | 'onlyStatus': 0, 28 | 'StartTime': { 29 | 'year': start.year, 30 | 'mon': start.month, 31 | 'day': start.day, 32 | 'hour': start.hour, 33 | 'min': start.minute, 34 | 'sec': start.second 35 | }, 36 | 'EndTime': { 37 | 'year': end.year, 38 | 'mon': end.month, 39 | 'day': end.day, 40 | 'hour': end.hour, 41 | 'min': end.minute, 42 | 'sec': end.second 43 | } 44 | } 45 | } 46 | body = [{"cmd": "Search", "action": 1, "param": search_params}] 47 | 48 | resp = self._execute_command('Search', body)[0] 49 | if 'value' not in resp: 50 | return [] 51 | values = resp['value'] 52 | if 'SearchResult' not in values: 53 | return [] 54 | result = values['SearchResult'] 55 | files = result.get('File', []) 56 | if len(files) > 0: 57 | # Begin processing files 58 | processed_files = self._process_motion_files(files) 59 | return processed_files 60 | return [] 61 | 62 | @staticmethod 63 | def _process_motion_files(motion_files: RAW_MOTION_LIST_TYPE) -> PROCESSED_MOTION_LIST_TYPE: 64 | """Processes raw list of dicts containing motion timestamps 65 | and the filename associated with them""" 66 | # Process files 67 | processed_motions = [] 68 | replace_fields = {'mon': 'month', 'sec': 'second', 'min': 'minute'} 69 | for file in motion_files: 70 | time_range = {} 71 | for x in ['Start', 'End']: 72 | # Get raw dict 73 | raw = file[f'{x}Time'] 74 | # Replace certain keys 75 | for k, v in replace_fields.items(): 76 | if k in raw.keys(): 77 | raw[v] = raw.pop(k) 78 | time_range[x.lower()] = dt(**raw) 79 | start, end = time_range.values() 80 | processed_motions.append({ 81 | 'start': start, 82 | 'end': end, 83 | 'filename': file['name'] 84 | }) 85 | return processed_motions 86 | -------------------------------------------------------------------------------- /reolinkapi/mixins/network.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class NetworkAPIMixin: 5 | """API calls for network settings.""" 6 | def set_network_settings(self, ip: str, gateway: str, mask: str, dns1: str, dns2: str, mac: str, 7 | use_dhcp: bool = True, auto_dns: bool = True) -> Dict: 8 | """ 9 | Set network settings including IP, gateway, subnet mask, DNS, and connection type (DHCP or Static). 10 | 11 | :param ip: str 12 | :param gateway: str 13 | :param mask: str 14 | :param dns1: str 15 | :param dns2: str 16 | :param mac: str 17 | :param use_dhcp: bool 18 | :param auto_dns: bool 19 | :return: Dict 20 | """ 21 | body = [{"cmd": "SetLocalLink", "action": 0, "param": { 22 | "LocalLink": { 23 | "dns": { 24 | "auto": 1 if auto_dns else 0, 25 | "dns1": dns1, 26 | "dns2": dns2 27 | }, 28 | "mac": mac, 29 | "static": { 30 | "gateway": gateway, 31 | "ip": ip, 32 | "mask": mask 33 | }, 34 | "type": "DHCP" if use_dhcp else "Static" 35 | } 36 | }}] 37 | 38 | return self._execute_command('SetLocalLink', body) 39 | print("Successfully Set Network Settings") 40 | return True 41 | 42 | def set_net_port(self, http_port: float = 80, https_port: float = 443, media_port: float = 9000, 43 | onvif_port: float = 8000, rtmp_port: float = 1935, rtsp_port: float = 554) -> bool: 44 | """ 45 | Set network ports 46 | If nothing is specified, the default values will be used 47 | :param rtsp_port: int 48 | :param rtmp_port: int 49 | :param onvif_port: int 50 | :param media_port: int 51 | :param https_port: int 52 | :type http_port: int 53 | :return: bool 54 | """ 55 | body = [{"cmd": "SetNetPort", "action": 0, "param": {"NetPort": { 56 | "httpPort": http_port, 57 | "httpsPort": https_port, 58 | "mediaPort": media_port, 59 | "onvifPort": onvif_port, 60 | "rtmpPort": rtmp_port, 61 | "rtspPort": rtsp_port 62 | }}}] 63 | self._execute_command('SetNetPort', body, multi=True) 64 | print("Successfully Set Network Ports") 65 | return True 66 | 67 | def set_wifi(self, ssid: str, password: str) -> Dict: 68 | body = [{"cmd": "SetWifi", "action": 0, "param": { 69 | "Wifi": { 70 | "ssid": ssid, 71 | "password": password 72 | }}}] 73 | return self._execute_command('SetWifi', body) 74 | 75 | def set_ntp(self, enable: bool = True, interval: int = 1440, port: int = 123, server: str = "pool.ntp.org") -> Dict: 76 | """ 77 | Set NTP settings. 78 | 79 | :param enable: bool 80 | :param interval: int 81 | :param port: int 82 | :param server: str 83 | :return: Dict 84 | """ 85 | body = [{"cmd": "SetNtp", "action": 0, "param": { 86 | "Ntp": { 87 | "enable": int(enable), 88 | "interval": interval, 89 | "port": port, 90 | "server": server 91 | }}}] 92 | response = self._execute_command('SetNtp', body) 93 | print("Successfully Set NTP Settings") 94 | return response 95 | 96 | def get_net_ports(self) -> Dict: 97 | """ 98 | Get network ports 99 | See examples/response/GetNetworkAdvanced.json for example response data. 100 | :return: response json 101 | """ 102 | body = [{"cmd": "GetNetPort", "action": 1, "param": {}}, 103 | {"cmd": "GetUpnp", "action": 0, "param": {}}, 104 | {"cmd": "GetP2p", "action": 0, "param": {}}] 105 | return self._execute_command('GetNetPort', body, multi=True) 106 | 107 | def get_wifi(self) -> Dict: 108 | body = [{"cmd": "GetWifi", "action": 1, "param": {}}] 109 | return self._execute_command('GetWifi', body) 110 | 111 | def scan_wifi(self) -> Dict: 112 | body = [{"cmd": "ScanWifi", "action": 1, "param": {}}] 113 | return self._execute_command('ScanWifi', body) 114 | 115 | def get_network_general(self) -> Dict: 116 | """ 117 | Get the camera information 118 | See examples/response/GetNetworkGeneral.json for example response data. 119 | :return: response json 120 | """ 121 | body = [{"cmd": "GetLocalLink", "action": 0, "param": {}}] 122 | return self._execute_command('GetLocalLink', body) 123 | 124 | def get_network_ddns(self) -> Dict: 125 | """ 126 | Get the camera DDNS network information 127 | See examples/response/GetNetworkDDNS.json for example response data. 128 | :return: response json 129 | """ 130 | body = [{"cmd": "GetDdns", "action": 0, "param": {}}] 131 | return self._execute_command('GetDdns', body) 132 | 133 | def get_network_ntp(self) -> Dict: 134 | """ 135 | Get the camera NTP network information 136 | See examples/response/GetNetworkNTP.json for example response data. 137 | :return: response json 138 | """ 139 | body = [{"cmd": "GetNtp", "action": 0, "param": {}}] 140 | return self._execute_command('GetNtp', body) 141 | 142 | def get_network_email(self) -> Dict: 143 | """ 144 | Get the camera email network information 145 | See examples/response/GetNetworkEmail.json for example response data. 146 | :return: response json 147 | """ 148 | body = [{"cmd": "GetEmail", "action": 0, "param": {}}] 149 | return self._execute_command('GetEmail', body) 150 | 151 | def get_network_ftp(self) -> Dict: 152 | """ 153 | Get the camera FTP network information 154 | See examples/response/GetNetworkFtp.json for example response data. 155 | :return: response json 156 | """ 157 | body = [{"cmd": "GetFtp", "action": 0, "param": {}}] 158 | return self._execute_command('GetFtp', body) 159 | 160 | def get_network_push(self) -> Dict: 161 | """ 162 | Get the camera push network information 163 | See examples/response/GetNetworkPush.json for example response data. 164 | :return: response json 165 | """ 166 | body = [{"cmd": "GetPush", "action": 0, "param": {}}] 167 | return self._execute_command('GetPush', body) 168 | 169 | def get_network_status(self) -> Dict: 170 | """ 171 | Get the camera status network information 172 | See examples/response/GetNetworkGeneral.json for example response data. 173 | :return: response json 174 | """ 175 | return self.get_network_general() 176 | -------------------------------------------------------------------------------- /reolinkapi/mixins/nvrdownload.py: -------------------------------------------------------------------------------- 1 | from datetime import datetime as dt 2 | 3 | class NvrDownloadAPIMixin: 4 | """API calls for NvrDownload.""" 5 | def get_playback_files(self, start: dt, end: dt = dt.now(), channel: int = 0, 6 | streamtype: str = 'sub'): 7 | """ 8 | Get the filenames of the videos for the time range provided. 9 | 10 | Args: 11 | start: the starting time range to examine 12 | end: the end time of the time range to examine 13 | channel: which channel to download from 14 | streamtype: 'main' or 'sub' - the stream to examine 15 | :return: response json 16 | """ 17 | search_params = { 18 | 'NvrDownload': { 19 | 'channel': channel, 20 | 'iLogicChannel': 0, 21 | 'streamType': streamtype, 22 | 'StartTime': { 23 | 'year': start.year, 24 | 'mon': start.month, 25 | 'day': start.day, 26 | 'hour': start.hour, 27 | 'min': start.minute, 28 | 'sec': start.second 29 | }, 30 | 'EndTime': { 31 | 'year': end.year, 32 | 'mon': end.month, 33 | 'day': end.day, 34 | 'hour': end.hour, 35 | 'min': end.minute, 36 | 'sec': end.second 37 | } 38 | } 39 | } 40 | body = [{"cmd": "NvrDownload", "action": 1, "param": search_params}] 41 | try: 42 | resp = self._execute_command('NvrDownload', body)[0] 43 | except Exception as e: 44 | print(f"Error: {e}") 45 | return [] 46 | if 'value' not in resp: 47 | return [] 48 | values = resp['value'] 49 | if 'fileList' not in values: 50 | return [] 51 | files = values['fileList'] 52 | if len(files) > 0: 53 | return [file['fileName'] for file in files] 54 | return [] 55 | -------------------------------------------------------------------------------- /reolinkapi/mixins/ptz.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class PtzAPIMixin: 5 | """ 6 | API for PTZ functions. 7 | """ 8 | def get_ptz_check_state(self) -> Dict: 9 | """ 10 | Get PTZ Check State Information that indicates whether calibration is required (0) running (1) or done (2) 11 | Value is contained in response[0]["value"]["PtzCheckState"]. 12 | See examples/response/GetPtzCheckState.json for example response data. 13 | :return: response json 14 | """ 15 | body = [{"cmd": "GetPtzCheckState", "action": 1, "param": { "channel": 0}}] 16 | return self._execute_command('GetPtzCheckState', body) 17 | 18 | def get_ptz_presets(self) -> Dict: 19 | """ 20 | Get ptz presets 21 | See examples/response/GetPtzPresets.json for example response data. 22 | :return: response json 23 | """ 24 | 25 | body = [{"cmd": "GetPtzPreset", "action": 1, "param": { "channel": 0}}] 26 | return self._execute_command('GetPtzPreset', body) 27 | 28 | def perform_calibration(self) -> Dict: 29 | """ 30 | Do the calibration (like app -> ptz -> three dots -> calibration). Moves camera to all end positions. 31 | If not calibrated, your viewpoint of presets might drift. So before setting new presets, or moving to preset, 32 | check calibration status (get_ptz_check_state -> 2 = calibrated) and perform calibration if not yet calibrated. 33 | As of 2024-01-23 (most recent firmware 3.1.0.1711_23010700 for E1 Zoom) does not do this on startup. 34 | Method blocks while calibrating. 35 | See examples/response/PtzCheck.json for example response data. 36 | :return: response json 37 | """ 38 | data = [{"cmd": "PtzCheck", "action": 0, "param": {"channel": 0}}] 39 | return self._execute_command('PtzCheck', data) 40 | 41 | def _send_operation(self, operation: str, speed: float, index: float = None) -> Dict: 42 | # Refactored to reduce redundancy 43 | param = {"channel": 0, "op": operation, "speed": speed} 44 | if index is not None: 45 | param['id'] = index 46 | data = [{"cmd": "PtzCtrl", "action": 0, "param": param}] 47 | return self._execute_command('PtzCtrl', data) 48 | 49 | def _send_noparm_operation(self, operation: str) -> Dict: 50 | data = [{"cmd": "PtzCtrl", "action": 0, "param": {"channel": 0, "op": operation}}] 51 | return self._execute_command('PtzCtrl', data) 52 | 53 | def _send_set_preset(self, enable: float, preset: float = 1, name: str = 'pos1') -> Dict: 54 | data = [{"cmd": "SetPtzPreset", "action": 0, "param": { 55 | "channel": 0, "enable": enable, "id": preset, "name": name}}] 56 | return self._execute_command('PtzCtrl', data) 57 | 58 | def go_to_preset(self, speed: float = 60, index: float = 1) -> Dict: 59 | """ 60 | Move the camera to a preset location 61 | :return: response json 62 | """ 63 | return self._send_operation('ToPos', speed=speed, index=index) 64 | 65 | def add_preset(self, preset: float = 1, name: str = 'pos1') -> Dict: 66 | """ 67 | Adds the current camera position to the specified preset. 68 | :return: response json 69 | """ 70 | return self._send_set_preset(enable=1, preset=preset, name=name) 71 | 72 | def remove_preset(self, preset: float = 1, name: str = 'pos1') -> Dict: 73 | """ 74 | Removes the specified preset 75 | :return: response json 76 | """ 77 | return self._send_set_preset(enable=0, preset=preset, name=name) 78 | 79 | def move_right(self, speed: float = 25) -> Dict: 80 | """ 81 | Move the camera to the right 82 | The camera moves self.stop_ptz() is called. 83 | :return: response json 84 | """ 85 | return self._send_operation('Right', speed=speed) 86 | 87 | def move_right_up(self, speed: float = 25) -> Dict: 88 | """ 89 | Move the camera to the right and up 90 | The camera moves self.stop_ptz() is called. 91 | :return: response json 92 | """ 93 | return self._send_operation('RightUp', speed=speed) 94 | 95 | def move_right_down(self, speed: float = 25) -> Dict: 96 | """ 97 | Move the camera to the right and down 98 | The camera moves self.stop_ptz() is called. 99 | :return: response json 100 | """ 101 | return self._send_operation('RightDown', speed=speed) 102 | 103 | def move_left(self, speed: float = 25) -> Dict: 104 | """ 105 | Move the camera to the left 106 | The camera moves self.stop_ptz() is called. 107 | :return: response json 108 | """ 109 | return self._send_operation('Left', speed=speed) 110 | 111 | def move_left_up(self, speed: float = 25) -> Dict: 112 | """ 113 | Move the camera to the left and up 114 | The camera moves self.stop_ptz() is called. 115 | :return: response json 116 | """ 117 | return self._send_operation('LeftUp', speed=speed) 118 | 119 | def move_left_down(self, speed: float = 25) -> Dict: 120 | """ 121 | Move the camera to the left and down 122 | The camera moves self.stop_ptz() is called. 123 | :return: response json 124 | """ 125 | return self._send_operation('LeftDown', speed=speed) 126 | 127 | def move_up(self, speed: float = 25) -> Dict: 128 | """ 129 | Move the camera up. 130 | The camera moves self.stop_ptz() is called. 131 | :return: response json 132 | """ 133 | return self._send_operation('Up', speed=speed) 134 | 135 | def move_down(self, speed: float = 25) -> Dict: 136 | """ 137 | Move the camera down. 138 | The camera moves self.stop_ptz() is called. 139 | :return: response json 140 | """ 141 | return self._send_operation('Down', speed=speed) 142 | 143 | def stop_ptz(self) -> Dict: 144 | """ 145 | Stops the cameras current action. 146 | :return: response json 147 | """ 148 | return self._send_noparm_operation('Stop') 149 | 150 | def auto_movement(self, speed: float = 25) -> Dict: 151 | """ 152 | Move the camera in a clockwise rotation. 153 | The camera moves self.stop_ptz() is called. 154 | :return: response json 155 | """ 156 | return self._send_operation('Auto', speed=speed) 157 | -------------------------------------------------------------------------------- /reolinkapi/mixins/record.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class RecordAPIMixin: 5 | """API calls for the recording settings""" 6 | 7 | def get_recording_encoding(self) -> Dict: 8 | """ 9 | Get the current camera encoding settings for "Clear" and "Fluent" profiles. 10 | See examples/response/GetEnc.json for example response data. 11 | :return: response json 12 | """ 13 | body = [{"cmd": "GetEnc", "action": 1, "param": {"channel": 0}}] 14 | return self._execute_command('GetEnc', body) 15 | 16 | def get_recording_advanced(self) -> Dict: 17 | """ 18 | Get recording advanced setup data 19 | See examples/response/GetRec.json for example response data. 20 | :return: response json 21 | """ 22 | body = [{"cmd": "GetRec", "action": 1, "param": {"channel": 0}}] 23 | return self._execute_command('GetRec', body) 24 | 25 | def set_recording_encoding(self, 26 | audio: float = 0, 27 | main_bit_rate: float = 8192, 28 | main_frame_rate: float = 8, 29 | main_profile: str = 'High', 30 | main_size: str = "2560*1440", 31 | sub_bit_rate: float = 160, 32 | sub_frame_rate: float = 7, 33 | sub_profile: str = 'High', 34 | sub_size: str = '640*480') -> Dict: 35 | """ 36 | Sets the current camera encoding settings for "Clear" and "Fluent" profiles. 37 | :param audio: int Audio on or off 38 | :param main_bit_rate: int Clear Bit Rate 39 | :param main_frame_rate: int Clear Frame Rate 40 | :param main_profile: string Clear Profile 41 | :param main_size: string Clear Size 42 | :param sub_bit_rate: int Fluent Bit Rate 43 | :param sub_frame_rate: int Fluent Frame Rate 44 | :param sub_profile: string Fluent Profile 45 | :param sub_size: string Fluent Size 46 | :return: response 47 | """ 48 | body = [ 49 | { 50 | "cmd": "SetEnc", 51 | "action": 0, 52 | "param": { 53 | "Enc": { 54 | "audio": audio, 55 | "channel": 0, 56 | "mainStream": { 57 | "bitRate": main_bit_rate, 58 | "frameRate": main_frame_rate, 59 | "profile": main_profile, 60 | "size": main_size 61 | }, 62 | "subStream": { 63 | "bitRate": sub_bit_rate, 64 | "frameRate": sub_frame_rate, 65 | "profile": sub_profile, 66 | "size": sub_size 67 | } 68 | } 69 | } 70 | } 71 | ] 72 | return self._execute_command('SetEnc', body) 73 | -------------------------------------------------------------------------------- /reolinkapi/mixins/stream.py: -------------------------------------------------------------------------------- 1 | import string 2 | from random import choices 3 | from typing import Any, Optional 4 | from urllib import parse 5 | from io import BytesIO 6 | 7 | import requests 8 | 9 | try: 10 | from PIL.Image import Image, open as open_image 11 | 12 | from reolinkapi.utils.rtsp_client import RtspClient 13 | 14 | 15 | class StreamAPIMixin: 16 | """ API calls for opening a video stream or capturing an image from the camera.""" 17 | 18 | def open_video_stream(self, callback: Any = None, proxies: Any = None) -> Any: 19 | """ 20 | 'https://support.reolink.com/hc/en-us/articles/360007010473-How-to-Live-View-Reolink-Cameras-via-VLC-Media-Player' 21 | Blocking function creates a generator and returns the frames as it is spawned 22 | :param callback: 23 | :param proxies: Default is none, example: {"host": "localhost", "port": 8000} 24 | """ 25 | rtsp_client = RtspClient( 26 | ip=self.ip, username=self.username, password=self.password, profile=self.profile, proxies=proxies, callback=callback) 27 | return rtsp_client.open_stream() 28 | 29 | def get_snap(self, timeout: float = 3, proxies: Any = None) -> Optional[Image]: 30 | """ 31 | Gets a "snap" of the current camera video data and returns a Pillow Image or None 32 | :param timeout: Request timeout to camera in seconds 33 | :param proxies: http/https proxies to pass to the request object. 34 | :return: Image or None 35 | """ 36 | data = { 37 | 'cmd': 'Snap', 38 | 'channel': 0, 39 | 'rs': ''.join(choices(string.ascii_uppercase + string.digits, k=10)), 40 | 'user': self.username, 41 | 'password': self.password, 42 | } 43 | parms = parse.urlencode(data).encode("utf-8") 44 | 45 | try: 46 | response = requests.get(self.url, proxies=proxies, params=parms, timeout=timeout) 47 | if response.status_code == 200: 48 | return open_image(BytesIO(response.content)) 49 | print("Could not retrieve data from camera successfully. Status:", response.status_code) 50 | return None 51 | 52 | except Exception as e: 53 | print("Could not get Image data\n", e) 54 | raise 55 | except ImportError as err: 56 | print("ImportError", err) 57 | 58 | class StreamAPIMixin: 59 | """ API calls for opening a video stream or capturing an image from the camera.""" 60 | 61 | def open_video_stream(self, callback: Any = None, proxies: Any = None) -> Any: 62 | raise ImportError(f'open_video_stream requires streaming extra dependencies\nFor instance "pip install ' 63 | f'reolinkapi[streaming]"') 64 | 65 | def get_snap(self, timeout: float = 3, proxies: Any = None) -> Optional['Image']: 66 | raise ImportError( 67 | f'get_snap requires streaming extra dependencies\nFor instance "pip install reolinkapi[streaming]"') 68 | -------------------------------------------------------------------------------- /reolinkapi/mixins/system.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class SystemAPIMixin: 5 | """API for accessing general system information of the camera.""" 6 | def get_general_system(self) -> Dict: 7 | """:return: response json""" 8 | body = [{"cmd": "GetTime", "action": 1, "param": {}}, {"cmd": "GetNorm", "action": 1, "param": {}}] 9 | return self._execute_command('get_general_system', body, multi=True) 10 | 11 | def get_performance(self) -> Dict: 12 | """ 13 | Get a snapshot of the current performance of the camera. 14 | See examples/response/GetPerformance.json for example response data. 15 | :return: response json 16 | """ 17 | body = [{"cmd": "GetPerformance", "action": 0, "param": {}}] 18 | return self._execute_command('GetPerformance', body) 19 | 20 | def get_information(self) -> Dict: 21 | """ 22 | Get the camera information 23 | See examples/response/GetDevInfo.json for example response data. 24 | :return: response json 25 | """ 26 | body = [{"cmd": "GetDevInfo", "action": 0, "param": {}}] 27 | return self._execute_command('GetDevInfo', body) 28 | 29 | def reboot_camera(self) -> Dict: 30 | """ 31 | Reboots the camera 32 | :return: response json 33 | """ 34 | body = [{"cmd": "Reboot", "action": 0, "param": {}}] 35 | return self._execute_command('Reboot', body) 36 | 37 | def get_dst(self) -> Dict: 38 | """ 39 | Get the camera DST information 40 | See examples/response/GetDSTInfo.json for example response data. 41 | :return: response json 42 | """ 43 | body = [{"cmd": "GetTime", "action": 0, "param": {}}] 44 | return self._execute_command('GetTime', body) 45 | -------------------------------------------------------------------------------- /reolinkapi/mixins/user.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class UserAPIMixin: 5 | """User-related API calls.""" 6 | def get_online_user(self) -> Dict: 7 | """ 8 | Return a list of current logged-in users in json format 9 | See examples/response/GetOnline.json for example response data. 10 | :return: response json 11 | """ 12 | body = [{"cmd": "GetOnline", "action": 1, "param": {}}] 13 | return self._execute_command('GetOnline', body) 14 | 15 | def get_users(self) -> Dict: 16 | """ 17 | Return a list of user accounts from the camera in json format. 18 | See examples/response/GetUser.json for example response data. 19 | :return: response json 20 | """ 21 | body = [{"cmd": "GetUser", "action": 1, "param": {}}] 22 | return self._execute_command('GetUser', body) 23 | 24 | def add_user(self, username: str, password: str, level: str = "guest") -> bool: 25 | """ 26 | Add a new user account to the camera 27 | :param username: The user's username 28 | :param password: The user's password 29 | :param level: The privilege level 'guest' or 'admin'. Default is 'guest' 30 | :return: whether the user was added successfully 31 | """ 32 | body = [{"cmd": "AddUser", "action": 0, 33 | "param": {"User": {"userName": username, "password": password, "level": level}}}] 34 | r_data = self._execute_command('AddUser', body)[0] 35 | if r_data["value"]["rspCode"] == 200: 36 | return True 37 | print("Could not add user. Camera responded with:", r_data["value"]) 38 | return False 39 | 40 | def modify_user(self, username: str, password: str) -> bool: 41 | """ 42 | Modify the user's password by specifying their username 43 | :param username: The user which would want to be modified 44 | :param password: The new password 45 | :return: whether the user was modified successfully 46 | """ 47 | body = [{"cmd": "ModifyUser", "action": 0, "param": {"User": {"userName": username, "password": password}}}] 48 | r_data = self._execute_command('ModifyUser', body)[0] 49 | if r_data["value"]["rspCode"] == 200: 50 | return True 51 | print(f"Could not modify user: {username}\nCamera responded with: {r_data['value']}") 52 | return False 53 | 54 | def delete_user(self, username: str) -> bool: 55 | """ 56 | Delete a user by specifying their username 57 | :param username: The user which would want to be deleted 58 | :return: whether the user was deleted successfully 59 | """ 60 | body = [{"cmd": "DelUser", "action": 0, "param": {"User": {"userName": username}}}] 61 | r_data = self._execute_command('DelUser', body)[0] 62 | if r_data["value"]["rspCode"] == 200: 63 | return True 64 | print(f"Could not delete user: {username}\nCamera responded with: {r_data['value']}") 65 | return False 66 | -------------------------------------------------------------------------------- /reolinkapi/mixins/zoom.py: -------------------------------------------------------------------------------- 1 | from typing import Dict 2 | 3 | 4 | class ZoomAPIMixin: 5 | """ 6 | API for zooming and changing focus. 7 | Note that the API does not allow zooming/focusing by absolute 8 | values rather that changing focus/zoom for a given time. 9 | """ 10 | def _start_operation(self, operation: str, speed: float) -> Dict: 11 | data = [{"cmd": "PtzCtrl", "action": 0, "param": {"channel": 0, "op": operation, "speed": speed}}] 12 | return self._execute_command('PtzCtrl', data) 13 | 14 | def _stop_zooming_or_focusing(self) -> Dict: 15 | """This command stops any ongoing zooming or focusing actions.""" 16 | data = [{"cmd": "PtzCtrl", "action": 0, "param": {"channel": 0, "op": "Stop"}}] 17 | return self._execute_command('PtzCtrl', data) 18 | 19 | def get_zoom_focus(self) -> Dict: 20 | """This command returns the current zoom and focus values.""" 21 | data = [{"cmd": "GetZoomFocus", "action": 0, "param": {"channel": 0}}] 22 | return self._execute_command('GetZoomFocus', data) 23 | 24 | def start_zoom_pos(self, position: float) -> Dict: 25 | """This command sets the zoom position.""" 26 | data = [{"cmd": "StartZoomFocus", "action": 0, "param": {"ZoomFocus": {"channel": 0, "op": "ZoomPos", "pos": position}}}] 27 | return self._execute_command('StartZoomFocus', data) 28 | 29 | def start_focus_pos(self, position: float) -> Dict: 30 | """This command sets the focus position.""" 31 | data = [{"cmd": "StartZoomFocus", "action": 0, "param": {"ZoomFocus": {"channel": 0, "op": "FocusPos", "pos": position}}}] 32 | return self._execute_command('StartZoomFocus', data) 33 | 34 | def get_auto_focus(self) -> Dict: 35 | """This command returns the current auto focus status.""" 36 | data = [{"cmd": "GetAutoFocus", "action": 0, "param": {"channel": 0}}] 37 | return self._execute_command('GetAutoFocus', data) 38 | 39 | def set_auto_focus(self, disable: bool) -> Dict: 40 | """This command sets the auto focus status.""" 41 | data = [{"cmd": "SetAutoFocus", "action": 0, "param": {"AutoFocus": {"channel": 0, "disable": 1 if disable else 0}}}] 42 | return self._execute_command('SetAutoFocus', data) 43 | 44 | def start_zooming_in(self, speed: float = 60) -> Dict: 45 | """ 46 | The camera zooms in until self.stop_zooming() is called. 47 | :return: response json 48 | """ 49 | return self._start_operation('ZoomInc', speed=speed) 50 | 51 | def start_zooming_out(self, speed: float = 60) -> Dict: 52 | """ 53 | The camera zooms out until self.stop_zooming() is called. 54 | :return: response json 55 | """ 56 | return self._start_operation('ZoomDec', speed=speed) 57 | 58 | def stop_zooming(self) -> Dict: 59 | """ 60 | Stop zooming. 61 | :return: response json 62 | """ 63 | return self._stop_zooming_or_focusing() 64 | 65 | def start_focusing_in(self, speed: float = 32) -> Dict: 66 | """ 67 | The camera focuses in until self.stop_focusing() is called. 68 | :return: response json 69 | """ 70 | return self._start_operation('FocusInc', speed=speed) 71 | 72 | def start_focusing_out(self, speed: float = 32) -> Dict: 73 | """ 74 | The camera focuses out until self.stop_focusing() is called. 75 | :return: response json 76 | """ 77 | return self._start_operation('FocusDec', speed=speed) 78 | 79 | def stop_focusing(self) -> Dict: 80 | """ 81 | Stop focusing. 82 | :return: response json 83 | """ 84 | return self._stop_zooming_or_focusing() 85 | -------------------------------------------------------------------------------- /reolinkapi/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ReolinkCameraAPI/reolinkapipy/e0fee8d9d31428791ff447a59f6fdf9d1e7d0682/reolinkapi/utils/__init__.py -------------------------------------------------------------------------------- /reolinkapi/utils/rtsp_client.py: -------------------------------------------------------------------------------- 1 | import os 2 | from threading import ThreadError 3 | from typing import Any 4 | import cv2 5 | from reolinkapi.utils.util import threaded 6 | 7 | 8 | class RtspClient: 9 | """ 10 | This is a wrapper of the OpenCV VideoCapture method 11 | Inspiration from: 12 | - https://benhowell.github.io/guide/2015/03/09/opencv-and-web-cam-streaming 13 | - https://stackoverflow.com/questions/19846332/python-threading-inside-a-class 14 | - https://stackoverflow.com/questions/55828451/video-streaming-from-ip-camera-in-python-using-opencv-cv2-videocapture 15 | """ 16 | 17 | def __init__(self, ip: str, username: str, password: str, port: float = 554, profile: str = "main", 18 | use_udp: bool = True, callback: Any = None, **kwargs): 19 | """ 20 | RTSP client is used to retrieve frames from the camera in a stream 21 | 22 | :param ip: Camera IP 23 | :param username: Camera Username 24 | :param password: Camera User Password 25 | :param port: RTSP port 26 | :param profile: "main" or "sub" 27 | :param use_upd: True to use UDP, False to use TCP 28 | :param proxies: {"host": "localhost", "port": 8000} 29 | """ 30 | self.capture = None 31 | self.thread_cancelled = False 32 | self.callback = callback 33 | 34 | capture_options = 'rtsp_transport;' 35 | self.ip = ip 36 | self.username = username 37 | self.password = password 38 | self.port = port 39 | self.proxy = kwargs.get("proxies") 40 | self.url = f'rtsp://{self.username}:{self.password}@{self.ip}:{self.port}//h264Preview_01_{profile}' 41 | capture_options += 'udp' if use_udp else 'tcp' 42 | 43 | os.environ["OPENCV_FFMPEG_CAPTURE_OPTIONS"] = capture_options 44 | 45 | # opens the stream capture, but does not retrieve any frames yet. 46 | self._open_video_capture() 47 | 48 | def _open_video_capture(self): 49 | # To CAP_FFMPEG or not To ? 50 | self.capture = cv2.VideoCapture(self.url, cv2.CAP_FFMPEG) 51 | 52 | def _stream_blocking(self): 53 | while True: 54 | try: 55 | if self.capture.isOpened(): 56 | ret, frame = self.capture.read() 57 | if ret: 58 | yield frame 59 | else: 60 | print("stream closed") 61 | self.capture.release() 62 | return 63 | except Exception as e: 64 | print(e) 65 | self.capture.release() 66 | return 67 | 68 | @threaded 69 | def _stream_non_blocking(self): 70 | while not self.thread_cancelled: 71 | try: 72 | if self.capture.isOpened(): 73 | ret, frame = self.capture.read() 74 | if ret: 75 | self.callback(frame) 76 | else: 77 | print("stream is closed") 78 | self.stop_stream() 79 | except ThreadError as e: 80 | print(e) 81 | self.stop_stream() 82 | 83 | def stop_stream(self): 84 | self.capture.release() 85 | self.thread_cancelled = True 86 | 87 | def open_stream(self): 88 | """ 89 | Opens OpenCV Video stream and returns the result according to the OpenCV documentation 90 | https://docs.opencv.org/3.4/d8/dfe/classcv_1_1VideoCapture.html#a473055e77dd7faa4d26d686226b292c1 91 | """ 92 | 93 | # Reset the capture object 94 | if self.capture is None or not self.capture.isOpened(): 95 | self._open_video_capture() 96 | 97 | print("opening stream") 98 | 99 | if self.callback is None: 100 | return self._stream_blocking() 101 | else: 102 | # reset the thread status if the object was not re-created 103 | if not self.thread_cancelled: 104 | self.thread_cancelled = False 105 | return self._stream_non_blocking() 106 | -------------------------------------------------------------------------------- /reolinkapi/utils/util.py: -------------------------------------------------------------------------------- 1 | from threading import Thread 2 | 3 | 4 | def threaded(fn): 5 | def wrapper(*args, **kwargs): 6 | thread = Thread(target=fn, args=args, kwargs=kwargs) 7 | thread.daemon = True 8 | thread.start() 9 | return thread 10 | 11 | return wrapper 12 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | . -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import os 3 | import re 4 | import codecs 5 | from setuptools import setup, find_packages 6 | 7 | 8 | def read(*parts): 9 | with codecs.open(os.path.join(here, *parts), 'r') as fp: 10 | return fp.read() 11 | 12 | 13 | def find_version(*file_paths): 14 | version_file = read(*file_paths) 15 | version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]", version_file, re.M) 16 | if version_match: 17 | return version_match.group(1) 18 | raise RuntimeError("Unable to find version string.") 19 | 20 | 21 | # Package meta-data. 22 | NAME = 'reolinkapi' 23 | DESCRIPTION = 'Reolink Camera API client written in Python 3' 24 | URL = 'https://github.com/ReolinkCameraAPI/reolinkapipy' 25 | AUTHOR_EMAIL = 'alanoterblanche@gmail.com' 26 | AUTHOR = 'Benehiko' 27 | LICENSE = 'GPL-3.0' 28 | INSTALL_REQUIRES = [ 29 | 'setuptools', 30 | 'PySocks==1.7.1', 31 | 'PyYaml==6.0.2', 32 | 'requests>=2.32.3', 33 | ] 34 | EXTRAS_REQUIRE = { 35 | 'streaming': [ 36 | 'numpy==2.0.1', 37 | 'opencv-python==4.10.0.84', 38 | 'Pillow==10.4.0', 39 | ], 40 | } 41 | 42 | 43 | here = os.path.abspath(os.path.dirname(__file__)) 44 | # read the contents of your README file 45 | with open(os.path.join(here, 'README.md'), encoding='utf-8') as f: 46 | long_description = f.read() 47 | 48 | 49 | setup( 50 | name=NAME, 51 | python_requires='>=3.12.4', 52 | version=find_version('reolinkapi', '__init__.py'), 53 | description=DESCRIPTION, 54 | long_description=long_description, 55 | long_description_content_type='text/markdown', 56 | author=AUTHOR, 57 | author_email=AUTHOR_EMAIL, 58 | url=URL, 59 | license=LICENSE, 60 | install_requires=INSTALL_REQUIRES, 61 | packages=find_packages(exclude=['examples', 'tests']), 62 | extras_require=EXTRAS_REQUIRE 63 | ) 64 | -------------------------------------------------------------------------------- /tests/test_camera.py: -------------------------------------------------------------------------------- 1 | import os 2 | from configparser import RawConfigParser 3 | import unittest 4 | from reolinkapi import Camera 5 | 6 | 7 | def read_config(props_path: str) -> dict: 8 | """Reads in a properties file into variables. 9 | 10 | NB! this config file is kept out of commits with .gitignore. The structure of this file is such: 11 | # secrets.cfg 12 | [camera] 13 | ip={ip_address} 14 | username={username} 15 | password={password} 16 | """ 17 | config = RawConfigParser() 18 | assert os.path.exists(props_path), f"Path does not exist: {props_path}" 19 | config.read(props_path) 20 | return config 21 | 22 | 23 | class TestCamera(unittest.TestCase): 24 | 25 | @classmethod 26 | def setUpClass(cls) -> None: 27 | cls.config = read_config('../secrets.cfg') 28 | 29 | def setUp(self) -> None: 30 | self.cam = Camera(self.config.get('camera', 'ip'), self.config.get('camera', 'username'), 31 | self.config.get('camera', 'password')) 32 | 33 | def test_camera(self): 34 | """Test that camera connects and gets a token""" 35 | self.assertTrue(self.cam.ip == self.config.get('camera', 'ip')) 36 | self.assertTrue(self.cam.token != '') 37 | 38 | def test_snapshot(self): 39 | img = self.cam.get_snap() 40 | # write Pillow Image to file 41 | img.save('./tmp/snaps/camera.jpg') 42 | self.assertTrue(os.path.exists('./tmp/snaps/camera.jpg')) 43 | 44 | 45 | if __name__ == '__main__': 46 | unittest.main() 47 | --------------------------------------------------------------------------------