reolinkcameraapi / reolinkapipy Goto Github PK
View Code? Open in Web Editor NEWReolink Camera API written in Python 3.6
License: GNU General Public License v3.0
Reolink Camera API written in Python 3.6
License: GNU General Public License v3.0
Is there anyway to control PTZ with the API? I am coming from Foscam which has a super rich rest api where you can control motion detection, alarm settings, PTZ, and move the camera to specific positions, etc. thanks
Hello!
I'm a newbie about Reolink Technologies but i try to connect with my Cam by using these APIs.
I tried to call cam.get_alarm_motion() but it's not working.
This is my code:
import datetime
import reolinkapi
if __name__ == "__main__":
cam = reolinkapi.Camera("192.168.1.2", "***", "***", defer_login=False)
cam.get_alarm_motion()
I kept secret my username and my password but i passed them to Camera object.
This is the response:
Login success [{'cmd': 'Unknown', 'code': 1, 'error': {'detail': 'not support', 'rspCode': -9}}]
Any suggestions? Thank you so much!
Hello,
is it possible to read an alert from a RLC-520A that has been triggered by a person/car detection? I mean, to configure the camera with the manufacturer app or webapp but be polling for detections of the AI camera's feature.
Thanks.
Hi all,
I just started playing with this.
I'm just trying to get some consistent images from time to time.
I'm using the streaming_video.py from examples folder but I'm getting a weird behaviour:
[h264 @ 0x2bb0580] error while decoding MB 42 54, bytestream -5
[h264 @ 0x2bdf480] error while decoding MB 103 80, bytestream -15
[h264 @ 0x2bb1780] error while decoding MB 87 36, bytestream -5
[h264 @ 0x2bdf480] error while decoding MB 8 32, bytestream -11
[h264 @ 0x2bb1780] error while decoding MB 31 18, bytestream -5
[h264 @ 0x2bb0580] error while decoding MB 41 75, bytestream -9
Also the image is rendered broken sometimes.
How can I solve this?
7 def non_blocking():
8 print("calling non-blocking")
9 def inner_callback(img):
10 now = int(datetime.datetime.now().timestamp())
11 cv2.imwrite(f"/path/{now}.png",
12 img)
13 cv2.destroyAllWindows()
Regards,
C.
I implemented a zoom command in a separate project some time ago. I would open a PR with the command in the next days, if there are no objections.
Hi,
Running on windows, python3.9.1 I got an issue when using get_snap. I dont have the error message handy, but it produced error on random.choices function. I changed the AppData\Roaming\Python\Python39\site-packages\reolinkapi\mixins\stream.py file:
#from random import random
import random
And now its downloading snapshot.
Thought it might be good to have a central place for the Reolink API documentation.
https://docs.google.com/document/d/1jQde_FZ2BywT8V0VQJpnPTKuV35msg9s4Nz8Xpu_usc/edit?usp=sharing
Any updated versions can also be added to this issue.
On line 39 of stream.py, the rs parameter is set as follows:
'rs': ''.join(random.choices(string.ascii_uppercase + string.digits, k=10)),
However, the import statement on line 2 is
from random import random
With this import statement, the symbol random
refers to the function rather than the library, and it is the library which has the choices function.
This problem causes a crash with AttributeError: 'builtin_function_or_method' object has no attribute 'choices'
when get_snap is called.
For who is interested:
https://gist.github.com/velzend/895c18d533b3992f3a0cc128f27c0894
Would it be easier to keep requirements.txt
for a while since pipfile
does not seem to widespread known?
The get_general_system
function does not look right, is it correct?.
https://github.com/ReolinkCameraAPI/reolink-python-api/blob/984747e1db3e8f8be4d1ea55b8faa2f96eea1b39/api/system.py#L3
Also cannot find any example responses for it #27
This is a pretty minor feature, but when I was working with this library I just needed the API interface without any of the image processing. This made it a bit overkill to install the numpy, opencv, and pillow dependencies. It would be nice if these were configured as optional dependencies https://setuptools.readthedocs.io/en/latest/userguide/dependency_management.html#optional-dependencies or there was an easy way to leave them out.
The main change other then to setup.py would be to make reolinkapi/mixins/stream.py stub itself out if the dependencies are not installed and return exceptions if invoked. Possibly like:
try:
import opencv
# Normal implementation
except ImportError:
# Stubbed out implementation
Hi, I tried to login using the following code:
from reolinkapi.camera import Camera
ip: str = '127.0.0.1'
username: str = "admin"
password: str = "12345"
https: bool = True
defer_login: bool = False
profile: str = "main"
c = Camera(ip, username, password, https, defer_login, profile)
c.login()
and I get the following error
[
{
"cmd" : "Login",
"code" : 1,
"error" : {
"detail" : "param error",
"rspCode" : -4
}
}
]
I am wondering if RLC-510a camera is supported, I don't see it in this issue #35
Hi,
Nice package! Just wondering if you run into any limitations/issues with the API so far. I'm looking in to getting a wifi/ip camera and would like to control all it's parameters.
Did you run into the same issue as here?
https://ipcamtalk.com/threads/control-reolink-rlc-423-with-api.16815/
Thanks
Hi Benehiko,
first of all thank you for working on this huge topic, I really miss an official API from Reolink to my cams!
This one is a feature request:
I would like to relate the sending of alert mails with my presence at home and the time of day.
So e.g. when my "smart home" detects that I left home it shall send a command to my Reolink cams to activate the sending of mails in case of alerts.
Sending of mails all day long is sometimes very annoying when we are around in the garden because we receive a lot of mails every few minutes.
I am using a Reolink Argus 2 and two RLC-422W so if you need a beta testers for new code feel free to contact me (unfortunalety I am no coder myself...).
Greetz
André
Response data missing for reboot_camera
The example responses are incomplete and requires some review. It seems mostly the SET
request responses are missing.
For those out there that are using the library, would you be so kind as to mention which Reolink camera's you are using the library with.
Just paste the information on this issue and it will be added to the README.md file
Hi,
I'm using cam.get_file( .. ) to download from cam.get_motion_files(start=start, end=end, streamtype=streamtype) .
It works great, but sometimes it seems to just hang and never finish download. At that point it also looks like the Reolink android app has issues connecting to camera, at least the settings page. If I manually kill (ctrl C!) my program and start over again it works to download and back to normal.
Is it possible to add a timeout function to get_file operation? Just kill it if it does not work after N seconds..
Camera: RLC 410W 4MP
Thanks! love the api
When ever I call the Get_snap or Open_video_stream functions I keep getting these errors. I can receive data but not any video
Here is my code:
from reolinkapi import Camera
import time
ip = "192.168.0.13"
user = "admin"
password ="FC98**"
c = Camera(ip, user, password, True, proxy={"http": "socks5://192.168.0.13:8000/"})
#c = Camera(ip, user, password, True, True, proxy={"http":"192.168.0.13"})
time.sleep(1)
#c.get_snap()
#c.logout()
print(c.get_general_system())
c.get_snap()
#c.open_video_stream
g = c.get_snap()
Here is the error im getting:
Could not get Image data
HTTPSConnectionPool(host='192.168.0.13', port=443): Max retries exceeded with url: /cgi-bin/api.cgi?cmd=Snap&channel=0&rs=U60T7YLGDC&user=admin&password=FC98%2A%2A (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)')))
Traceback (most recent call last):
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
httplib_response = self._make_request(
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 386, in _make_request
self._validate_conn(conn)
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 1042, in validate_conn
conn.connect()
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connection.py", line 414, in connect
self.sock = ssl_wrap_socket(
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\ssl.py", line 453, in ssl_wrap_socket
ssl_sock = ssl_wrap_socket_impl(sock, context, tls_in_tls)
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\ssl.py", line 495, in _ssl_wrap_socket_impl
return ssl_context.wrap_socket(sock)
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 500, in wrap_socket
return self.sslsocket_class._create(
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1040, in _create
self.do_handshake()
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\ssl.py", line 1309, in do_handshake
self._sslobj.do_handshake()
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 489, in send
resp = conn.urlopen(
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\connectionpool.py", line 787, in urlopen
retries = retries.increment(
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\urllib3\util\retry.py", line 592, in increment
File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\sessions.py", line 701, in send
r = adapter.send(request, **kwargs) File "C:\Users\Rhys Brown\AppData\Local\Programs\Python\Python39\lib\site-packages\requests\adapters.py", line 563, in send
raise SSLError(e, request=request)
requests.exceptions.SSLError: HTTPSConnectionPool(host='192.168.0.13', port=443): Max retries exceeded with url: /cgi-bin/api.cgi?cmd=Snap&channel=0&rs=U60T7YLGDC&user=admin&password=FC98%2A%2A (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1122)')))
PS C:\Users\Rhys Brown\Documents\GitHub\Farming_AI>
Not sure how the PtzApi response data should look like. I guess they only respond with some "status":"ok" type json struct?
https://github.com/ReolinkCameraAPI/reolink-python-api/blob/master/api/ptz.py
Hi! Thanks for building this library out. I'd love to use it in some upcoming projects.
I thought I'd point out that the structure of this repo is such that installing as a python library (e.g., pip install reolink-api
) results in a mixed bag of libraries (api, utils, Camera, etc...) that don't seem to be able to communicate with each other too well. For instance, running the following after a fresh install:
from Camera import Camera
results in a ModuleNotFoundError
, as the util
file isn't found and thus can't import from util import threaded
.
If the structure of the library were to be changed to something like my suggestion below, it would likely function more like a regular python library and thus would avoid the problem of modules not being found:
(From the project root)
reolinkapi (this is currently the 'api' folder)
- Camera.py
- ConfigHandler.py
- RtspClient.py
- resthandle.py
- util.py
- (everything else that's already in the `api` folder)
Also, in setup.py
, changing the NAME
variable to reolink_api
or reolinkapi
(matching the directory name change above), as having a -
in a package name in Python can result in unexpected issues when performing a standard import.
Anyway, just thought I'd bring this up in case your goal was for this project to behave more like a "standard" Python library. I'm certain there are other ways to maintain a repo than what I've suggested, so I accept that I might be wrong in my assumptions about your project. That said, if you'd like some help in moving your project in the direction I've suggested I'd be happy to help out.
Cheers,
Thanks for the answer on a previous question. My issue was solved by upgrading the firmware which surprised me. I am now trying a Reolink camera which appears to be far better than the Amcrest camera.
I verified that I can grab a frame from the camera. Using Chrome browser:
http://192.168.1.122/cgi-bin/api.cgi?cmd=Snap&channel=0&user=admin&password=myPassword
If I refresh the browser - I get updated frames as expected. However,
I tried using opencv VideoCapture - oddly (different behavior from Amcrest) - it will get 1 frame but does not return frames on subsequent calls. (my program worked well with the Amcrest cameras - the Reolink has better image quality so I'm switching cameras.) So I am looking at your API.
import RtspClient
r = RtspClient.RtspClient('192.168.1.122', 'admin', myPassword)
r.connect()
<socks.socksocket fd=10, family=AddressFamily.AF_INET, type=SocketKind.SOCK_STREAM, proto=0, laddr=('192.168.1.110', 46678), raddr=('192.168.1.122', 554)>
r.preview()
'NoneType' object has no attribute 'send'
Traceback (most recent call last):
File "", line 1, in
File "/media/home/jay/projects/ReolinkCameraAPI/RtspClient.py", line 78, in preview
cv2.imshow(win_name, self.get_frame())
cv2.error: OpenCV(4.2.0) /io/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'
bytes = r.get_frame()
'NoneType' object has no attribute 'send'
I'm a relative novice with RESTful APIs so this is probably a pretty simple issue. Looks like I have an object = None someplace
Seems the NetworkApi has two methods that have no mapping to an example response.
https://github.com/ReolinkCameraAPI/reolink-python-api/blob/984747e1db3e8f8be4d1ea55b8faa2f96eea1b39/api/network.py#L47
Most single actions have a very similar structure, for example set_wifi(..)
, get_link_local(...)
etc. This could be refactored using a generic method like this:
class APIHandler:
def _execute_command(self, command, data):
"""
Send a POST request to the IP camera with given JSON body and
:param command: name of the command to send
:param data: object to send to the camera
:return: response as python object
"""
try:
if self.token is None:
raise ValueError("Login first")
response = Request.post(self.url, data=data, params={"cmd": command, "token": self.token})
return json.loads(response.text)
except Exception as e:
print(f"Command {command} failed: {e}")
raise
def set_wifi(self, ssid, password) -> json or None:
body = [{"cmd": "SetWifi", "action": 0, "param": {
"Wifi": {
"ssid": ssid,
"password": password
}}}]
return self._execute_command('SetWifi', body)
def get_link_local(self):
"""
Get General network data
This includes IP address, Device mac, Gateway and DNS
:return:
"""
body = [{"cmd": "GetLocalLink", "action": 1, "param": {}}]
return self._execute_command('GetLocalLink', body)
That's just a simple draft. This or similar refactoring could shorten the APIHandler.py
file a lot and make the code much more readable.
If such refactoring is appreciated, I'm happy to create a PR.
What would you recommend to set up a way to control the camera remotely, so that this code doesn't have to run on the same network as the camera?
Will need to look into moving the RTSP stream to its own Mixin. Currently it is in the RecordingMixin, but since it does not perform any recording it seems a bit out of place. Also the get_snap
function.
Will also have to look into getting rid of the opencv dependency inside the library.
As a title can be great to enable or disable notifications when i go away from home
Dear developers,
Thank you for all the efforts on this - really helpful.
I am wondering if you could help me sove the following error (IPs make it impossible to make it reproducable).
I am able to initialize the camera with cam = Camera(cam_ip, cam_settings.user, cam_settings.pw)
. However the login only works now and then - the cam.token will remain empty.
Oddly enough the Ping (on the IP address works fine and the Reolink App is able to connect as well via the IP address)
When calling cam.get_snap() I get the following error:
File "C:/Projekte/cam_api_calls/main.py", line 35, in fetch_all_images
im = cam.get_snap()
File "C:\Users\ge37mof\Anaconda3\envs\cam_fetcher\lib\site-packages\reolinkapi\mixins\stream.py", line 48, in get_snap
return open_image(BytesIO(response.content))
File "C:\Users\ge37mof\Anaconda3\envs\cam_fetcher\lib\site-packages\PIL\Image.py", line 2943, in open
raise UnidentifiedImageError(
PIL.UnidentifiedImageError: cannot identify image file <_io.BytesIO object at 0x0000016B17CA0D10>
Could you give me some hints on how to proceed on this?
thanks in advance
Hi, i get an Error when i start camera.py
`pi@raspberrypi:~/tflite/examples $ python3 mytest.py
Login success
Getting information [{'cmd': 'GetDevInfo', 'code': 0, 'value': {'DevInfo': {'B485': 0, 'IOInputNum': 0, 'IOOutputNum': 0, 'audioNum': 1, 'buildDay': 'build 20103104', 'cfgVer': 'v3.0.0.0', 'channelNum': 1, 'detail': 'IPC_51516M5MS10E1W31100000001', 'diskNum': 1, 'firmVer': 'v3.0.0.116_20103104', 'frameworkVer': 1, 'hardVer': 'IPC_51516M5M', 'model': 'RLC-511W', 'name': 'Pond', 'pakSuffix': 'pak,paks', 'serial': '00000000065536', 'type': 'IPC', 'wifi': 1}}}]
Error connecting to SOCKS5 proxy 127.0.0.1:8000: [Errno 111] Connection refused
Error connecting to SOCKS5 proxy 127.0.0.1:8000: [Errno 111] Connection refused
'NoneType' object has no attribute 'send'
Traceback (most recent call last):
File "/home/pi/.local/lib/python3.7/site-packages/api/recording.py", line 44, in open_video_stream
rtsp_client.preview()
File "/home/pi/.local/lib/python3.7/site-packages/RtspClient.py", line 78, in preview
cv2.imshow(win_name, self.get_frame())
cv2.error: OpenCV(4.4.0) /tmp/pip-wheel-2l8ccy47/opencv-python/opencv/modules/highgui/src/window.cpp:376: error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'imshow'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "mytest.py", line 5, in
c.open_video_stream()
File "/home/pi/.local/lib/python3.7/site-packages/api/recording.py", line 44, in open_video_stream
rtsp_client.preview()
File "/home/pi/.local/lib/python3.7/site-packages/RtspClient.py", line 34, in exit
self.sockt.close()
AttributeError: 'NoneType' object has no attribute 'close'
Hi guys,
Thank so much to those who have been contributing to this repository. I didn't think there would be so much interest in this project with people starring the project and creating PRs. I must admit I haven't been the best at maintaining this project since I have also had some time constraints and restrictions to the very devices I built this library for.
So here it goes, maybe it might be best to start a discord server with all the people who have contributed to this repository. This will make life easier in talking about how to move forward with this library (as it's still very small and incomplete). The discord server can also be a central repository for supported cameras, test reports from users and a channel for users' who aren't necessarily "code savvy" to be able to share their thoughts.
My other request is - since I have no access whatsoever to a reolink device currently, my development on this project has also basically ceased. An alternative is to have a testing camera which can be tested on - something running behind a proxy which the current contributors (or just I for now idk) can use to test this library on and expand on it.
I am open to suggestions and would really like to hear your thoughts :)
Again thank you!
Hello, I read cameras that uses special clients that not have a web client are not supported by this project. It would be very difficult to add suport to them? the API is completely different?
Thank you!
The ImageApi has no example response.
https://github.com/ReolinkCameraAPI/reolink-python-api/blob/master/api/image.py
Thanks for making your project public. I want to set up a system where I am taking snapshots and sending the images into some computer vision models. I started with Amcrest cameras and it was taking 1-2 seconds to get a frame from the camera - far too slow. What has been your experience with the Reolink camera and your API? Have you measured a frame-rate of grabbing images? (I tried two methods - HTTP and OpenCV VideoCapture). Thanks for responding to my question
I am trying to configure this API for Reaolink battery-powered camera. I have enabled port forwarding for the camera but still getting requests.exceptions.ConnectionError: HTTPConnectionPool(host=ip, port=port): Max retries exceeded with url: /cgi-bin/api.cgi?cmd=Login&token=null
error.
I there any way I can connect to the camera using UID of reolink instead of IP address?
Hi Benehiko,
I think it would be nice to have some kind of dependency management in this project. Currently, these packages are used:
Pillow
pyyaml
requests
Personally, I prefer pipenv for this task.
Want to implement a non-blocking video streaming function.
The easiest might be to implement using OpenCV but it might be too much overhead for this small library.
Before I submit the PR, do you have any objections to publishing this great work to PyPi as a package?
How can I start/stop a recording manually? And how can I trigger the audio alarm or Flashlight manually? What are the commands for this? Is there a complete list of all Python commands?
Thanks
Jo
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.