ftp_file_pyinotify.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. # -*- coding: utf-8 -*-
  2. #!/usr/bin/env python
  3. # encoding:utf-8
  4. # 注意:import顺序很重要
  5. import os, sys
  6. # 将django项目根目录加入环境变量
  7. BASE_DIR = os.path.dirname(os.path.abspath(__file__)) # 定位到你的django根目录
  8. sys.path.append(os.path.abspath(os.path.join(BASE_DIR, os.pardir)))
  9. # 引入django配置文件
  10. os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yfwlw_pro.settings") # 你的django的settings文件
  11. # 启动django
  12. import django
  13. django.setup()
  14. import re
  15. import shutil
  16. import json
  17. import requests
  18. from PIL import Image
  19. from io import BytesIO
  20. import time
  21. import paho.mqtt.client as mqtt
  22. import sys
  23. import datetime
  24. from pyinotify import WatchManager, Notifier, \
  25. ProcessEvent, IN_DELETE, IN_CREATE, IN_MODIFY
  26. from apps.AppInfoManage.models import Equip, Equip_type, CBDdata, CBDstatus, MyUser,Alarm_record,CBDphoto, RecentCBDdata
  27. from apps.EquipManage.views import CJSONEncoder
  28. from apps.ReportManage.tasks import photo_transpond,test
  29. # 剪切
  30. def mymovefile(srcfile,dstfile):
  31. if not os.path.isfile(srcfile):
  32. print("%s not exist!"%(srcfile))
  33. else:
  34. fpath,fname=os.path.split(dstfile) #分离文件名和路径
  35. if not os.path.exists(fpath):
  36. os.makedirs(fpath) #创建路径
  37. shutil.move(srcfile,dstfile) #移动文件
  38. print("move %s -> %s"%(srcfile,dstfile))
  39. # 复制
  40. def mycopyfile(srcfile,dstfile):
  41. if not os.path.isfile(srcfile):
  42. print("%s not exist!"%(srcfile))
  43. else:
  44. fpath,fname=os.path.split(dstfile) #分离文件名和路径
  45. if not os.path.exists(fpath):
  46. os.makedirs(fpath) #创建路径
  47. shutil.copyfile(srcfile,dstfile) #复制文件
  48. print("copy %s -> %s"%(srcfile,dstfile))
  49. class EventHandler(ProcessEvent):
  50. """事件处理"""
  51. def process_IN_CREATE(self, event):
  52. print ("Create file: %s " % os.path.join(event.path, event.name))
  53. if event.name.endswith(".jpg"):
  54. print("new file upload is ok!")
  55. print("type event.path:",type(event.path))
  56. print("event.path:",event.path)
  57. print("event.name:",event.name)
  58. # imei = re.findall(r"/(.+?)/",event.path)
  59. imei = re.findall(r"\d+\.?\d*",event.path)[0]
  60. print("imei:", imei)
  61. nowtime = datetime.datetime.now().strftime('%Y%m%d')
  62. # origin = sys.stdout
  63. # f = open('../logs/'+nowtime+'.txt','a+')
  64. # sys.stdout = f
  65. # 判断设备是否存在:
  66. if Equip.objects.filter(equip_id=imei).exists():
  67. equip = Equip.objects.get(equip_id=imei)
  68. img_addr = "pyftp/" + os.path.join(event.path, event.name)
  69. # print("设备场景为------->>",equip.scene)
  70. # print("设备场景为------->>",type(equip.scene))
  71. # time.sleep(10)
  72. data_obj = RecentCBDdata.objects.get(equip_id=equip)
  73. CBDphoto.objects.create(equip_id=equip, addr=img_addr,at=eval(data_obj.cbd_data)['at'],ah=eval(data_obj.cbd_data)['ah'])
  74. print("==================================================")
  75. print("图片增加链接成功!")
  76. r = photo_transpond.delay(imei,event.path,event.name)
  77. # r = test.delay(imei)
  78. print("---------------->>",r)
  79. # FTP转发图片
  80. # try:
  81. # # if imei == "868575028869008":
  82. # if imei == "869300039229913" or imei == "860344048751540":
  83. # print("img_addr",img_addr)
  84. # time.sleep(20)
  85. # a = "/data/yfwlw/" + img_addr
  86. # # a = "/home/web/yfwlw/" + img_addr
  87. # # c = event.name
  88. # # b = c.replace(':','-')
  89. # # 切割文件名
  90. # # aa = img_addr.split("/")
  91. # # 拼接文件夹
  92. # # b = aa[3] + "/" + aa[4] + "/" + b
  93. # n_time = datetime.datetime.now()
  94. # b = imei + "/" + n_time.strftime('%Y%m%d') + "/" + n_time.strftime('%H-%M-%S') + ".jpg"
  95. # # print("bbbbbbb",b)
  96. # print("target_ftp_name:",b)
  97. # ftp_url = os.system(r'curl ftp://47.95.247.86:8022/%s --ftp-create-dirs -u "hnyfkj:hnyfkj19416" -T "%s" -# -v'%(b,a))
  98. # print("=====>>",ftp_url)
  99. # else:
  100. # pass
  101. # if imei == "869300039255967" or imei == "869300039253798" or imei == "868575028876029":
  102. # print("img_addr",img_addr)
  103. # time.sleep(20)
  104. # a = "/data/yfwlw/" + img_addr
  105. # # a = "/home/web/yfwlw/" + img_addr
  106. # # c = event.name
  107. # # b = c.replace(':','-')
  108. # # 切割文件名
  109. # # aa = img_addr.split("/")
  110. # # 拼接文件夹
  111. # # b = aa[3] + "/" + aa[4] + "/" + b
  112. # n_time = datetime.datetime.now()
  113. # b = imei + "/" + n_time.strftime('%Y%m%d') + "/" + n_time.strftime('%H-%M-%S') + ".jpg"
  114. # print("target_ftp_name:",b)
  115. # ftp_url = os.system(r'curl ftp://47.95.247.86:8022/%s --ftp-create-dirs -u "xjhnyfkj:xjhnyfkj511" -T "%s" -# -v'%(b,a))
  116. # print("=====>>",ftp_url)
  117. # else:
  118. # pass
  119. # except Exception as eee:
  120. # print(eee)
  121. # try:
  122. # time.sleep(10)
  123. # # insect_indentify 昆虫识别
  124. # # # 保存图片之后调用害虫识别接口
  125. # # 正则切割文件名 去掉.jpg后缀
  126. # pattern = r'[.]'
  127. # res = event.name
  128. # result = re.split(pattern, res)
  129. # insect_pic_name = result[0] + 'result' + '.jpg'
  130. # # url = 'http://60.166.14.184:9143/upload'
  131. # url = 'http://60.166.14.184:9143/upload'
  132. # # 测试服务器路径
  133. # # imageFile = {'imageFile':('pic.jpg',open("/home/web/yfwlw/" + img_addr,'rb'),'image/jpeg')}
  134. # # 正式服务器路径
  135. # imageFile = {'imageFile':('pic.jpg',open("/data/yfwlw/" + img_addr,'rb'),'image/jpeg')}
  136. # data = {'longitude':'118.279643','latitude':'31.221456'}
  137. # print('data:',data)
  138. # res = requests.post(url,data=data,files=imageFile,timeout=10)
  139. # print("res:",res.text)
  140. # resp = json.loads(res.text)
  141. # print("insect_pic_name:", insect_pic_name)
  142. # print("-------------------------接口调用成功")
  143. # except Exception as e:
  144. # print(e)
  145. # print("---------------------识别失败")
  146. # try:
  147. # if resp["returnResult"]["returnStatus"] == "0":
  148. # print("识别结果为空,不进行保存")
  149. # else:
  150. # # 将识别结果中的链接中的图片存入本地 测试服务器
  151. # # pic_dir_1 = "/home/web/yfwlw/result_pyftp/" + event.path + "/"
  152. # pic_dir_1 = "/data/yfwlw/result_pyftp/" + event.path + "/"
  153. # print("pic_dir_1:",pic_dir_1)
  154. # if os.path.exists(pic_dir_1) == False:
  155. # os.makedirs(pic_dir_1)
  156. # img_src = resp["returnResult"]["returnImageUrl"]
  157. # response = requests.get(img_src)
  158. # image = Image.open(BytesIO(response.content))
  159. # insect_image_addr = pic_dir_1 + insect_pic_name
  160. # print("insect_image_addr:",insect_image_addr)
  161. # image.save(insect_image_addr)
  162. # print("------------------图片保存成功")
  163. # try:
  164. # photo_obj = CBDphoto.objects.get(addr=img_addr)
  165. # if resp["returnResult"]["returnStatus"] == "0":
  166. # print("识别结果为空,不进行保存")
  167. # else:
  168. # # 将识别结果存入数据库
  169. # pic_dir = "result_pyftp/" + os.path.join(event.path, insect_pic_name)
  170. # photo_obj.indentify_photo = pic_dir
  171. # photo_obj.indentify_result = resp["returnResult"]["returnString"]
  172. # photo_obj.save()
  173. # print("图片路径:", pic_dir)
  174. # print("---------------数据库保存识别结果成功")
  175. # except Exception as ex:
  176. # print(ex)
  177. # print("---------------数据库保存识别结果失败")
  178. # except Exception as exc:
  179. # print(exc)
  180. # print("----------------识别结果图片保存失败")
  181. # try:
  182. # 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":
  183. # try:
  184. # if CBDphoto.objects.get(addr=img_addr).indentify_photo == None:
  185. # indentify_photo_1 = ""
  186. # indentify_result_1 = ""
  187. # img_addr_1 = "http://120.27.222.26/" + img_addr
  188. # else:
  189. # r_photo = CBDphoto.objects.get(addr=img_addr).indentify_photo
  190. # indentify_result_1 = CBDphoto.objects.get(addr=img_addr).indentify_result
  191. # img_addr_1 = "http://120.27.222.26/" + img_addr
  192. # indentify_photo_1 = "http://120.27.222.26/" + r_photo
  193. # data = {
  194. # "cmd": "Imageresult",
  195. # "ext": {
  196. # "Image": img_addr_1,
  197. # "Result_image": indentify_photo_1,
  198. # "Result": indentify_result_1,
  199. # "imei": imei
  200. # }
  201. # }
  202. # except Exception as eee:
  203. # print("====京东错误信息为",eee)
  204. # data = {
  205. # "cmd": "Imageresult",
  206. # "ext": {
  207. # "Image": "",
  208. # "Result_image": "",
  209. # "Result": "",
  210. # "imei": imei
  211. # }
  212. # }
  213. # TASK_TOPIC = '/yfkj/cbd/sub/%s'%imei # 客户端发布消息主题
  214. # """
  215. # 客户端发布消息
  216. # :param message: 消息主体
  217. # :return:
  218. # """
  219. # payload = data
  220. # # publish(主题:Topic; 消息内容)
  221. # client_id = time.strftime('%Y%m%d%H%M%S', time.localtime(time.time()))
  222. # client = mqtt.Client(client_id, transport='tcp')
  223. # client.connect("120.27.222.26", 1883, 60) # 此处端口默认为1883,通信端口期keepalive默认60
  224. # client.loop_start()
  225. # client.publish(TASK_TOPIC, json.dumps(payload, ensure_ascii=False))
  226. # if equip.ftp_addr:
  227. # # http://120.27.222.26/cbd/pyftp/ftp_file/ykm_cbd/868575028845867/20190305/20:56:15.jpg
  228. # ftp_addr = equip.ftp_addr
  229. # pattern = r'[#]'
  230. # split_result = re.split(pattern, ftp_addr)
  231. # print("split_result:",split_result)
  232. # try:
  233. # need_result = split_result[1]
  234. # except:
  235. # print("对接设备的地址填写有误!请检查!")
  236. # need_result = "0"
  237. # if need_result == "1":
  238. # if CBDphoto.objects.get(addr=img_addr).indentify_result == None:
  239. # indentify_photo_1 = CBDphoto.objects.get(addr=img_addr).indentify_result
  240. # else:
  241. # r_photo = CBDphoto.objects.get(addr=img_addr).indentify_photo
  242. # indentify_photo_1 = "http://120.27.222.26/" + r_photo
  243. # try:
  244. # # r_photo = CBDphoto.objects.get(addr=img_addr).indentify_photo
  245. # indentify_result_1 = CBDphoto.objects.get(addr=img_addr).indentify_result
  246. # img_addr_1 = "http://120.27.222.26/" + img_addr
  247. # # indentify_photo_1 = "http://120.27.222.26/" + r_photo
  248. # print("img_addr_1:",img_addr_1)
  249. # print("indentify_photo_1:",indentify_photo_1)
  250. # print("indentify_result_1:",indentify_result_1)
  251. # data = {
  252. # "Image":img_addr_1,
  253. # "Result_image":indentify_photo_1,
  254. # "Result":indentify_result_1,
  255. # "imei":imei
  256. # }
  257. # data = json.dumps(data, cls=CJSONEncoder)
  258. # print("data:",data)
  259. # res_1 = requests.post(split_result[0],data=data,timeout=2)
  260. # print("res_1:",res_1)
  261. # print("------------------识别结果发送成功!!!")
  262. # except Exception as aex:
  263. # print(aex)
  264. # try:
  265. # img_addr_1 = "http://120.27.222.26/" + img_addr
  266. # print("img_addr_1:",img_addr_1)
  267. # data = {
  268. # "Image":img_addr_1,
  269. # "imei":imei,
  270. # "Result_image":img_addr_1,
  271. # "Result":"0",
  272. # }
  273. # data = json.dumps(data, cls=CJSONEncoder)
  274. # print("data:",data)
  275. # print("url:",split_result[0])
  276. # res_1 = requests.post(split_result[0],data=data)
  277. # print(res_1.text)
  278. # except Exception as e:
  279. # print("错误信息为",e)
  280. # print("------------------识别结果发送失败!!!")
  281. # else:
  282. # try:
  283. # img_addr_1 = "http://120.27.222.26/" + img_addr
  284. # print("img_addr_1:",img_addr_1)
  285. # data = {
  286. # "Image":img_addr_1,
  287. # "imei":imei
  288. # }
  289. # data = json.dumps(data, cls=CJSONEncoder)
  290. # print("data:",data)
  291. # print("url:",split_result[0])
  292. # res_1 = requests.post(split_result[0],data=data,timeout=2)
  293. # print("res_1:",res_1.text)
  294. # # 判断文件大小的方法
  295. # # path = 'F:\YFWLW\yfwlw\\16_19_21.jpg'
  296. # # size = os.path.getsize(path)/1024
  297. # print("------------------对接设备图片发送成功!!!")
  298. # except Exception as aexc:
  299. # print(aexc)
  300. # print("------------------对接设备图片发送失败!!!")
  301. # except Exception as exce:
  302. # print(exce)
  303. # print("!!!")
  304. else:
  305. print("该设备不存在")
  306. # sys.stdout = origin
  307. # f.close()
  308. def process_IN_DELETE(self, event):
  309. print ("Delete file: %s " % os.path.join(event.path, event.name))
  310. # imei = re.findall(r"\d+\.?\d*",event.path)[0]
  311. # img_addr = "pyftp/" + os.path.join(event.path, event.name)
  312. # img_addr = "/home/web/yfwlw/" + img_addr[0:-9]
  313. # print("image_addr:",img_addr)
  314. # print("判断是否存在:",os.path.exists(img_addr))
  315. if event.name.endswith(".jpg"):
  316. print("file delete is ok!")
  317. # def process_IN_MODIFY(self, event):
  318. # print ("Modify file: %s " % os.path.join(event.path, event.name))
  319. def FSMonitor(path='.'):
  320. wm = WatchManager()
  321. mask = IN_DELETE | IN_CREATE | IN_MODIFY
  322. notifier = Notifier(wm, EventHandler())
  323. wm.add_watch(path, mask, auto_add=True, rec=True)
  324. print('ftp file watchdog is running')
  325. print('now starting monitor %s' % (path))
  326. while True:
  327. try:
  328. notifier.process_events()
  329. if notifier.check_events():
  330. notifier.read_events()
  331. except KeyboardInterrupt:
  332. notifier.stop()
  333. break
  334. if __name__ == "__main__":
  335. FSMonitor('ftp_file/ykm_cbd')