华为IVS1800 第三方目标检测算法

# 描述 调用IVS1800 API 接口从摄像机上捕获截图
# 作者 gjs
# 日期 2022-06-17
# 版本 1.0
import json
import threading
import urllib.request
import urllib.parse
import ssl
import os
import time
import datetime
import argparse
import socket
from decimal import Decimal
import shutil
import requests
import smtplib
from email.mime.text import MIMEText

ssl._create_default_https_context = ssl._create_unverified_context

# 定义变量
cookie = ''  # 请求要携带的凭证
imagesPath = './images_new'  # 保存文件路径
imagesOldPath = './images_old'  # 保存文件路径
alarmPath = './alarm_info'
deviceList = []
userName = 'apiuser'
password = 'HuaWei@123'
ivsIP = ''  # IVS1800 API 访问IP
ivsPort = ''  # IVS1800 API 访问端口
intervalMinute = ''
warningApiUrl = ''  # 预警服务api地址
packNum = 10
cameralImageIsNormal = 1
sendWarningInfoIsNormal = 1
lastCameralImageTime = ''
lastSendWarningInfoTime = ''
lastTargetDetectionTime = ''
sendServerMonitoringInfoTimeInval = 5


def sendMail(subject='', text=''):
    # 确定发送方、邮箱授权码和接收方,邮件主题和内容
    my_from = '[email protected]'  # 发送方
    password = 'xxxxx'  # 授权码
    to = ['[email protected]']  # 接收方,可以多个接收方,类似于群发
    subject = subject  # 主题
    text = text  # 正文
    #  邮件内容设置
    # MIMEApplication用于发送各种文件,比如压缩,word,excel,pdf等
    '''
    #这一部分是用于发送图片的代码
    imageFile = r"1.jpg"
    imageApart = MIMEImage(open(imageFile, 'rb').read())
    imageApart.add_header('Content-Disposition', 'attachment', filename=imageFile)
    massage = MIMEMultipart()
    massage.attach(imageApart)
    构造邮件
    massage.attach(MIMEText(text,'html'))
    '''
    massage = MIMEText(text)  # 邮件对象
    massage['Subject'] = subject  # 给邮件添加主题
    # massage['From'] = my_from   #谁发送的
    massage['From'] = "IVS1800_淄博张店"  # 谁发送的

    massage['To'] = ";".join(to)  # 发给你想发送的对象

    # 发送邮件
    s = smtplib.SMTP_SSL('smtp.qq.com', 465)
    # smtp.qq.com是qq邮箱的服务器地址(SMTP地址),465是他的端口号

    s.login(my_from, password)
    # 登录
    s.sendmail(my_from, to, massage.as_string())
    # 发送方地址,接收方地址,邮件内容
    # massage.as_string()会将邮件原封不动的发送


# 发送服务器监控信息
def sendServerMonitoringInfo():
    info = ''
    while 1:
        try:
            if cameralImageIsNormal == 1:
                info += '获取图片正常,最后一次获取图片时间是%s\n' % lastCameralImageTime
            if cameralImageIsNormal == 0:
                info += '获取图片异常,最后一次获取图片时间是%s\n' % lastCameralImageTime
            if sendWarningInfoIsNormal == 1:
                info += '发送预警信息正常,最后一次发送预警信息时间是%s\n' % lastSendWarningInfoTime
            if sendWarningInfoIsNormal == 0:
                info += '发送预警信息异常,最后一次发送预警信息时间是%s\n' % lastSendWarningInfoTime
            info += '最后一次成功验证推理功能时间是:%s\n' % lastTargetDetectionTime
            if lastCameralImageTime != '' or lastSendWarningInfoTime != '':
                sendMail("IVS1800监控信息", info)
            info = ''
        except Exception as e:
            print(e)
            print('发送邮件失败')

        time.sleep(60 * sendServerMonitoringInfoTimeInval)


# get、post请求数据
def getRequestData(url='', data={}, headers={}, method=''):
    request = urllib.request.Request(url=url, data=data, headers=headers, method=method)
    response = urllib.request.urlopen(request)
    res = response.read()
    jsonData = json.loads(res)
    return jsonData


# 下载图片
def downLoadImages(url='', data={}, headers={}, method='', imageName=''):
    global cameralImageIsNormal, lastCameralImageTime
    request = urllib.request.Request(url=url, data=data, headers=headers, method=method)
    response = urllib.request.urlopen(request)
    img = response.read()
    with open(os.path.join(imagesOldPath, imageName), 'wb') as f:
        if len(img) > 100:
            f.write(img)
            shutil.copyfile(os.path.join(imagesOldPath, imageName), os.path.join(imagesPath, imageName))
            cameralImageIsNormal = 1
            lastCameralImageTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
        else:
            cameralImageIsNormal = 0


# 获取请求凭证
def getRequestCertificate():
    data = {
        'userName': userName,
        "password": password
    }

    headers = {
        'Content-Type': 'application/json'
    }
    data = bytes(json.dumps(data), 'utf8')
    # global ip, port
    url = 'https://%s:%s/loginInfo/login/v1.0' % (ivsIP, ivsPort)
    request = urllib.request.Request(url=url, data=data, headers=headers, method='POST')
    response = urllib.request.urlopen(request)
    global cookie
    cookie = response.headers.get('Set-Cookie').split(';')[0]
    res = response.read()
    jsonData = json.loads(res)
    return jsonData


# 获取设备列表
def getDeviceList():
    global deviceList
    deviceList = []
    data = {
    }

    headers = {
        'Content-Type': 'application/json',
        'Cookie': cookie
    }
    data = bytes(json.dumps(data), 'utf8')
    url = 'https://%s:%s/device/deviceList/v1.0?deviceType=2&fromIndex=1&toIndex=1000' % (ivsIP, ivsPort)
    res = getRequestData(url=url, data=data, headers=headers, method='GET')
    if res['resultCode'] == 0:
        deviceList = [data['code'] + '#' + data['domainCode'] for data in
                      res['cameraBriefInfos']['cameraBriefInfoList']]
    return res


# 请求保活
def keepAlive():
    while 1:
        try:
            data = {
            }

            headers = {
                'Content-Type': 'application/json',
                'Cookie': cookie
            }
            data = bytes(json.dumps(data), 'utf8')
            url = 'https://%s:%s/common/keepAlive' % (ivsIP, ivsPort)
            res = getRequestData(url=url, data=data, headers=headers, method='GET')
            # 网络状态正常,保活失败时,重新获取登录凭证
            if res['resultCode'] != 0:
                print('重新获取登录凭证')
                getRequestCertificate()
            print('保活方法返回:%s' % res)
        except Exception as e:
            print(e)
            print('keepAlive方法异常')
        time.sleep(60)


# 调用API方式发送预警信息
def sendAlarmData():
    global sendWarningInfoIsNormal, lastSendWarningInfoTime, lastTargetDetectionTime
    while 1:
        for alarmFile in os.listdir(alarmPath):
            alarmFilePath = os.path.join(alarmPath, alarmFile)
            with open(alarmFilePath, 'r') as file:
                try:
                    res = file.read()
                    data = json.loads(res)
                    imgPath = os.path.join(imagesOldPath, data['ImageName'])
                    if data['ImageName'] == 'test%29990707090103.jpg':
                        lastTargetDetectionTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    files = {'img': (imgPath, open(imgPath, 'rb'), 'image/jpg', {})}
                    requests.request('POST', url=warningApiUrl, data=data, files=files)
                    file.close()
                    os.remove(imgPath)
                    os.remove(alarmFilePath)
                    sendWarningInfoIsNormal = 1
                    lastSendWarningInfoTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                    # 每个预警数据间隔2秒
                    time.sleep(0.2)
                except Exception as e:
                    file.close()
                    os.remove(alarmFilePath)
                    sendWarningInfoIsNormal = 0
                    sendMail("IVS1800监控信息异常信息", '%s' % e)
                    print('发送预警数据失败!')

        time.sleep(1)


# 清理images_old文件夹过期图片
def clearOldImages():
    while 1:
        for imageFile in os.listdir(imagesOldPath):
            imageFilePath = os.path.join(imagesOldPath, imageFile)
            try:
                times = imageFile.split('%')[-1].split('.')[0]
                times = '%s-%s-%s %s:%s:%s' % (
                    times[0:4], times[4:6], times[6:8], times[8:10], times[10:12], times[12:14])
                times = datetime.datetime.strptime(times, '%Y-%m-%d %H:%M:%S')
                timeNow = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
                timeNow = datetime.datetime.strptime(timeNow, '%Y-%m-%d %H:%M:%S')
                seconds = (timeNow - times).total_seconds()
                if seconds > 2 * 60:
                    os.remove(imageFilePath)
            except Exception as e:
                print('清理images_old文件夹失败')

        time.sleep(1)


# 验证目标检测推理功能是否正常
def verifyTargetDetectionIsNormal():
    while 1:
        shutil.copyfile('./images/test%29990707090103.jpg', imagesPath + '/test%29990707090103.jpg')
        shutil.copyfile('./images/test%29990707090103.jpg', imagesOldPath + '/test%29990707090103.jpg')
        time.sleep(60 * 5)


def parse_args():
    """
    :return:进行参数的解析
    """
    description = "you should add those parameter"
    parser = argparse.ArgumentParser(description=description)
    parser.add_argument('-ivsIP', help='IVS1800 API ip')
    parser.add_argument('-ivsPort', help='IVS1800 API port')
    parser.add_argument('-intervalMinute', help='IVS1800 API camera images intervalMinute')
    parser.add_argument('-warningApiUrl', help='warningApiUrl')
    args = parser.parse_args()
    return args


if __name__ == '__main__':
    args = parse_args()
    ivsIP = args.ivsIP
    ivsPort = args.ivsPort
    intervalMinute = args.intervalMinute
    warningApiUrl = args.warningApiUrl

    # ivsIP = '10.198.12.196'
    # ivsPort = '18531'
    # intervalMinute = 1
    # warningApiUrl = 'http://10.198.12.200:90//IVS/Upload'

    try:
        if ivsIP is None or ivsPort is None:
            raise Exception('请传入IVS1800 API ip,port!')
        if warningApiUrl is None:
            raise Exception('请传入warningApiUrl!')
        if intervalMinute is None:
            raise Exception('请传入IVS1800 API intervalMinute!')
        # 获取请求凭证
        res = getRequestCertificate()
        if res['resultCode'] != 0:
            print('获取凭证失败')
        # 请求保活
        t = threading.Thread(target=keepAlive, args=())
        t.start()
        # 开启线程发送预警信息到预警服务器
        m = threading.Thread(target=sendAlarmData, args=())
        m.start()

        # 开启线程发送服务器监控信息
        m = threading.Thread(target=sendServerMonitoringInfo, args=())
        m.start()

        # 发送测试图片到推理模型,验证推理功能是否正常工作
        m = threading.Thread(target=verifyTargetDetectionIsNormal, args=())
        m.start()

        # 清理images_old过期文件
        m = threading.Thread(target=clearOldImages, args=())
        m.start()

        # 获取设备截图
        while 1:
            try:
                res = getDeviceList()
                if res['resultCode'] != 0:
                    print('获取设备列表失败')
                for code in deviceList:
                    data = {
                        'cameraCode': code
                    }

                    headers = {
                        'Content-Type': 'application/json',
                        'Cookie': cookie
                    }
                    data = bytes(json.dumps(data), 'utf8')
                    url = 'https://%s:%s/snapshot/manualsnapshot' % (ivsIP, ivsPort)
                    imageName = code + '%' + datetime.datetime.now().strftime('%Y%m%d%H%M%S') + '.jpg'
                    downLoadImages(url=url, data=data, headers=headers, method='POST', imageName=imageName)
                    if os.path.exists(imagesPath + "/" + imageName):
                        for i in range(25):
                            shutil.copyfile(imagesOldPath + "/" + imageName, imagesOldPath + "/" + str(i) + imageName)
                            shutil.copyfile(imagesOldPath + "/" + imageName, imagesPath + "/" + str(i) + imageName)

                    time.sleep(1)
            except Exception as e:
                print(e)
            time.sleep(int(Decimal(intervalMinute) * 60))
    except Exception as e:
        print(e)
        print('调用格式 python3 CameraImages.py -ivsIP 10.198.12.196 -ivsPort 18531 -intervalMinute 1 -warningApiUrl http://10.198.12.200:90//IVS/Upload')

你可能感兴趣的:(人工智能,目标检测,人工智能,python,计算机视觉)