test2.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. #主業務邏輯中的視圖和路由的定義
  2. import os
  3. import datetime
  4. from flask import render_template, request, session, Response
  5. #導入藍圖程序,用於構建路由
  6. from werkzeug.utils import redirect
  7. from . import main
  8. from manage import mqtt
  9. #導入db,用於操作數據庫
  10. from manage import db
  11. #導入實體類,用於操作數據庫
  12. from ..models import *
  13. import json
  14. from datetime import datetime as dt
  15. from sqlalchemy import text
  16. import socket
  17. import pickle
  18. import cv2
  19. import numpy as np
  20. import math
  21. import threading
  22. import time
  23. #主頁的訪問路徑
  24. @main.route('/')
  25. def main_index():
  26. #獲取登入信息
  27. if 'id' in session and 'uname' in session:
  28. return render_template('allindex.html')
  29. else:
  30. return render_template('sign_in.html')
  31. #登入頁面的訪問路徑
  32. @main.route('/login', methods=['GET','POST'])
  33. def login_views():
  34. if request.method == 'GET':
  35. if 'id' in session and 'uname' in session:
  36. return redirect('/')
  37. else:
  38. return render_template('sign_in.html')
  39. else:
  40. #接收前端傳過來的資料
  41. username = request.form['username']
  42. password = request.form['password']
  43. #使用接收的用戶和密碼到資料庫中查詢
  44. user = User.query.filter_by(account=username, password=password).first()
  45. #如果用戶存在,將信息保存置session並重定向回首頁,否則重定向回登入頁
  46. if user:
  47. resp = redirect('/')
  48. #判斷是否有記住密碼
  49. if 'rem' in request.form:
  50. sn = str(user.sn)
  51. max_age = 60*60*24*365
  52. resp.set_cookie("username", username, max_age=max_age)
  53. resp.set_cookie("sn", sn, max_age=max_age)
  54. session['uname'] = user.account
  55. session['id'] = user.sn
  56. return resp
  57. else:
  58. errMsg = "Wrong login or password"
  59. return render_template('sign_in.html',errMsg=errMsg)
  60. #註冊頁面的訪問路徑
  61. @main.route('/register',methods=['POST',"GET"])
  62. def register_views():
  63. if request.method == 'GET':
  64. return render_template('registration.html')
  65. else:
  66. #獲取文本框的值並賦值給user實體對象
  67. user = User()
  68. user.account = request.form['username']
  69. user.password = request.form['password']
  70. #將數據保存進資料庫 - 註冊
  71. db.session.add(user)
  72. #手動提交,目的是為了獲取提交後的user的id
  73. db.session.commit()
  74. #當user成功插入進資料庫之後,程序會自動將所有信息取出來在賦值給user
  75. #完成登入的操作
  76. user = User.query.filter_by(account=user.account).first()
  77. session['id'] = user.sn
  78. session['uname'] = user.account
  79. return redirect('/')
  80. #毛豆田的主頁面
  81. @main.route('/aindex', methods=['POST', 'GET'])
  82. def aindex_views():
  83. return render_template('aindex.html')
  84. #毛豆車的主頁面
  85. @main.route('/cindex', methods=['POST', 'GET'])
  86. def cindex_views():
  87. return render_template('cindex.html')
  88. #毛豆田拍攝設定的主頁面
  89. @main.route('/ashoot_setting/<tid>', methods=['POST', 'GET'])
  90. def ashoot_setting_views(tid):
  91. if request.method == 'GET':
  92. dict = request.args.to_dict()
  93. if dict:
  94. try:
  95. nr = "KDAIS" + dict['nr']
  96. mode = int(dict['mode'])
  97. jvtotime = JvtOTime.query.filter_by(nr=nr, MODE=mode).order_by(text('datetime desc')).first()
  98. tilt_angle = jvtotime.tilt_angle
  99. pan_angle = jvtotime.pan_angle
  100. zoom = str(jvtotime.zoom_now)
  101. time1 = jvtotime.time1
  102. time2 = jvtotime.time2
  103. time3 = jvtotime.time3
  104. time4 = jvtotime.time4
  105. time5 = jvtotime.time5
  106. time6 = jvtotime.time6
  107. time7 = jvtotime.time7
  108. time8 = jvtotime.time8
  109. dict = {"tilt_angle":tilt_angle, "pan_angle":pan_angle, "zoom":zoom, "time1":time1,
  110. "time2":time2, "time3":time3, "time4":time4, "time5":time5, "time6":time6,
  111. "time7":time7, "time8":time8}
  112. return json.dumps(dict)
  113. except Exception:
  114. dict = {"tilt_angle":"0", "pan_angle":"0", "zoom":"0", "time1":"00000000",
  115. "time2":"00000000", "time3":"00000000", "time4":"00000000", "time5":"00000000", "time6":"00000000",
  116. "time7":"00000000", "time8":"00000000"}
  117. return json.dumps(dict)
  118. return render_template('aim.html', params=locals())
  119. else:
  120. dict = request.form.to_dict()
  121. jvtotime = JvtOTime()
  122. if dict['nr'] == '1':
  123. jvtotime.MAC = 'b8:27:eb:a1:b0:70'
  124. elif dict['nr'] == '2':
  125. jvtotime.MAC = 'b8:27:eb:e7:51:44'
  126. elif dict['nr'] == '3':
  127. jvtotime.MAC = 'b8:27:eb:ce:a5:35'
  128. elif dict['nr'] == '4':
  129. jvtotime.MAC = 'b8:27:eb:06:9a:f1'
  130. elif dict['nr'] == '5':
  131. jvtotime.MAC = 'b8:27:eb:0c:f0:21'
  132. elif dict['nr'] == '6':
  133. jvtotime.MAC = 'b8:27:eb:df:4b:0f'
  134. elif dict['nr'] == '7':
  135. jvtotime.MAC = 'b8:27:eb:af:df:b6'
  136. elif dict['nr'] == '8':
  137. jvtotime.MAC = 'b8:27:eb:d2:d0:8f'
  138. elif dict['nr'] == '9':
  139. jvtotime.MAC = 'b8:27:eb:57:3c:da'
  140. elif dict['nr'] == '10':
  141. jvtotime.MAC = 'b8:27:eb:bd:29:b1'
  142. elif dict['nr'] == '11':
  143. jvtotime.MAC = 'b8:27:eb:7c:f6:06'
  144. elif dict['nr'] == '12':
  145. jvtotime.MAC = 'b8:27:eb:74:bd:ac'
  146. elif dict['nr'] == '13':
  147. jvtotime.MAC = 'b8:27:eb:e7:21:e5'
  148. elif dict['nr'] == '14':
  149. jvtotime.MAC = 'b8:27:eb:6f:5a:6b'
  150. elif dict['nr'] == '15':
  151. jvtotime.MAC = 'b8:27:eb:e3:f1:f4'
  152. elif dict['nr'] == '16':
  153. jvtotime.MAC = 'b8:27:eb:60:1c:2e'
  154. elif dict['nr'] == '17':
  155. jvtotime.MAC = 'b8:27:eb:9d:68:05'
  156. elif dict['nr'] == '18':
  157. jvtotime.MAC = 'b8:27:eb:4d:e4:34'
  158. jvtotime.nr = 'KDAIS' + dict['nr']
  159. jvtotime.MODE = int(dict['mode'])
  160. jvtotime.tilt_angle = dict['tilt_angle']
  161. jvtotime.pan_angle = dict['pan_angle']
  162. jvtotime.zoom_before = 0
  163. jvtotime.zoom_now = int(dict['zoom'])
  164. jvtotime.time1 = dict['time1']
  165. jvtotime.time2 = dict['time2']
  166. jvtotime.time3 = dict['time3']
  167. jvtotime.time4 = dict['time4']
  168. jvtotime.time5 = dict['time5']
  169. jvtotime.time6 = dict['time6']
  170. jvtotime.time7 = dict['time7']
  171. jvtotime.time8 = dict['time8']
  172. jvtotime.datetime = dt.now()
  173. db.session.add(jvtotime)
  174. db.session.commit()
  175. return {"status":"OK"}
  176. #毛豆田歷史資料的主頁面
  177. @main.route('/aimg_history/<tid>', methods=['POST', 'GET'])
  178. def aimg_history_views(tid):
  179. if request.method == 'GET':
  180. return render_template('ahistory_ndvi1.html', params=locals())
  181. else:
  182. pass
  183. #毛豆車拍攝設定的主頁面
  184. @main.route('/cshoot_setting/<tid>', methods=['POST', 'GET'])
  185. def cshoot_setting_views(tid):
  186. if request.method == 'GET':
  187. return render_template('cim.html', params=locals())
  188. else:
  189. pass
  190. #毛豆車歷史資料的主頁面
  191. @main.route('/cimg_history/<tid>', methods=['POST', 'GET'])
  192. def cimg_history_views(tid):
  193. if request.method == 'GET':
  194. return render_template('chistory_ndvi1.html', params=locals())
  195. else:
  196. pass
  197. #退出的訪問路徑
  198. @main.route('/logout')
  199. def logout_views():
  200. if 'id' in session and 'uname' in session:
  201. del session['id']
  202. del session['uname']
  203. return redirect('/')
  204. lock = threading.Lock()
  205. @main.route("/udp_client")
  206. def udp_views():
  207. time.sleep(1)
  208. max_length = 65000
  209. # max_length = 95000
  210. #lab1的IP
  211. host = "192.168.50.65"
  212. # lab2的IP
  213. # host = "192.168.51.161"
  214. port = 8000
  215. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  216. #地下室小兵
  217. # cap = cv2.VideoCapture('rtsp://admin:abcd1234@192.168.51.48/av2_0')
  218. #主機攝像頭
  219. # cap = cv2.VideoCapture(0)
  220. #外面小兵
  221. cap = cv2.VideoCapture('rtsp://admin:admin@192.168.50.182/av2_0')
  222. ret, frame = cap.read()
  223. while ret:
  224. # compress frame
  225. frame = cv2.resize(frame, (500, 400), interpolation=cv2.INTER_AREA)
  226. retval, buffer = cv2.imencode(".jpg", frame)
  227. if retval:
  228. # convert to byte array
  229. buffer = buffer.tobytes()
  230. # get size of the frame
  231. buffer_size = len(buffer)
  232. num_of_packs = 1
  233. if buffer_size > max_length:
  234. num_of_packs = math.ceil(buffer_size / max_length)
  235. frame_info = {"packs": num_of_packs}
  236. # send the number of packs to be expected
  237. print("Number of packs:", num_of_packs)
  238. sock.sendto(pickle.dumps(frame_info), (host, port))
  239. left = 0
  240. right = max_length
  241. for i in range(num_of_packs):
  242. print("left:", left)
  243. print("right:", right)
  244. # truncate data to send
  245. data = buffer[left:right]
  246. left = right
  247. right += max_length
  248. # send the frames accordingly
  249. sock.sendto(data, (host, port))
  250. ret, frame = cap.read()
  251. print("done")
  252. lock = threading.Lock()
  253. #影像串流的路徑
  254. @main.route ( "/video_feed", methods=['POST', 'GET'])
  255. def video_feed_views( ) :
  256. # 影像生成器函數,將影像以jpg格式傳給前端
  257. def generate():
  258. # lab1的IP
  259. host = "192.168.50.65"
  260. # lab2的IP
  261. # host = "192.168.51.161"
  262. port = 8000
  263. max_length = 65540
  264. # max_length = 95540
  265. sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
  266. sock.bind((host, port))
  267. frame_info = None
  268. buffer = None
  269. frame = None
  270. port8000_status = 1
  271. print("-> waiting for connection")
  272. while True:
  273. data, address = sock.recvfrom(max_length)
  274. if len(data) < 100:
  275. frame_info = pickle.loads(data)
  276. if frame_info:
  277. nums_of_packs = frame_info["packs"]
  278. for i in range(nums_of_packs):
  279. data, address = sock.recvfrom(max_length)
  280. if i == 0:
  281. buffer = data
  282. else:
  283. buffer += data
  284. frame = np.frombuffer(buffer, dtype=np.uint8)
  285. frame = frame.reshape(frame.shape[0], 1)
  286. frame = cv2.imdecode(frame, cv2.IMREAD_COLOR)
  287. frame = cv2.resize(frame, (1280, 720), interpolation=cv2.INTER_AREA)
  288. global lock
  289. with lock:
  290. if frame is None:
  291. continue
  292. # encode the frame in JPEG format
  293. (flag, encodedImage) = cv2.imencode(".jpg", frame)
  294. # ensure the frame was successfully encoded
  295. if not flag:
  296. continue
  297. # yield the output frame in the byte format
  298. yield (b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n' +
  299. bytearray(encodedImage) + b'\r\n')
  300. if request.method == 'GET':
  301. # return the response generated along with the specific media
  302. # type (mime type)
  303. return Response(generate ( ) ,mimetype = "multipart/x-mixed-replace; boundary=frame")
  304. else:
  305. pass