# -*- coding: utf-8 -*- # File Name:mqtt_chat_client.py # Python Version:3.5.1 import os import django import sys from qcloudsms_py import SmsSingleSender from qcloudsms_py.httpclient import HTTPError from qcloudsms_py import SmsMultiSender BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目录 sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir))) os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yfwlw_pro.settings") # project_name 项目名称 django.setup() import json from apps.AppInfoManage.models import Equip, Equip_type, MyUser, CBDphoto, CBDstatus, QXZdata, SCDstatus, CBDstatus, Equip_SimInfo, CBDdata, BZYphoto, RecentCBDdata,RecentSCDdata,\ Msg_Conf, Msg_Send, BZYstatus import re import datetime import time import random from apps.SimInfo.views import get_siminfo from apps.ReportManage.all_dict import insect_dict_new, transpont_equip_scd import requests import oss2 from PIL import Image from io import BytesIO auth = oss2.Auth('LTAI4G7tFh5Nk4KXZoSPk1D8', 'RV4S2SfbLPoFNjlI4uIOoA0J1LQPQc') # Endpoint以杭州为例,其它Region请按实际情况填写。 # bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', '') # bucket = oss2.Bucket(auth, 'https://cbdphoto.oss-cn-hangzhou.aliyuncs.com', 'cbdphoto') bucket = oss2.Bucket(auth, 'http://oss-cn-hangzhou.aliyuncs.com', 'cbdpic') def TimeStampToTime(timestamp): timeStruct = time.localtime(timestamp) str_p = time.strftime('%Y-%m-%d %H:%M:%S',timeStruct) dateTime_p = datetime.datetime.strptime(str_p,'%Y-%m-%d %H:%M:%S') return dateTime_p def get_FileCreateTime(filePath): # filePath = unicode(filePath,'utf8') t = os.path.getmtime(filePath) return TimeStampToTime(t) # imei = request.POST.get("imei") for x in Equip.objects.filter(equip_type=3): imei = x.equip_id equip_obj = x file_dir = "../pyftp/ftp_file/ykm_cbd/%s"%imei for root, dirs, file in os.walk(file_dir): if file != [] and "jpg" in file[0]: # print("当前路径下所有非目录子文件>>",file) for i in file: pic_addr_1 = root + "/" + i pic_addr = pic_addr_1.replace("../","") picname_1 = get_FileCreateTime(pic_addr_1) # print("文件时间为",picname_1) # now = datetime.datetime.now() # try: # if imei == "869300039229913" or imei == "860344048751540": # print("pic_addr",pic_addr) # a = "/data/yfwlw/" + pic_addr # n_time = datetime.datetime.now() # b = imei + "/" + n_time.strftime('%Y%m%d') + "/" + n_time.strftime('%H-%M-%S') + ".jpg" # print("target_ftp_name:",b) # ftp_url = os.system(r'curl ftp://47.95.247.86:8022/%s --ftp-create-dirs -u "hnyfkj:hnyfkj19416" -T "%s" -# -v'%(b,a)) # print("=====>>",ftp_url) # elif imei == "869300039255967" or imei == "869300039253798" or imei == "868575028876029": # print("pic_addr",pic_addr) # a = "/data/yfwlw/" + pic_addr # n_time = datetime.datetime.now() # b = imei + "/" + n_time.strftime('%Y%m%d') + "/" + n_time.strftime('%H-%M-%S') + ".jpg" # print("target_ftp_name:",b) # ftp_url = os.system(r'curl ftp://47.95.247.86:8022/%s --ftp-create-dirs -u "xjhnyfkj:xjhnyfkj511" -T "%s" -# -v'%(b,a)) # print("=====>>",ftp_url) # else: # pass # except Exception as eee: # print(eee) try: a_name = i.replace(".jpg","") insect_pic_name = a_name + 'result' + '.jpg' url = 'http://60.166.14.184:9143/upload' # 测试服务器路径 imageFile = {'imageFile':('pic.jpg',open("/home/web/yfwlw/" + pic_addr,'rb'),'image/jpeg')} lng = CBDstatus.objects.get(equip_id=equip_obj).lng lat = CBDstatus.objects.get(equip_id=equip_obj).lat # 正式服务器路径 # imageFile = {'imageFile':('pic.jpg',open("/data/yfwlw/" + pic_addr,'rb'),'image/jpeg')} data = {'longitude':lng,'latitude':lat} print('data:',data) res = requests.post(url,data=data,files=imageFile,timeout=10) print("res:",res.text) resp = json.loads(res.text) print("insect_pic_name:", insect_pic_name) print("-------------------------接口调用成功") except Exception as e: print(e) print("---------------------识别失败") try: if resp["returnResult"]["returnStatus"] == "0": print("识别结果为空,不进行保存") else: # 将识别结果中的链接中的图片存入本地 测试服务器 pic_dir_1 = "/home/web/yfwlw/result_pyftp/" + root + "/" # pic_dir_1 = "/data/yfwlw/result_pyftp/" + root + "/" print("pic_dir_1:",pic_dir_1) if os.path.exists(pic_dir_1) == False: os.makedirs(pic_dir_1) img_src = resp["returnResult"]["returnImageUrl"] response = requests.get(img_src) image = Image.open(BytesIO(response.content)) insect_image_addr = pic_dir_1 + insect_pic_name print("insect_image_addr:",insect_image_addr) image.save(insect_image_addr) print("------------------图片保存成功") try: # photo_obj = CBDphoto.objects.get(addr=pic_addr) photo_obj = CBDphoto.objects.create(equip_id=equip_obj,addr=pic_addr) if resp["returnResult"]["returnStatus"] == "0": print("识别结果为空,不进行保存") else: # 将识别结果存入数据库 pic_dir = "result_pyftp/" + os.path.join(root, insect_pic_name) photo_obj.indentify_photo = pic_dir photo_obj.indentify_result = resp["returnResult"]["returnString"] photo_obj.save() print("图片路径:", pic_dir) print("---------------数据库保存识别结果成功") except Exception as ex: print(ex) print("---------------数据库保存识别结果失败") except Exception as exc: print(exc) print("----------------识别结果图片保存失败") addr = pic_addr.split("/")[-1] if "ALARM_INPUT" in addr or "FACE_BACKGROUND" in addr or "FACE_SNAP" in addr or "MOTION_DETECTION" in addr or "ALARM_INP" in addr: # print("长addr",addr) _time = addr.split("_")[2][0:14] # print("------->>",len(_time)) try: _time = datetime.datetime.strptime(_time,'%Y%m%d%H%M%S') except: print("时间转化错误alarm") print("----->>",addr) _time = picname_1 # print("192.168的时间",pic_addr) # print("------->>",_time) # if i.upl_time.hour != _time.hour: # i.upl_time = _time # i.save() elif len(addr) == 18: _time = addr.split(".")[0][0:14] _time = _time.split("\r")[0] try: _time = datetime.datetime.strptime(_time,'%Y%m%d%H%M%S') except: print("时间转化错误18") print("----->>",addr) _time = picname_1 # print("len=18的时间",pic_addr) # print("------->>",_time) elif ":" in addr: _year_month = pic_addr.split("/")[-2] _day = addr.split(".")[0] _time = _year_month + _day try: _time = datetime.datetime.strptime(_time,'%Y%m%d%H:%M:%S') except: print("时间转化错误 :") print("----->>",addr) _time = get_FileCreateTime(pic_addr_1) # print("带:的时间",pic_addr) # print("------->>",_time) elif "-" in addr and len(addr) < 15: _year_month = pic_addr.split("/")[-2] _day = addr.split(".")[0] _time = _year_month + _day try: _time = datetime.datetime.strptime(_time,'%Y%m%d%H-%M-%S') except: print("时间转化错误-") print("----->>",addr) _time = get_FileCreateTime(pic_addr_1) # print("带-的时间",pic_addr) # print("------->>",_time) elif len(addr) == 10: _year_month = pic_addr.split("/")[-2] _day = addr.split(".")[0] _time = _year_month + _day try: _time = datetime.datetime.strptime(_time,'%Y%m%d%H%M%S') except: print("时间转化错误10") print("----->>",pic_addr) _time = get_FileCreateTime(pic_addr_1) # print("len=10的时间",pic_addr) # print("------->>",_time) elif "-" in addr and len(addr) > 15: _addr = addr.split('.')[-2] _addr = _addr.split('-') _time = _addr[-2] + _addr[-1] try: _time = datetime.datetime.strptime(_time,'%Y%m%d%H%M%S') except: print("时间转化错误--") print("----->>",pic_addr) _time = get_FileCreateTime(pic_addr_1) else: print("其他addr",addr) print("其他",pic_addr) _time = get_FileCreateTime(pic_addr_1) # time.sleep(1) if _time.year == 1970: _time = get_FileCreateTime(pic_addr_1) strnow = datetime.datetime.strftime(_time,'%Y%m') picname = datetime.datetime.strftime(_time,'%Y%m%d%H%M%S') # # bucket_pic = bucket.put_object_from_file(strnow + '/' + imei + '/'+ picname + '.jpg', pic_addr_1) # print("图片数据库路径为pic_addr",pic_addr) new_addr = "https://cbdpic.oss-cn-hangzhou.aliyuncs.com/" + strnow + '/' + imei + '/'+ picname + '.jpg' exist = bucket.object_exists(strnow + '/' + imei + '/'+ picname + '.jpg') if exist: print('object exist') if CBDphoto.objects.filter(addr=pic_addr).exists(): if CBDphoto.objects.filter(addr=new_addr).exists(): pass else: data_obj = RecentCBDdata.objects.get(equip_id=equip_obj) # CBDphoto.objects.create(equip_id=equip_obj,addr=new_addr,upl_time=_time) CBDphoto.objects.filter(addr=pic_addr).update(addr=new_addr,upl_time=_time,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) # os.remove(pic_addr_1) print("图片删除成功") print("数据库创建链接成功") else: if CBDphoto.objects.filter(addr=new_addr).exists(): pass else: data_obj = RecentCBDdata.objects.get(equip_id=equip_obj) # CBDphoto.objects.create(equip_id=equip, addr=img_addr,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) CBDphoto.objects.create(equip_id=equip_obj,addr=new_addr,upl_time=_time,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) # os.remove(pic_addr_1) print("图片删除成功") else: print('object not exist') bucket_pic = bucket.put_object_from_file(strnow + '/' + imei + '/'+ picname + '.jpg', pic_addr_1) if CBDphoto.objects.filter(addr=pic_addr).exists(): if CBDphoto.objects.filter(addr=new_addr).exists(): pass else: data_obj = RecentCBDdata.objects.get(equip_id=equip_obj) # CBDphoto.objects.create(equip_id=equip, addr=img_addr,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) CBDphoto.objects.filter(addr=pic_addr).update(addr=new_addr,upl_time=_time,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) # os.remove(pic_addr_1) print("图片删除成功") else: if CBDphoto.objects.filter(addr=new_addr).exists(): pass else: data_obj = RecentCBDdata.objects.get(equip_id=equip_obj) # CBDphoto.objects.create(equip_id=equip, addr=img_addr,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) CBDphoto.objects.create(equip_id=equip_obj,addr=new_addr,upl_time=_time,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah']) # os.remove(pic_addr_1) print("图片删除成功") # BZYphoto.objects.create(equip_id=imei,addr=new_addr,upl_time=picname) print("oss传输成功") try: if imei == "868956044807455" or imei == "868956044806671" or imei == "868956044831604" or imei == "868956044831711" or imei == "868956044807471" or imei == "868956044830994" or imei == "868956044824930" or imei == "868956044807455" or imei == "865650043209341" or imei == "868956044806705" or imei == "868956044830929" or imei == "868956044824898" or imei == "868956044830887" or imei == "868956044830911": try: if CBDphoto.objects.get(addr=new_addr).indentify_photo == None: indentify_photo_1 = "" indentify_result_1 = "" img_addr_1 = new_addr else: r_photo = CBDphoto.objects.get(addr=new_addr).indentify_photo indentify_result_1 = CBDphoto.objects.get(addr=new_addr).indentify_result img_addr_1 = new_addr indentify_photo_1 = "http://120.27.222.26/" + r_photo data = { "cmd": "Imageresult", "ext": { "Image": img_addr_1, "Result_image": indentify_photo_1, "Result": indentify_result_1, "imei": imei } } except Exception as eee: print("====京东错误信息为",eee) data = { "cmd": "Imageresult", "ext": { "Image": "", "Result_image": "", "Result": "", "imei": imei } } TASK_TOPIC = '/yfkj/cbd/sub/%s'%imei # 客户端发布消息主题 """ 客户端发布消息 :param message: 消息主体 :return: """ payload = data # publish(主题:Topic; 消息内容) client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time())) client = mqtt.Client(client_id, transport='tcp') client.connect("120.27.222.26", 1883, 60) # 此处端口默认为1883,通信端口期keepalive默认60 client.loop_start() client.publish(TASK_TOPIC, json.dumps(payload, ensure_ascii=False)) print("京东信息发送成功",data) # equip = Equip.objects.get(equip_id=imei) # if equip.ftp_addr: # # http://120.27.222.26/cbd/pyftp/ftp_file/ykm_cbd/868575028845867/20190305/20:56:15.jpg # ftp_addr = equip.ftp_addr # pattern = r'[#]' # split_result = re.split(pattern, ftp_addr) # print("split_result:",split_result) # try: # need_result = split_result[1] # except: # print("对接设备的地址填写有误!请检查!") # need_result = "0" print("imei------------------------>>",imei) try: equip_list = Equip_Forward.objects.get(equip_id=imei) ftp_addr = equip_list.equip_img_url pattern = r'[#]' split_result = re.split(pattern, ftp_addr) print("split_result:",split_result) need_result = split_result[1] except: print("对接设备的地址填写有误!请检查!") need_result = "400" #害虫识别 if need_result == "1": if CBDphoto.objects.get(addr=new_addr).indentify_result == None: indentify_photo_1 = CBDphoto.objects.get(addr=new_addr).indentify_result else: r_photo = CBDphoto.objects.get(addr=new_addr).indentify_photo indentify_photo_1 = "http://120.27.222.26/" + r_photo try: # r_photo = CBDphoto.objects.get(addr=img_addr).indentify_photo indentify_result_1 = CBDphoto.objects.get(addr=new_addr).indentify_result img_addr_1 = new_addr # indentify_photo_1 = "http://120.27.222.26/" + r_photo print("img_addr_1:",img_addr_1) print("indentify_photo_1:",indentify_photo_1) print("indentify_result_1:",indentify_result_1) if indentify_result_1 == None: data = { "Image":img_addr_1, "imei":imei, "Result_image":"0", "Result":"0", } else: data = { "Image":img_addr_1, "Result_image":indentify_photo_1, "Result":indentify_result_1, "imei":imei } data = json.dumps(data, cls=CJSONEncoder) print("data:",data) if equip_list.equip_img_between == "1": res_1 = requests.post(split_result[0],data=data,timeout=2) elif equip_list.equip_img_between == "2": headers = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'} res_1 = requests.post(split_result[0], data=data, timeout=3,headers=headers) print("res_1:",res_1) print("------------------识别结果发送成功!!!") except Exception as aex: print(aex) try: img_addr_1 = new_addr print("img_addr_1:",img_addr_1) data = { "Image":img_addr_1, "imei":imei, "Result_image":"0", "Result":"0", } data = json.dumps(data, cls=CJSONEncoder) print("data:",data) print("url:",split_result[0]) if equip_list.equip_img_between == "1": res_1 = requests.post(split_result[0],data=data,timeout=2) elif equip_list.equip_img_between == "2": headers = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'} res_1 = requests.post(split_result[0], data=data, timeout=3,headers=headers) print(res_1.text) except Exception as e: print("错误信息为",e) print("------------------识别结果发送失败!!!") #害虫计数 elif need_result == "2": try: # r_photo = CBDphoto.objects.get(addr=img_addr).indentify_photo indentify_result_1 = CBDphoto.objects.get(addr=new_addr).indentify_result img_addr_1 = new_addr # indentify_photo_1 = "http://120.27.222.26/" + r_photo print("img_addr_1:",img_addr_1) print("indentify_result_1:",indentify_result_1) data = { "Image":img_addr_1, "Result":indentify_result_1, "imei":imei } data = json.dumps(data, cls=CJSONEncoder) print("data:",data) if equip_list.equip_img_between == "1": res_1 = requests.post(split_result[0],data=data,timeout=2) elif equip_list.equip_img_between == "2": headers = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'} res_1 = requests.post(split_result[0], data=data, timeout=3,headers=headers) print("res_1:",res_1) print("------------------识别结果发送成功!!!") except Exception as aex: print(aex) try: img_addr_1 = new_addr print("img_addr_1:",img_addr_1) data = { "Image":img_addr_1, "imei":imei, "Result":"0", } data = json.dumps(data, cls=CJSONEncoder) print("data:",data) print("url:",split_result[0]) if equip_list.equip_img_between == "1": res_1 = requests.post(split_result[0],data=data,timeout=2) elif equip_list.equip_img_between == "2": headers = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'} res_1 = requests.post(split_result[0], data=data, timeout=3,headers=headers) print(res_1.text) except Exception as e: print("错误信息为",e) print("------------------识别结果发送失败!!!") #不带害虫识别 elif need_result == "0": try: img_addr_1 = new_addr print("img_addr_1:",img_addr_1) data = { "Image":img_addr_1, "imei":imei } data = json.dumps(data, cls=CJSONEncoder) print("data:",data) print("url:",split_result[0]) if equip_list.equip_img_between == "1": res_1 = requests.post(split_result[0],data=data,timeout=2) elif equip_list.equip_img_between == "2": headers = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'} res_1 = requests.post(split_result[0], data=data, timeout=3,headers=headers) print("res_1:",res_1.text) # 判断文件大小的方法 # path = 'F:\YFWLW\yfwlw\\16_19_21.jpg' # size = os.path.getsize(path)/1024 print("------------------对接设备图片发送成功!!!") except Exception as aexc: print(aexc) print("------------------对接设备图片发送失败!!!") except Exception as exce: print(exce) print("!!!") # if BZYphoto.objects.filter(addr=pic_addr).exists(): # print("照片存在") # print("新的照片路径为",new_addr) # # 返回值为true表示文件存在,false表示文件不存在。 # if exist: # if BZYphoto.objects.filter(addr=new_addr).exists(): # BZYphoto.objects.filter(addr=new_addr).update(equip_id=equip_obj,upl_time=_time) # print('object exist') # BZYphoto.objects.filter(addr=pic_addr).update(equip_id=equip_obj,addr=new_addr,upl_time=_time) # else: # BZYphoto.objects.filter(addr=pic_addr).update(equip_id=equip_obj,addr=new_addr,upl_time=_time) # bucket_pic = bucket.put_object_from_file(strnow + '/' + imei + '/'+ picname + '.jpg', pic_addr_1) # print("oss传输成功") # print('object not exist') # else: # print("照片不存在") # # print("图片时间为",get_FileCreateTime(picname)) # if exist: # print('object exist') # if BZYphoto.objects.filter(addr=new_addr).exists(): # BZYphoto.objects.filter(addr=new_addr).update(equip_id=equip_obj,upl_time=_time) # else: # BZYphoto.objects.create(equip_id=equip_obj,addr=new_addr,upl_time=_time) # else: # print('object not exist') # if BZYphoto.objects.filter(addr=new_addr).exists(): # BZYphoto.objects.filter(addr=new_addr).update(equip_id=equip_obj,upl_time=_time) # else: # BZYphoto.objects.create(equip_id=equip_obj,addr=new_addr,upl_time=_time) # # BZYphoto.objects.create(equip_id=imei,addr=new_addr,upl_time=picname) # bucket_pic = bucket.put_object_from_file(strnow + '/' + imei + '/'+ picname + '.jpg', pic_addr_1) # print("oss传输成功") # if equip_obj.ftp_addr: # # bzy_imgs = "http://www.yfzhwlw.com/bzy/" + photo_addr # data = { # "Image":new_addr, # "imei":imei, # } # data = json.dumps(data) # headers = {"Content-Type": "application/json; charset=UTF-8", 'Connection': 'close'} # bzy_photo = requests.post(equip_obj.ftp_addr,data=data,headers=headers,timeout=3) # print("转发成功") # print('=================================================')