├── .gitignore ├── COPYING ├── README.md ├── config.toml.example ├── connectcam.py ├── install_service.sh └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | *~ 2 | .*.sw? 3 | __pycache__ 4 | *.toml 5 | -------------------------------------------------------------------------------- /COPYING: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ConnectCam - Minimialistic webcam manager for Prusa Connect 2 | =========================================================== 3 | Upgrading from a Prusa i3 MK3S+ to a Prusa MK4, I lost the great feature of 4 | connecting USB web cameras to the Raspberry Pi Zero I had running PrusaLink. 5 | This utility aims to be a solution to that problem. 6 | 7 | Simply take your old PrusaLink-Pi, give it a fresh installation of Raspberry Pi 8 | OS Lite, connect your webcam(s), install ConnectCam, and your cameras are back 9 | in Prusa Connect! 10 | 11 | Requirements 12 | ------------ 13 | * A Linux-based OS, like Raspberry Pi OS (ConnectCam is using 14 | [V4L2](https://en.wikipedia.org/wiki/Video4Linux) for basically everything) 15 | * Python (3.1+) 16 | * Python libraries: 17 | - On **Raspberry Pi OS**, these apt packages: 18 | `sudo apt install python3-toml python3-requests python3-v4l2` 19 | (All of these are installed by default in Raspberry Pi OS Lite.) 20 | - On **other** OS, these pip packages: 21 | `pip install toml requests v4l2-python3` 22 | 23 | Installation 24 | ------------ 25 | 1. Run `v4l2-ctl --list-devices` to find your connected cameras. 26 | **Example:** 27 | ``` 28 | UVC Camera (046d:0825) (usb-20980000.usb-1.1): 29 | /dev/video0 30 | /dev/video1 31 | /dev/media0 32 | 33 | Full HD webcam: Full HD webcam (usb-20980000.usb-1.3): 34 | /dev/video2 35 | /dev/video3 36 | /dev/media1 37 | ``` 38 | 2. Copy `config.toml.example` to `config.toml` and edit to your needs, adding 39 | your cameras to Prusa Connect to generate the needed tokens. 40 | **Example:** 41 | ``` 42 | refresh_rate = 10 # Seconds between each snapshot 43 | 44 | [[camera]] 45 | name = "Full HD webcam: Full HD webcam" 46 | token = "T0k3n0N3" 47 | 48 | [[camera]] 49 | name = "UVC Camera (046d:0825)" 50 | token = "T0k3n7W0" 51 | ``` 52 | (There are more settings available, see [config.toml.example]( 53 | https://github.com/firetech/ConnectCam/blob/master/config.toml.example) for 54 | more info.) 55 | 3. Run `./connectcam.py -vo config.toml` to make sure your config works. 56 | 4. Run `./install_service.sh config.toml` to install ConnectCam as a system 57 | service, starting automatically on boot. 58 | 5. Done! 59 | 60 | Limitations 61 | ----------- 62 | To keep the code small, and required libraries to the minimum, ConnectCam 63 | (currently) only supports MJPEG capable web cameras (unlike Prusa Link, which 64 | also supports YUYV). This works for my two cameras (Logitech C270 and Trust 65 | Trino HD). Experiments with YUYV just seemed to hang for some unknown reason 66 | when trying to speak to more than one camera at a time, so I gave that up quite 67 | quickly. 68 | 69 | Since I don't own any Pi Camera, I am unsure how this limitation affects them. 70 | Pull Requests are more than welcome, though! :) 71 | -------------------------------------------------------------------------------- /config.toml.example: -------------------------------------------------------------------------------- 1 | refresh_rate = 10 # Seconds between each snapshot 2 | 3 | # Example: 4 | [[camera]] 5 | name = "UVC Camera (046d:0825)" 6 | # ^ Required, find with `v4l2-ctl --list-devices`. 7 | # If specifying "dev" below, this can be whatever you want. 8 | token = "ToK3NFR0MPrUS4C0Nn3C7" 9 | # ^ Required, get from Prusa Connect camera page (Add new other camera) 10 | #fingerprint = "FinG3RPrIn7" 11 | # ^ Optional, will be generated automatically if not specified. 12 | # After first upload to a new camera, the fingerprint must stay the same. 13 | #dev = "/dev/video0" 14 | # ^ Optional, will be autodetected from name if not specified. 15 | # Recommended to not specify unless you have multiple identical cameras. 16 | #resolution = "1280x720" 17 | # ^ Optional, best resolution is used if not specified 18 | 19 | # [[camera]] 20 | # name = "camera2" 21 | # token = "token2" 22 | 23 | # [[camera]] 24 | # name = "camera3" 25 | # token = "token3" 26 | -------------------------------------------------------------------------------- /connectcam.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | # ConnectCam - Minimialistic webcam manager for Prusa Connect 4 | # Copyright (C) 2023 Joakim Tufvegren 5 | # 6 | # This program is free software; you can redistribute it and/or modify 7 | # it under the terms of the GNU General Public License as published by 8 | # the Free Software Foundation; either version 2 of the License, or 9 | # (at your option) any later version. 10 | # 11 | # This program is distributed in the hope that it will be useful, 12 | # but WITHOUT ANY WARRANTY; without even the implied warranty of 13 | # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | # GNU General Public License for more details. 15 | # 16 | # You should have received a copy of the GNU General Public License along 17 | # with this program; if not, write to the Free Software Foundation, Inc., 18 | # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 19 | 20 | import os 21 | import re 22 | import sys 23 | import mmap 24 | import time 25 | import v4l2 26 | import toml 27 | import errno 28 | import fcntl 29 | import base64 30 | import select 31 | import signal 32 | import requests 33 | import threading 34 | 35 | CAMERA_WAIT_TIMEOUT = 10 36 | DEFAULT_URL = 'https://connect.prusa3d.com/c/snapshot' 37 | 38 | verbose = False 39 | 40 | 41 | def verbose_print(*args, **kwargs): 42 | if verbose: 43 | print(*args, **kwargs) 44 | 45 | 46 | def load_config(config_file = None): 47 | if config_file is None: 48 | path = os.path.dirname(os.path.realpath(__file__)) 49 | config_file = os.path.join(path, 'config.toml') 50 | verbose_print("Loading '{}'...".format(config_file)) 51 | config = toml.load(config_file) 52 | if not 'camera' in config or len(config['camera']) < 1: 53 | if 'cameras' in config and len(config['cameras']) >= 1: 54 | config['camera'] = config['cameras'] 55 | else: 56 | raise ValueError("No cameras in config!") 57 | if not 'refresh_rate' in config: 58 | config['refresh_rate'] = 30 59 | return config 60 | 61 | 62 | def get_device(camera_name): 63 | dev = None 64 | for f in os.listdir("/sys/class/video4linux"): 65 | real_file = os.path.realpath( 66 | '/sys/class/video4linux/{}/name'.format(f)) 67 | with open(real_file, "rt") as name_file: 68 | name = name_file.read().rstrip() 69 | if camera_name in name: 70 | if dev is None or f < dev: 71 | dev = f 72 | if dev is not None: 73 | dev = '/dev/{}'.format(dev) 74 | return dev 75 | 76 | 77 | def init(config = {}, vd = None): 78 | if vd is None: 79 | if 'dev' in config: 80 | dev = config['dev'] 81 | else: 82 | dev = get_device(config['name']) 83 | if dev is None: 84 | raise Exception("Cannot find device for '{}'".format( 85 | config['name'])) 86 | vd = open(dev, 'rb+', buffering=0) 87 | 88 | verbose_print("Initializing '{}' ({})".format(config['name'], vd.name)) 89 | # Check video capture capability 90 | cp = v4l2.v4l2_capability() 91 | fcntl.ioctl(vd, v4l2.VIDIOC_QUERYCAP, cp) 92 | if v4l2.V4L2_CAP_VIDEO_CAPTURE & cp.capabilities == 0: 93 | raise ValueError 94 | 95 | # Set specified (or max) resolution 96 | config_res = config['resolution'] if 'resolution' in config else None 97 | if config_res is not None: 98 | c_width, c_height = map(int, config_res.split('x')) 99 | config_res_found = False 100 | fmt = v4l2.v4l2_format() 101 | fmt.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE 102 | fmt.fmt.pix.pixelformat = v4l2.V4L2_PIX_FMT_MJPEG 103 | max_pixels = 0 104 | size = v4l2.v4l2_frmsizeenum() 105 | size.pixel_format = fmt.fmt.pix.pixelformat 106 | size.index = 0 107 | while True: 108 | try: 109 | fcntl.ioctl(vd, v4l2.VIDIOC_ENUM_FRAMESIZES, size) 110 | except OSError: 111 | break 112 | if size.type == v4l2.V4L2_FRMSIZE_TYPE_DISCRETE: 113 | width = size.discrete.width 114 | height = size.discrete.height 115 | curr_pixels = width * height 116 | match = (config_res is not None and 117 | c_width == width and 118 | c_height == height) 119 | if match or curr_pixels >= max_pixels: 120 | fmt.fmt.pix.width = width 121 | fmt.fmt.pix.height = height 122 | max_pixels = curr_pixels 123 | if match: 124 | config_res_found = True 125 | break 126 | size.index += 1 127 | if config_res is not None and not config_res_found: 128 | print("Warning: Resolution '{}' not supported by '{}', " \ 129 | "using max instead".format( 130 | config_res, 131 | config['name']), 132 | file=sys.stderr) 133 | verbose_print("Setting resolution {}x{}".format( 134 | fmt.fmt.pix.width, 135 | fmt.fmt.pix.height)) 136 | fcntl.ioctl(vd, v4l2.VIDIOC_S_FMT, fmt) 137 | 138 | # Request and set up capture buffer 139 | req = v4l2.v4l2_requestbuffers() 140 | req.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE 141 | req.memory = v4l2.V4L2_MEMORY_MMAP 142 | req.count = 1 143 | fcntl.ioctl(vd, v4l2.VIDIOC_REQBUFS, req) 144 | buf = v4l2.v4l2_buffer() 145 | buf.type = v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE 146 | buf.memory = v4l2.V4L2_MEMORY_MMAP 147 | buf.index = 0 148 | fcntl.ioctl(vd, v4l2.VIDIOC_QUERYBUF, buf) 149 | mm = mmap.mmap(vd.fileno(), 150 | buf.length, 151 | mmap.MAP_SHARED, 152 | mmap.PROT_READ | mmap.PROT_WRITE, 153 | offset=buf.m.offset) 154 | 155 | # Toggle streaming to work around some intermittent initialization issues 156 | fcntl.ioctl(vd, v4l2.VIDIOC_STREAMON, 157 | v4l2.v4l2_buf_type(v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)) 158 | fcntl.ioctl(vd, v4l2.VIDIOC_STREAMOFF, 159 | v4l2.v4l2_buf_type(v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)) 160 | 161 | # Start streaming 162 | fcntl.ioctl(vd, v4l2.VIDIOC_STREAMON, 163 | v4l2.v4l2_buf_type(v4l2.V4L2_BUF_TYPE_VIDEO_CAPTURE)) 164 | 165 | return vd, buf, mm 166 | 167 | 168 | def capture(vd, buf, mm, config): 169 | # Grab a frame 170 | fcntl.ioctl(vd, v4l2.VIDIOC_QBUF, buf) 171 | events, *_ = select.select((vd,), (), (), CAMERA_WAIT_TIMEOUT) 172 | if not events: 173 | raise TimeoutError("Timeout getting frame for '{}'".format( 174 | config['name'])) 175 | fcntl.ioctl(vd, v4l2.VIDIOC_DQBUF, buf) 176 | verbose_print("Captured frame for '{}'".format(config['name'])) 177 | # At this point, the `mm` mmap contains the frame data 178 | 179 | 180 | # Adapted from https://stackoverflow.com/a/29838711 181 | class MMapStreamer(object): 182 | def __init__(self, mmap, total, block=65535): 183 | self.mmap = mmap 184 | self.remaining = total 185 | self.block = block 186 | 187 | # So that requests doesn't try to chunk the upload but will instead 188 | # stream it: 189 | self.len = total 190 | 191 | def read(self, amount=-1): 192 | if self.remaining <= 0: 193 | return b'' 194 | if amount < 0: 195 | amount = self.total 196 | data = self.mmap.read(min(self.block, self.remaining, amount)) 197 | self.remaining -= len(data) 198 | return data 199 | 200 | 201 | def upload(buf, mm, config): 202 | # Send frame to Prusa Connect 203 | response = requests.put( 204 | config['url'], 205 | headers={ 206 | 'Content-Type': 'image/jpg', 207 | 'Fingerprint': config['fingerprint'], 208 | 'Token': config['token'], 209 | }, 210 | data=MMapStreamer(mm, buf.bytesused) 211 | ) 212 | mm.seek(0) 213 | response.raise_for_status() 214 | verbose_print("Updated frame for '{}'".format(config['name'])) 215 | 216 | 217 | stop = threading.Event() 218 | def capture_thread(vd, buf, mm, config, rate = 30): 219 | try: 220 | while not stop.wait(timeout=rate): 221 | try: 222 | if vd is None: 223 | vd, buf, mm = init(config) 224 | capture(vd, buf, mm, config) 225 | except Exception as err: 226 | print("Error capturing frame for '{}': {}".format( 227 | config['name'], 228 | err 229 | ), 230 | file=sys.stderr) 231 | if vd is not None: 232 | vd.close() 233 | vd = None 234 | if mm is not None: 235 | mm.close() 236 | mm = None 237 | buf = None 238 | 239 | if vd is not None: 240 | try: 241 | upload(buf, mm, config) 242 | except Exception as err: 243 | print("Error updating frame for '{}': {}".format( 244 | config['name'], 245 | err 246 | ), 247 | file=sys.stderr) 248 | finally: 249 | if vd is not None: 250 | vd.close() 251 | if mm is not None: 252 | mm.close() 253 | 254 | 255 | def _signal_handler(sig, frame): 256 | verbose_print('Exiting...') 257 | stop.set() 258 | 259 | 260 | def _init_error(fatal, msg): 261 | if fatal: 262 | raise RuntimeError(msg) 263 | else: 264 | print("Warning: {}".format(msg), file=sys.stderr) 265 | 266 | 267 | if __name__ == '__main__': 268 | import argparse 269 | 270 | parser = argparse.ArgumentParser( 271 | description='Send webcam snapshots to Prusa Connect') 272 | parser.add_argument('-v', '--verbose', 273 | action='store_true', 274 | help='Output diagnostic info') 275 | parser.add_argument('-o', '--oneshot', 276 | action='store_true', 277 | help='Only send one shapshot per camera, then exit') 278 | parser.add_argument('config', 279 | nargs='?', 280 | help='Config file to use (default config.toml in directory of ' \ 281 | 'script)') 282 | 283 | args = parser.parse_args() 284 | 285 | verbose = args.verbose 286 | config = load_config(args.config) 287 | rate = config['refresh_rate'] 288 | threads = [] 289 | for cam_config in config['camera']: 290 | if not 'name' in cam_config: 291 | raise ValueError("Camera config missing name!") 292 | if not 'token' in cam_config: 293 | raise ValueError("Camera '{}' missing token!".format( 294 | cam_config['name'])) 295 | if not 'fingerprint' in cam_config: 296 | b64 = base64.b64encode(bytes(cam_config['name'], 'utf8')) 297 | fprint = b64.decode('ascii').ljust(16, '.') 298 | cam_config['fingerprint'] = fprint[0:64] 299 | if not 'url' in cam_config: 300 | cam_config['url'] = DEFAULT_URL 301 | vd = None 302 | buf = None 303 | mm = None 304 | try: 305 | vd, buf, mm = init(cam_config) 306 | except Exception as e: 307 | _init_error(args.oneshot, "Failed to initialize '{}'".format( 308 | cam_config['name'])) 309 | 310 | if vd is not None: 311 | try: 312 | capture(vd, buf, mm, cam_config) 313 | if args.oneshot: 314 | vd.close() 315 | except Exception as e: 316 | _init_error(args.oneshot, "Error capturing frame for '{}': " \ 317 | "{}".format( 318 | config['name'], 319 | err 320 | )) 321 | try: 322 | upload(buf, mm, cam_config) 323 | if args.oneshot: 324 | mm.close() 325 | except Exception as e: 326 | _init_error(args.oneshot, "Error updating frame for '{}': " \ 327 | "{}".format( 328 | config['name'], 329 | err 330 | )) 331 | 332 | if not args.oneshot: 333 | threads.append(threading.Thread( 334 | target=capture_thread, 335 | args=(vd, buf, mm, cam_config, rate))) 336 | 337 | if not args.oneshot: 338 | signal.signal(signal.SIGINT, _signal_handler) 339 | signal.signal(signal.SIGTERM, _signal_handler) 340 | 341 | for t in threads: 342 | t.start() 343 | 344 | for t in threads: 345 | t.join() 346 | -------------------------------------------------------------------------------- /install_service.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh -e 2 | 3 | [ $(id -u) != "0" ] || { 4 | echo "Don't run this as root!" >&2 5 | exit 1 6 | } 7 | 8 | [ -x "$(which systemctl)" ] || { 9 | echo "systemctl not found. Are you not using Systemd?" >&2 10 | exit 1 11 | } 12 | 13 | dir=$(dirname $(realpath $0)) 14 | config= 15 | [ -z $1 ] || { 16 | config=$(realpath $1) 17 | } 18 | 19 | echo "# Installing service file for ConnectCam..." 20 | 21 | sudo tee /etc/systemd/system/connectcam.service > /dev/null << EOF 22 | [Unit] 23 | Description=Minimalistic webcam manager for Prusa Connect 24 | After=network-online.target 25 | StartLimitInterval=200 26 | StartLimitBurst=5 27 | 28 | [Service] 29 | User=$(id -u) 30 | Group=$(id -g) 31 | WorkingDirectory=$dir 32 | ExecStart=/usr/bin/python3 $dir/connectcam.py $config 33 | Restart=always 34 | RestartSec=30 35 | 36 | [Install] 37 | WantedBy=multi-user.target 38 | EOF 39 | 40 | sudo systemctl daemon-reload 41 | sudo systemctl enable connectcam.service 42 | 43 | echo "# Starting ConnectCam service..." 44 | sudo systemctl start connectcam.service 45 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests>=2.25.1 2 | toml>=0.10.1 3 | v4l2-python3>=0.3.2 4 | --------------------------------------------------------------------------------