main.py 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085
  1. # fastapi
  2. from fastapi import FastAPI, Request, Response, HTTPException, status, Depends , Form
  3. from fastapi import templating
  4. from fastapi.templating import Jinja2Templates
  5. from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
  6. from fastapi.middleware.cors import CORSMiddleware
  7. from fastapi.staticfiles import StaticFiles
  8. # fastapi view function parameters
  9. from typing import List, Optional
  10. import json
  11. # path
  12. import sys
  13. from sqlalchemy.sql.elements import False_
  14. # time
  15. # import datetime
  16. from datetime import timedelta, datetime
  17. # db
  18. import dataset
  19. from passlib import context
  20. from sqlalchemy.sql.expression import true
  21. import models
  22. from random import randint,uniform
  23. # authorize
  24. from passlib.context import CryptContext
  25. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  26. import jwt
  27. from fastapi_jwt_auth import AuthJWT
  28. from fastapi_jwt_auth.exceptions import AuthJWTException
  29. from fastapi.security import OAuth2AuthorizationCodeBearer, OAuth2PasswordRequestForm
  30. import numpy as np
  31. import pymysql
  32. class dateEncode(json.JSONEncoder):
  33. def default(self, obj):
  34. if isinstance(obj, datetime):
  35. return obj.strftime('%Y-%m-%d %H:%M:%S')
  36. else:
  37. return json.JSONEncoder.default(self, obj)
  38. pymysql.install_as_MySQLdb()
  39. db_settings = {
  40. "host": "db.ptt.cx",
  41. "port": 3306,
  42. "user": "choozmo",
  43. "password": "pAssw0rd",
  44. "db": "Water_tower",
  45. "charset": "utf8mb4"
  46. }
  47. # app
  48. app = FastAPI()
  49. app.add_middleware(
  50. CORSMiddleware,
  51. allow_origins=["*"],
  52. allow_credentials=True,
  53. allow_methods=["*"],
  54. allow_headers=["*"],
  55. )
  56. SECRET_KEY = "df2f77bd544240801a048bd4293afd8eeb7fff3cb7050e42c791db4b83ebadcd"
  57. ALGORITHM = "HS256"
  58. ACCESS_TOKEN_EXPIRE_MINUTES = 3000
  59. pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
  60. #
  61. app.mount(path='/templates', app=StaticFiles(directory='templates'), name='templates')
  62. app.mount(path='/static', app=StaticFiles(directory='static'), name='static ')
  63. #
  64. templates = Jinja2Templates(directory='templates')
  65. @AuthJWT.load_config
  66. def get_config():
  67. return models.Settings()
  68. # view
  69. @app.get('/', response_class=HTMLResponse)
  70. async def index(request: Request):
  71. print(request)
  72. return templates.TemplateResponse(name='index.html', context={'request': request})
  73. @app.get('/login', response_class=HTMLResponse)
  74. async def login(request: Request):
  75. return templates.TemplateResponse(name='login.html', context={'request': request})
  76. @app.post("/login")
  77. async def login_for_access_token(request: Request, form_data: OAuth2PasswordRequestForm = Depends(), Authorize: AuthJWT = Depends()):
  78. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  79. user = authenticate_user(form_data.username, form_data.password)
  80. if not user:
  81. raise HTTPException(
  82. status_code=status.HTTP_401_UNAUTHORIZED,
  83. detail="Incorrect username or password",
  84. headers={"WWW-Authenticate": "Bearer"},
  85. )
  86. access_token_expires = timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
  87. access_token = create_access_token(
  88. data={"sub": user.username}, expires_delta=access_token_expires
  89. )
  90. table = db['users']
  91. user.token = access_token
  92. print(user)
  93. table.update(dict(user), ['username'],['password'])
  94. access_token = Authorize.create_access_token(subject=user.username)
  95. refresh_token = Authorize.create_refresh_token(subject=user.username)
  96. Authorize.set_access_cookies(access_token)
  97. Authorize.set_refresh_cookies(refresh_token)
  98. #return templates.TemplateResponse("home.html", {"request": request, "msg": 'Login'})
  99. return {"access_token": access_token, "token_type": "bearer"} # 回傳token給前端
  100. @app.get('/register', response_class=HTMLResponse)
  101. async def login(request: Request):
  102. return templates.TemplateResponse(name='rigister_test.html', context={'request': request})
  103. @app.post('/register')
  104. async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depends()):
  105. user = models.User(**await request.form())
  106. print(form_data.username, form_data.password, user)
  107. user.id = randint(1000, 9999)
  108. user.isAdmin = 0 #預設為非管理者
  109. user.roleType = 0 #預設為employee
  110. # 密碼加密
  111. #user.password = get_password_hash(user.password)
  112. # 存入DB
  113. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  114. user_table = db['users']
  115. user_table.insert(dict(user))
  116. # 跳轉頁面至登入
  117. return templates.TemplateResponse(name='login.html', context={'request': request})
  118. @app.get('/home', response_class=HTMLResponse)
  119. async def home(request: Request, Authorize: AuthJWT = Depends()):
  120. try:
  121. Authorize.jwt_required()
  122. except Exception as e:
  123. print(e)
  124. return RedirectResponse('/login')
  125. #add_data()
  126. return templates.TemplateResponse(name='home.html', context={'request': request})
  127. @app.get('/home/show', response_class=HTMLResponse)
  128. async def home(request: Request, Authorize: AuthJWT = Depends()):
  129. try:
  130. Authorize.jwt_required()
  131. except Exception as e:
  132. print(e)
  133. return RedirectResponse('/login')
  134. current_user = Authorize.get_jwt_subject()
  135. result = [{'user_role':check_role_type(current_user)}]
  136. result.append(check_tower_health(current_user))
  137. #print(result)
  138. return json.dumps(result,ensure_ascii=False)
  139. @app.get('/org', response_class=HTMLResponse)
  140. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  141. try:
  142. Authorize.jwt_required()
  143. except Exception as e:
  144. print(e)
  145. return RedirectResponse('/login')
  146. current_user = Authorize.get_jwt_subject()
  147. result = get_user_under_organization(current_user)
  148. return json.dumps(result,ensure_ascii=False)
  149. @app.get('/tower', response_class=HTMLResponse)
  150. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  151. try:
  152. Authorize.jwt_required()
  153. except Exception as e:
  154. print(e)
  155. return RedirectResponse('/login')
  156. current_user = Authorize.get_jwt_subject()
  157. result = get_user_under_organization(current_user)
  158. result.append({'Data' : get_tower_info('dev001')})
  159. return templates.TemplateResponse(name='tower.html', context={"request":request})
  160. @app.get('/tower/org', response_class=HTMLResponse)
  161. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  162. try:
  163. Authorize.jwt_required()
  164. except Exception as e:
  165. print(e)
  166. return RedirectResponse('/login')
  167. current_user = Authorize.get_jwt_subject()
  168. result = get_user_under_organization(current_user)
  169. return json.dumps(result,ensure_ascii=False)
  170. @app.get('/tower/', response_class=HTMLResponse)
  171. async def tower(request: Request,company:str,factory:str,department:str,towerGroup:str, Authorize: AuthJWT = Depends()):
  172. try:
  173. Authorize.jwt_required()
  174. except Exception as e:
  175. print(e)
  176. return RedirectResponse('/login')
  177. #current_user = Authorize.get_jwt_subject()
  178. tower_arr = get_tower(company,factory,department,towerGroup)
  179. result = []
  180. for tower in tower_arr:
  181. result.append({'tower_name': tower,'tower_data': get_tower_info(tower)})
  182. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  183. @app.get('/tower/performance/{tower_id}', response_class=HTMLResponse)
  184. async def member_authority(request:Request,tower_id: str,Authorize: AuthJWT = Depends()):
  185. """設定成員權限"""
  186. try:
  187. Authorize.jwt_required()
  188. except Exception as e:
  189. print(e)
  190. return RedirectResponse('/login')
  191. result = get_tower_perform(tower_id)
  192. print(result)
  193. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  194. @app.get('/optim', response_class=HTMLResponse)
  195. async def optim(request: Request, Authorize: AuthJWT = Depends()):
  196. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  197. statement = 'SELECT value FROM record_tower WHERE record_tower.key = "hotTemp"'
  198. x = 0
  199. y = 0
  200. z = 0
  201. count = 0
  202. waterflow = 0
  203. fannum = 0
  204. savewater = 0
  205. fanchange = 0
  206. saveelec = 0
  207. total = 0
  208. flowchange = 0
  209. for temp in db.query(statement):
  210. print(temp['value'])
  211. x=temp['value']
  212. statement2 = 'SELECT value FROM record_tower WHERE record_tower.key = "coldTempData2"'
  213. for temp2 in db.query(statement2):
  214. print(temp2['value'])
  215. y=temp2['value']
  216. statement3 = 'SELECT value FROM record_tower WHERE record_tower.key = "wetTemp"'
  217. for temp3 in db.query(statement3):
  218. print(temp3['value'])
  219. z=temp3['value']
  220. statement4 = 'SELECT value FROM record_tower WHERE record_tower.key = "count"'
  221. for tower in db.query(statement4):
  222. print(tower['value'])
  223. count=tower['value']
  224. statement5 = 'SELECT value FROM record_tower WHERE record_tower.key = "waterflow"'
  225. for tower in db.query(statement5):
  226. waterflow=tower['value']
  227. statement6 = 'SELECT value FROM record_tower WHERE record_tower.key = "fannum"'
  228. for tower in db.query(statement6):
  229. fannum=tower['value']
  230. statement7 = 'SELECT value FROM record_tower WHERE record_tower.key = "flowchange"'
  231. for tower in db.query(statement7):
  232. flowchange=tower['value']
  233. statement8 = 'SELECT value FROM record_tower WHERE record_tower.key = "savewater"'
  234. for tower in db.query(statement8):
  235. savewater=tower['value']
  236. statement9 = 'SELECT value FROM record_tower WHERE record_tower.key = "fanchange"'
  237. for tower in db.query(statement9):
  238. fanchange=tower['value']
  239. statement10 = 'SELECT value FROM record_tower WHERE record_tower.key = "saveelec"'
  240. for tower in db.query(statement10):
  241. saveelec=tower['value']
  242. statement11 = 'SELECT value FROM record_tower WHERE record_tower.key = "total"'
  243. for tower in db.query(statement11):
  244. total=tower['value']
  245. try:
  246. Authorize.jwt_required()
  247. except Exception as e:
  248. print(e)
  249. return RedirectResponse('/login')
  250. return templates.TemplateResponse(name='optim.html',context=
  251. {
  252. 'request': request,"x":x,"y":y,"z":z,"count":count,"waterflow":waterflow
  253. ,"fannum":fannum , "flowchange":flowchange , "savewater":savewater
  254. , "fanchange":fanchange , "saveelec":saveelec , "total":total
  255. })
  256. @app.get('/vibration', response_class=HTMLResponse)
  257. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  258. try:
  259. Authorize.jwt_required()
  260. except Exception as e:
  261. print(e)
  262. return RedirectResponse('/login')
  263. return templates.TemplateResponse(name='vibration_test.html', context={'request': request})
  264. @app.get('/channel', response_class=HTMLResponse)
  265. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  266. try:
  267. Authorize.jwt_required()
  268. except Exception as e:
  269. print(e)
  270. return RedirectResponse('/login')
  271. return templates.TemplateResponse(name='channel.html', context={'request': request})
  272. @app.get('/channel/{tower_id}/{channel_id}', response_class=HTMLResponse)
  273. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  274. try:
  275. Authorize.jwt_required()
  276. except Exception as e:
  277. print(e)
  278. return RedirectResponse('/login')
  279. print(find_vibration_id(tower_id,channel_id))
  280. result = get_channel_info(find_vibration_id(tower_id,channel_id))
  281. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  282. @app.get('/channel_chart/{tower_id}/{channel_id}', response_class=HTMLResponse)
  283. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  284. try:
  285. Authorize.jwt_required()
  286. except Exception as e:
  287. print(e)
  288. return RedirectResponse('/login')
  289. print(find_vibration_id(tower_id,channel_id))
  290. result = get_channel_health(find_vibration_id(tower_id,channel_id))
  291. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  292. @app.get('/channel_predict/{tower_id}/{channel_id}', response_class=HTMLResponse)
  293. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  294. try:
  295. Authorize.jwt_required()
  296. except Exception as e:
  297. print(e)
  298. return RedirectResponse('/login')
  299. #print(find_vibration_id(tower_id,channel_id))
  300. result = get_predect_data(find_vibration_id(tower_id,channel_id))
  301. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  302. @app.get('/channel_frequency/{tower_id}/{channel_id}', response_class=HTMLResponse)
  303. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  304. try:
  305. Authorize.jwt_required()
  306. except Exception as e:
  307. print(e)
  308. return RedirectResponse('/login')
  309. #print(find_vibration_id(tower_id,channel_id))
  310. result = get_frequency(find_vibration_id(tower_id,channel_id))
  311. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  312. @app.get('/history', response_class=HTMLResponse)
  313. async def history(request: Request, Authorize: AuthJWT = Depends()):
  314. try:
  315. Authorize.jwt_required()
  316. except Exception as e:
  317. print(e)
  318. return RedirectResponse('/login')
  319. # current_user = Authorize.get_jwt_subject()
  320. return templates.TemplateResponse(name='history.html', context={'request': request})
  321. @app.get('/device', response_class=HTMLResponse)
  322. async def device(request: Request, Authorize: AuthJWT = Depends()):
  323. try:
  324. Authorize.jwt_required()
  325. except Exception as e:
  326. print(e)
  327. return RedirectResponse('/login')
  328. # current_user = Authorize.get_jwt_subject()
  329. return templates.TemplateResponse(name='device.html', context={'request': request})
  330. @app.get('/system', response_class=HTMLResponse)
  331. async def system(request: Request, Authorize: AuthJWT = Depends()):
  332. try:
  333. Authorize.jwt_required()
  334. except Exception as e:
  335. print(e)
  336. return RedirectResponse('/login')
  337. # current_user = Authorize.get_jwt_subject()
  338. return templates.TemplateResponse(name='system.html', context={'request': request})
  339. @app.get('/member', response_class=HTMLResponse)
  340. async def get_member(request: Request, Authorize: AuthJWT = Depends()):
  341. """獲取所有帳號資訊"""
  342. try:
  343. Authorize.jwt_required()
  344. except Exception as e:
  345. print(e)
  346. return RedirectResponse('/login')
  347. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  348. statement = 'SELECT id,username,isAdmin FROM users'
  349. json_dic = []
  350. for row in db.query(statement):
  351. #print(row['id'],row['username'])
  352. json_dic.append({'username':row['username'],'isAdmin':row['isAdmin'],'roleType':check_role_type(row['username']),'role_name' :get_role_name(check_role_type(row['username']))})
  353. result = json.dumps(json_dic,ensure_ascii=False)
  354. return result
  355. @app.get('/member/edit/', response_class=HTMLResponse)
  356. async def login(request: Request, name:str,isAdmin:int,isEnable:int ,Authorize: AuthJWT = Depends()):
  357. try:
  358. Authorize.jwt_required()
  359. except Exception as e:
  360. print(e)
  361. return RedirectResponse('/login')
  362. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  363. current_user = Authorize.get_jwt_subject()
  364. current_user_roleType = check_role_type(current_user)
  365. del_user_roleType = check_role_type(name)
  366. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  367. for row in db.query(statement):
  368. if row['isAdmin']!=1:
  369. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  370. if del_user_roleType == None:
  371. return json.dumps([{'msg':'不存在使用者'}],ensure_ascii=False)
  372. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  373. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  374. user_dic = get_user(name)
  375. print(user_dic)
  376. user_dic.isAdmin = isAdmin
  377. user_dic.isEnable = isEnable
  378. table = db['users']
  379. table.update(dict(user_dic), ['username'])
  380. return json.dumps([{'msg':"成功更改"}],ensure_ascii=False)
  381. @app.get('/member_delete', response_class=HTMLResponse)
  382. async def login(request: Request, Authorize: AuthJWT = Depends()):
  383. try:
  384. Authorize.jwt_required()
  385. except Exception as e:
  386. print(e)
  387. return RedirectResponse('/login')
  388. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  389. @app.post('/member_delete')
  390. async def delete_member(request: Request):
  391. """刪除成員"""
  392. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  393. del_user = models.del_user(**await request.form())
  394. delete_name = del_user.del_name
  395. statement = 'SELECT * FROM users'
  396. current_user = ''
  397. for row in db.query(statement):
  398. if row['token'] != None :
  399. if compare_jwt_token(row['token'],del_user.access_token):
  400. current_user = row['username']
  401. if current_user == '':
  402. return {'msg':'尚未登入'}
  403. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  404. for row in db.query(statement):
  405. if row['isAdmin']!=1:
  406. return {'msg': ' 你沒有權限'}
  407. current_user_roleType = check_role_type(current_user)
  408. del_user_roleType = check_role_type(delete_name)
  409. if del_user_roleType == None:
  410. return {'msg':'不存在使用者'}
  411. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  412. return {'msg': ' 你沒有權限'}
  413. else :
  414. table = db['users']
  415. table.delete(username=delete_name)
  416. return {'msg': ' 成功刪除'}
  417. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  418. async def member_authority(request:Request,edit_one: int,Authorize: AuthJWT = Depends()):
  419. """設定成員權限"""
  420. try:
  421. Authorize.jwt_required()
  422. except Exception as e:
  423. print(e)
  424. return RedirectResponse('/login')
  425. context = {'request': request}
  426. current_user = Authorize.get_jwt_subject()
  427. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  428. statement = check_isAdmin(current_user)
  429. if statement == "no user":
  430. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no user' })
  431. elif statement == 0:
  432. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  433. current_user_roleType = check_role_type(current_user)
  434. if edit_one == None:
  435. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no role' })
  436. elif int(current_user_roleType)>int(edit_one) or int(current_user_roleType)==int(edit_one):
  437. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  438. result = check_role_acl(edit_one)
  439. if result == []:
  440. cmd = 'SELECT id FROM module'
  441. for row in db.query(cmd):
  442. dic_tmp = {'id':0,'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : edit_one}
  443. context[get_modul_name(row['id']) ] = dic_tmp
  444. else:
  445. for dic in result:
  446. modul_name = get_modul_name(dic['module_id'])
  447. del dic['module_id']
  448. context[modul_name ] = dic
  449. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  450. @app.post('/member_authority')
  451. async def member_authority(request: Request):
  452. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  453. edit_one = models.user_authority(**await request.form())
  454. statement = 'SELECT * FROM users'
  455. current_user = ''
  456. for row in db.query(statement):
  457. if row['token'] != None :
  458. if compare_jwt_token(row['token'],edit_one.access_token):
  459. current_user = row['username']
  460. if current_user == '':
  461. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'尚未登入'})
  462. statement = check_isAdmin(current_user)
  463. if statement == "no user":
  464. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':statement })
  465. elif statement == 0:
  466. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'你沒有權限' })
  467. current_user_roleType = check_role_type(current_user)
  468. edit_one_roleType = edit_one.role_id
  469. if current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  470. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': ' 你沒有權限'})
  471. else :
  472. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  473. if check_role_acl(edit_one.role_id) == []:
  474. for module in row :
  475. new_dict = edit_one.get_acl_from_module_name(module)
  476. new_dict["id"]= None
  477. table = db['role_acl']
  478. table.insert(new_dict)
  479. else:
  480. for module in row :
  481. new_dict = edit_one.get_acl_from_module_name(module)
  482. table = db['role_acl']
  483. table.update(new_dict, ['id'])
  484. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': '成功更改權限'})
  485. # 溫度API
  486. @app.get('/temperature')
  487. async def get_temperatures():
  488. """ 撈DB溫度 """
  489. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  490. @app.post("/example")
  491. async def example(request: Request,Authorize: AuthJWT = Depends()):
  492. try:
  493. Authorize.jwt_required()
  494. except Exception as e:
  495. print(e)
  496. current_user = Authorize.get_jwt_subject()
  497. #form_data = await request.form()
  498. print( current_user)
  499. return current_user
  500. @app.post('/user')
  501. def user(Authorize: AuthJWT = Depends()):
  502. Authorize.jwt_required()
  503. current_user = Authorize.get_jwt_subject()
  504. return {"user": current_user}
  505. @app.get("/add_data", response_class=HTMLResponse)
  506. async def example(request: Request,Authorize: AuthJWT = Depends()):
  507. try:
  508. Authorize.jwt_required()
  509. except Exception as e:
  510. print(e)
  511. return RedirectResponse('/login')
  512. add_data()
  513. return templates.TemplateResponse(name='test.html', context={'request': request})
  514. @app.get('/health')
  515. async def get_health(date: str):
  516. """ 撈健康指標、預設健康指標 """
  517. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  518. print(date)
  519. print(str(datetime.today()))
  520. print(str(datetime.today()-timedelta(days=1)))
  521. fake_data = {
  522. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  523. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  524. }
  525. return fake_data[date]
  526. @app.get('/history_data')
  527. async def get_history(time_end: str):
  528. """ 透過終點時間,抓取歷史資料。 """
  529. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  530. print(date)
  531. print(str(datetime.today()))
  532. print(str(datetime.today()-timedelta(days=1)))
  533. fake_data = {
  534. str(datetime.today())[:10]: {
  535. 'curr_history': {
  536. 'RPM_1X': list(np.random.rand(13)),
  537. 'RPM_2X': list(np.random.rand(13)),
  538. 'RPM_3X': list(np.random.rand(13)),
  539. 'RPM_4X': list(np.random.rand(13)),
  540. 'RPM_5X': list(np.random.rand(13)),
  541. 'RPM_6X': list(np.random.rand(13)),
  542. 'RPM_7X': list(np.random.rand(13)),
  543. 'RPM_8X': list(np.random.rand(13)),
  544. 'Gear_1X': list(np.random.rand(13)),
  545. 'Gear_2X': list(np.random.rand(13)),
  546. 'Gear_3X': list(np.random.rand(13)),
  547. 'Gear_4X': list(np.random.rand(13)),
  548. },
  549. 'past_history': {
  550. 'RPM_1X': list(np.random.rand(13)),
  551. 'RPM_2X': list(np.random.rand(13)),
  552. 'RPM_3X': list(np.random.rand(13)),
  553. 'RPM_4X': list(np.random.rand(13)),
  554. 'RPM_5X': list(np.random.rand(13)),
  555. 'RPM_6X': list(np.random.rand(13)),
  556. 'RPM_7X': list(np.random.rand(13)),
  557. 'RPM_8X': list(np.random.rand(13)),
  558. 'Gear_1X': list(np.random.rand(13)),
  559. 'Gear_2X': list(np.random.rand(13)),
  560. 'Gear_3X': list(np.random.rand(13)),
  561. 'Gear_4X': list(np.random.rand(13)),
  562. }
  563. },
  564. str(datetime.today()-timedelta(days=1))[:10]: {
  565. 'curr_history': {
  566. 'RPM_1X': list(np.random.rand(13)),
  567. 'RPM_2X': list(np.random.rand(13)),
  568. 'RPM_3X': list(np.random.rand(13)),
  569. 'RPM_4X': list(np.random.rand(13)),
  570. 'RPM_5X': list(np.random.rand(13)),
  571. 'RPM_6X': list(np.random.rand(13)),
  572. 'RPM_7X': list(np.random.rand(13)),
  573. 'RPM_8X': list(np.random.rand(13)),
  574. 'Gear_1X': list(np.random.rand(13)),
  575. 'Gear_2X': list(np.random.rand(13)),
  576. 'Gear_3X': list(np.random.rand(13)),
  577. 'Gear_4X': list(np.random.rand(13)),
  578. },
  579. 'past_history': {
  580. 'RPM_1X': list(np.random.rand(13)),
  581. 'RPM_2X': list(np.random.rand(13)),
  582. 'RPM_3X': list(np.random.rand(13)),
  583. 'RPM_4X': list(np.random.rand(13)),
  584. 'RPM_5X': list(np.random.rand(13)),
  585. 'RPM_6X': list(np.random.rand(13)),
  586. 'RPM_7X': list(np.random.rand(13)),
  587. 'RPM_8X': list(np.random.rand(13)),
  588. 'Gear_1X': list(np.random.rand(13)),
  589. 'Gear_2X': list(np.random.rand(13)),
  590. 'Gear_3X': list(np.random.rand(13)),
  591. 'Gear_4X': list(np.random.rand(13)),
  592. }
  593. },
  594. }
  595. return fake_data[date]
  596. # Login funtion part
  597. def check_user_exists(username):
  598. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  599. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  600. return True
  601. else:
  602. return False
  603. def get_user(username: str):
  604. """ 取得使用者資訊(Model) """
  605. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  606. if not check_user_exists(username): # if user don't exist
  607. return False
  608. user_dict = next(
  609. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  610. user = models.User(**user_dict)
  611. return user
  612. def user_register(user):
  613. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  614. table = db['users']
  615. #user.password = get_password_hash(user.password)
  616. table.insert(dict(user))
  617. def get_password_hash(password):
  618. """ 加密密碼 """
  619. return pwd_context.hash(password)
  620. def verify_password(plain_password, hashed_password):
  621. """ 驗證密碼(hashed) """
  622. return pwd_context.verify(plain_password, hashed_password)
  623. def authenticate_user(username: str, password: str):
  624. """ 連線DB,讀取使用者是否存在。 """
  625. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  626. if not check_user_exists(username): # if user don't exist
  627. return False
  628. if not check_user_isEnable(username):
  629. return False
  630. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  631. user = models.User(**user_dict)
  632. #if not verify_password(password, user.password):
  633. #return False
  634. return user
  635. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  636. """ 創建token,並設定過期時間。 """
  637. to_encode = data.copy()
  638. if expires_delta:
  639. expire = datetime.utcnow() + expires_delta
  640. else:
  641. expire = datetime.utcnow() + timedelta(minutes=15)
  642. to_encode.update({"exp": expire})
  643. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  644. return encoded_jwt
  645. def compare_jwt_token(access_token: str, token: str):
  646. """比對jwt token"""
  647. if len(access_token) < len(token):
  648. if access_token in token:
  649. return True
  650. else :
  651. return False
  652. elif len(access_token) > len(token):
  653. if token in access_token:
  654. return True
  655. else :
  656. return False
  657. else :
  658. if token == access_token:
  659. return True
  660. else :
  661. return False
  662. def check_isAdmin(user_name:str):
  663. """查看是否為管理員"""
  664. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  665. isAdmin = None
  666. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  667. for row in db.query(cmd) :
  668. isAdmin = row['isAdmin']
  669. if isAdmin== None:
  670. return "no user"
  671. return isAdmin
  672. def check_role_type(user_name:str)->int:
  673. """查看使用者權限"""
  674. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  675. cmd = 'SELECT user_role.role_id FROM `users` JOIN `user_role` ON `users`.id = `user_role`.user_id where `users`.username = "'+user_name+'"'
  676. role_type = None
  677. for row in db.query(cmd) :
  678. role_type = row['role_id']
  679. return role_type
  680. def check_role_acl(role:int):
  681. """查看權限"""
  682. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  683. cmd = 'SELECT * FROM role_acl where role_id = '+str(role)
  684. result = []
  685. for row in db.query(cmd) :
  686. dic ={}
  687. for col_name in db['role_acl'].columns:
  688. dic[col_name] = row[col_name]
  689. if dic != {}:
  690. result.append(dic)
  691. return result
  692. def get_role_name(role_id:int):
  693. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  694. cmd = 'SELECT * FROM role where id = '+str(role_id)
  695. role:str
  696. for row in db.query(cmd) :
  697. role = row['name']
  698. return role
  699. def check_user_isEnable(user_name:str)->bool:
  700. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  701. cmd = 'SELECT isEnable FROM users where username = "'+str(user_name)+'"'
  702. able:bool
  703. for row in db.query(cmd) :
  704. able = row['isEnable']
  705. return able
  706. def get_user_under_organization(user_name:str):
  707. """查看所屬公司"""
  708. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  709. user_role = check_role_type(user_name)
  710. print(user_name,user_role)
  711. cmd = 'SELECT * FROM organization'
  712. result = []
  713. if int(user_role) == 1 :
  714. for row in db.query(cmd) :
  715. company = row['Company']
  716. factory = row['Factory']
  717. department = row['Department']
  718. cmd2 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  719. group = []
  720. for row2 in db.query(cmd2):
  721. if row2['TowerGroupCode'] not in group :
  722. group.append(row2['TowerGroupCode'])
  723. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  724. elif int(user_role) == 2:
  725. cmd2 = 'SELECT company FROM user WHERE user.username ="'+user_name +'"'
  726. company_able:str
  727. for row in db.query(cmd2) :
  728. company_able = row['company']
  729. for row in db.query(cmd) :
  730. company = row['Company']
  731. factory = row['Factory']
  732. department = row['Department']
  733. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  734. group = []
  735. for row2 in db.query(cmd3):
  736. if row2['TowerGroupCode'] not in group :
  737. group.append(row2['TowerGroupCode'])
  738. if company == company_able:
  739. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  740. else:
  741. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  742. elif int(user_role) == 3:
  743. cmd2 = 'SELECT company,factory FROM users WHERE users.username = "'+user_name +'"'
  744. company_able:str
  745. factory_able:str
  746. num = 0
  747. for row in db.query(cmd2) :
  748. company_able = row['company']
  749. factory_able = row['factory']
  750. for row in db.query(cmd) :
  751. company = row['Company']
  752. factory = row['Factory']
  753. department = row['Department']
  754. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  755. group = []
  756. for row2 in db.query(cmd3):
  757. if row2['TowerGroupCode'] not in group :
  758. group.append(row2['TowerGroupCode'])
  759. if company == company_able and factory==factory_able:
  760. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  761. else:
  762. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  763. elif int(user_role) == 4:
  764. cmd2 = 'SELECT company,factory,department FROM users WHERE username = "'+user_name +'"'
  765. company_able:str
  766. factory_able:str
  767. department_able:str
  768. for row in db.query(cmd2) :
  769. company_able = row['company']
  770. factory_able = row['factory']
  771. department_able = row['department']
  772. for row in db.query(cmd) :
  773. company = row['Company']
  774. factory = row['Factory']
  775. department = row['Department']
  776. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  777. group = []
  778. for row2 in db.query(cmd3):
  779. if row2['TowerGroupCode'] not in group :
  780. group.append(row2['TowerGroupCode'])
  781. if company == company_able and factory==factory_able and department==department_able:
  782. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  783. else:
  784. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  785. else :
  786. result =[ {'msg':"error"}]
  787. return result
  788. def get_user_id(user_name:str):
  789. """獲取user id"""
  790. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  791. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  792. id = None
  793. for row in db.query(cmd) :
  794. id = row['id']
  795. return id
  796. def get_user_name(user_id:int):
  797. """獲取user name"""
  798. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  799. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  800. id = None
  801. for row in db.query(cmd) :
  802. id = row['username']
  803. return id
  804. def get_modul_name(modul_id:str):
  805. """獲取modul名稱"""
  806. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  807. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  808. modul_name = None
  809. for row in db.query(cmd) :
  810. modul_name = row['moduleName']
  811. return modul_name
  812. def get_tower_info(tower_id:str):
  813. """獲取水塔資料"""
  814. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  815. cmd = 'SELECT * FROM `record_dcs` where device_id = "'+tower_id+'"'
  816. result ={'DCS':{},'Fan':{},'Moter':{},'Device_info':{}}
  817. for row in db.query(cmd) :
  818. result['DCS'][row['key']]=row['value']
  819. cmd = 'SELECT * FROM `record_tower` where device_id = "'+tower_id+'"'
  820. for row in db.query(cmd) :
  821. result['Fan'][row['key']]=row['value']
  822. result['Moter'] = []
  823. cmd = 'SELECT * FROM `vibration` where device_id = "'+tower_id+'"'
  824. tmp = {}
  825. for row in db.query(cmd) :
  826. for col in db['vibration'].columns :
  827. tmp[col] = row[col]
  828. result['Moter'].append(tmp)
  829. tmp = {}
  830. cmd = 'SELECT * FROM `device` where id = "'+tower_id+'"'
  831. for row in db.query(cmd):
  832. for col in db['device'].columns :
  833. if col != 'createTime':
  834. result['Device_info'][col] = row[col]
  835. return result
  836. def get_tower_perform(tower_id:str):
  837. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  838. cmd = 'SELECT * FROM `record_performance` where deviceCode = "'+tower_id+'" AND designWFR = 27000'
  839. result = [{}]
  840. for row in db.query(cmd):
  841. for col in db['record_performance'].columns :
  842. if col != 'createTime':
  843. result[0][col] = row[col]
  844. #print(result)
  845. return result
  846. def get_tower(company:str,factory:str,department:str,towerGroup:str):
  847. towergroup_arr =[]
  848. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  849. cmd = 'SELECT id FROM `device` where CompanyCode = "'+company+'" AND FactoryCode = "' +factory+'" AND DepartmentCode = "'+department+'" AND TowerGroupCode = "' + towerGroup + '"'
  850. for row in db.query(cmd) :
  851. towergroup_arr.append(row['id'])
  852. return towergroup_arr
  853. def check_tower_health(user_name:str):
  854. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  855. org = get_user_under_organization(user_name)
  856. #print(org)
  857. towers : list
  858. result = []
  859. for dic in org:
  860. #print(dic)
  861. if dic['able'] == 1:
  862. for group in dic['group']:
  863. towers = get_tower(dic['company'],dic['factory'],dic['department'],group)
  864. for tower in towers:
  865. cmd = 'SELECT CVIndex,threshold FROM `vibration` where device_id = "'+tower+'"'
  866. health =1
  867. for row in db.query(cmd) :
  868. if int(row['CVIndex']) < int(row['threshold']):
  869. health = 0
  870. result.append({'company':dic['company'], 'factory':dic['factory'], 'department':dic['department'], 'group': group, 'tower': tower, 'health': health})
  871. return result
  872. def find_vibration_id(tower_id:str,channel_id:str):
  873. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  874. cmd = 'SELECT id FROM `vibration` where device_id = "'+tower_id+'" AND channelName = "' +channel_id+'"'
  875. for row in db.query(cmd) :
  876. return row['id']
  877. def get_channel_info(vibration_id):
  878. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  879. cmd = 'SELECT * FROM `record_diagnosis` where vibration_id = "'+vibration_id+'"'
  880. result = {}
  881. for row in db.query(cmd) :
  882. for col in db['record_diagnosis'].columns :
  883. result[col] = row[col]
  884. cmd2='SELECT CVIndex,threshold FROM `vibration` where id = "'+vibration_id+'"'
  885. for row2 in db.query(cmd2) :
  886. result['CVIndex'] = row2['CVIndex']
  887. result['threshold'] = row2['threshold']
  888. print(result)
  889. return result
  890. def get_channel_health(vibration_id:str):
  891. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  892. result = []
  893. data_name = ['CV_index', 'Vrms' ,'RPM']
  894. for row in data_name:
  895. result.append({'name':row,'data':[]})
  896. cmd = 'SELECT * FROM record_health where vibration_id = "'+vibration_id+'"'
  897. for row in db.query(cmd) :
  898. for dic in result:
  899. dic['data'].append(row[dic['name']])
  900. return result
  901. def get_predect_data(vibration_id:str):
  902. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  903. result = {}
  904. cmd = 'SELECT * FROM record_prediction_upd where vibration_id = "'+vibration_id+'"'
  905. for row in db.query(cmd) :
  906. arr = row['predictData'].split(',')
  907. result['data']=arr
  908. return result
  909. def get_frequency(vibration_id:str):
  910. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  911. result = {'Hz':[],'value':[]}
  912. print(vibration_id)
  913. cmd = 'SELECT * FROM record_frequency where vibration_id = "'+vibration_id+'"'
  914. for row in db.query(cmd) :
  915. result['Hz'].append(row['MFHz'])
  916. result['value'].append(row['MFValue'])
  917. return result
  918. def add_data():
  919. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  920. loc_dt = datetime.today()
  921. loc_dt_format = loc_dt.strftime("%Y-%m-%d %H:%M:%S")
  922. cmd = "TRUNCATE TABLE record_health"
  923. db.query(cmd)
  924. for j in range(1,5):
  925. for i in range(0,7):
  926. time_del = timedelta(days=i)
  927. date=loc_dt-time_del
  928. db['record_health'].insert(dict(time_stamp=date, CV_index=uniform(0.6, 0.8), Vrms=uniform(1,3),Grms = uniform(1,3),RPM=uniform(1,3),vibration_id = j))
  929. cmd = "TRUNCATE TABLE record_frequency"
  930. db.query(cmd)
  931. for i in range(0,5000):
  932. print(i)
  933. db['record_frequency'].insert(dict(time_stamp=loc_dt_format, MFHz=i, MFValue=uniform(0,0.12),vibration_id = 1))