ftp_file_pyinotify.py 20 KB

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