我正在尝试连接到安装在停车场的海康视觉摄像头来监控入口和存在。为了获取事件数据,我使用[hikvisionapi][1]。
这是我连接相机的方法:
from hikvisionapi import AsyncClient
cam = AsyncClient('http://XXX.XX.XXX.X:XXXX', 'xxxxx', 'XXXXXX')
async for event in cam.Event.notification.alertStream(method='get', type='stream', timeout=None):
if(event['EventNotificationAlert']['eventType'] == 'ANPR'):
print(event['EventNotificationAlert'])
这样,我就能够获取事件数据,但是在检测到第一个“ANPR”事件后,我收到“IndexError”。我尝试过其他方法,例如:
from hikvisionapi import AsyncClient
import logging
import time
cam = AsyncClient('http://XXX.XX.XXX.X:XXXX', 'xxxxx', 'XXXXXX')
while True:
try:
async for event in cam.Event.notification.alertStream(method='get', type='stream', timeout=None):
if event['EventNotificationAlert']['eventType'] == 'ANPR':
logging.info(event['EventNotificationAlert'])
time.sleep(1) # Add a delay to avoid overloading the system
except Exception as e:
logging.error(e)
我也尝试过:
from hikvisionapi import AsyncClient
if __name__ == '__main__':
cam = AsyncClient('http://XXX.XX.XXX.X:XXXX', 'xxxxxxx', 'XXXXX')
while True:
async for event in cam.Event.notification.alertStream(method='get', type='stream', timeout=None):
if 'EventNotificationAlert' in event and 'eventType' in event['EventNotificationAlert']:
if event['EventNotificationAlert']['eventType'] == 'ANPR':
logging.info(event['EventNotificationAlert']['ANPR'])
else:
logging.info(event['EventNotificationAlert'])
time.sleep(1)
else:
print('No events')
time.sleep(1)
使用无限 while 循环的所有其他方式,我得到第一个 ANPR 事件,但随后它没有检测到任何更多事件。代码不会崩溃,它继续运行,但没有检测到更多事件。
我将不胜感激任何帮助。
所以我的问题是,如何保持与流的连接并忽略任何错误。 [1]:https://pypi.org/project/hikvisionapi/
from http.server import BaseHTTPRequestHandler, HTTPServer
import xml.etree.ElementTree as ET
import re
import csv
import os
class ANPRRequestHandler(BaseHTTPRequestHandler):
def do_POST(self):
# Read the body of the request
content_length = int(self.headers['Content-Length'])
post_data = self.rfile.read(content_length)
# Split the payload into parts
parts = post_data.split(b'--boundary\r\n')[1:-1] # Exclude the first and last split elements
for part in parts:
headers, body = part.split(b'\r\n\r\n', 1)
body = body.strip()
# Process XML part
if b'anpr.xml' in headers:
self.process_xml(body)
# Process image part
elif b'.jpg' in headers:
filename = re.findall(rb'filename="([^"]+)"', headers)[0].decode()
self.save_image(body, filename)
# Send response
self.send_response(200)
self.end_headers()
self.wfile.write("Received and processed ANPR event".encode('utf-8'))
def append_to_csv(self, license_plate):
# CSV file path
csv_file = 'license_plates.csv'
# Check if the CSV file exists
file_exists = os.path.isfile(csv_file)
# Open the file in append mode
with open(csv_file, mode='a', newline='') as file:
writer = csv.writer(file)
# If the file does not exist, write the header
if not file_exists:
writer.writerow(['License Plate'])
# Write the license plate data
writer.writerow([license_plate])
def process_xml(self, xml_data):
# Parse XML data
#print(xml_data)
try:
root = ET.fromstring(xml_data)
# Find the license plate element
# Update XPath to include namespace prefix
namespaces = {'ns': 'http://www.hikvision.com/ver20/XMLSchema'}
# Find the license plate element
# Update XPath to include namespace prefix
license_plate_element = root.find('.//ns:ANPR/ns:licensePlate', namespaces)
if license_plate_element is not None and license_plate_element.text:
license_plate = license_plate_element.text.strip()
print(f"License Plate: {license_plate}")
self.append_to_csv(license_plate)
else:
print("License plate not found in XML.")
except ET.ParseError as e:
print(f"Error parsing XML: {e}")
def save_image(self, image_data, image_name):
# Save the image
with open(image_name, 'wb') as image_file:
image_file.write(image_data)
print(f"Saved image {image_name}")
def run(server_class=HTTPServer, handler_class=ANPRRequestHandler, port=8888):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print(f"Starting httpd on port {port}...")
httpd.serve_forever()
if __name__ == '__main__':
run()
and this is the wireshark data:
POST / HTTP/1.1
Content-Type: multipart/form-data; boundary=boundary
Host: 10.199.13.29:8888
Connection: close
Content-Length: 525605
--boundary
Content-Disposition: form-data; name="anpr.xml"; filename="anpr.xml"
Content-Type: text/xml
Content-Length: 2744
<?xml version="1.0" encoding="UTF-8"?>
<EventNotificationAlert version="2.0" xmlns="http://www.hikvision.com/ver20/XMLSchema">
<ipAddress>10.199.27.128</ipAddress>
<portNo>8888</portNo>
<protocol>HTTP</protocol>
<macAddress>d4:e8:53:bc:4c:02</macAddress>
<channelID>1</channelID>
<dateTime>2024-01-19T11:17:19+08:00</dateTime>
<activePostCount>1</activePostCount>
<eventType>ANPR</eventType>
<eventState>active</eventState>
<eventDescription>ANPR</eventDescription>
<channelName>Camera 01</channelName>
<ANPR>
<country>3</country>
<licensePlate>PECT600</licensePlate>
<line>2</line>
<direction>reverse</direction>
<confidenceLevel>97</confidenceLevel>
<plateType>unknown</plateType>
<plateColor>unknown</plateColor>
<licenseBright>0</licenseBright>
<dangmark>no</dangmark>
<twoWheelVehicle>no</twoWheelVehicle>
<threeWheelVehicle>no</threeWheelVehicle>
<plateCharBelieve>99,99,99,99,99,99,99</plateCharBelieve>
<vehicleType>vehicle</vehicleType>
<detectDir>8</detectDir>
<detectType>0</detectType>
<alarmDataType>0</alarmDataType>
<vehicleInfo>
<index>8050</index>
<colorDepth>2</colorDepth>
<color>white</color>
<length>0</length>
<vehicleLogoRecog>1036</vehicleLogoRecog>
<vehileSubLogoRecog>0</vehileSubLogoRecog>
<vehileModel>0</vehileModel>
</vehicleInfo>
<pictureInfoList>
<pictureInfo>
<fileName>licensePlatePicture.jpg</fileName>
<type>licensePlatePicture</type>
<dataType>0</dataType>
<picRecogMode>1</picRecogMode>
<absTime>20240119111719654</absTime>
<pId>2024011911172148100XqTdZBLMwoCkk</pId>
</pictureInfo>
<pictureInfo>
<fileName>detectionPicture.jpg</fileName>
<type>detectionPicture</type>
<dataType>0</dataType>
<picRecogMode>1</picRecogMode>
<absTime>20240119111719654</absTime>
<plateRect>
<X>691</X>
<Y>397</Y>
<width>59</width>
<height>34</height>
</plateRect>
<pId>2024011911172148200AcB8K3CS9B2h5</pId>
</pictureInfo>
</pictureInfoList>
<originalLicensePlate>PECT600</originalLicensePlate>
<CRIndex>3</CRIndex>
<vehicleListName>otherList</vehicleListName>
<plateSize>0</plateSize>
</ANPR>
<UUID>2024011911172144900FlERIduqg06eKsYuvLX072NugIxaHw22mHG5D5KBmWqX</UUID>
<picNum>2</picNum>
<monitoringSiteID></monitoringSiteID>
<isDataRetransmission>false</isDataRetransmission>
<DeviceGPSInfo>
<longitudeType>E</longitudeType>
<latitudeType>N</latitudeType>
<Longitude>
<degree>111</degree>
<minute>0</minute>
<sec>0.000000</sec>
</Longitude>
<Latitude>
<degree>0</degree>
<minute>22</minute>
<sec>0.000000</sec>
</Latitude>
</DeviceGPSInfo>
<detectionBackgroundImageResolution>
<height>1568</height>
<width>2560</width>
</detectionBackgroundImageResolution>
<countryAbbreviation>NON</countryAbbreviation>
</EventNotificationAlert>
--boundary
Content-Disposition: form-data; name="licensePlatePicture.jpg"; filename="2024011911172148100XqTdZBLMwoCkk.jpg"
Content-Type: image/jpeg
Content-Length: 5940
......JFIF..