main.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051
  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. for temp in db.query(statement):
  203. print(temp['value'])
  204. x=temp['value']
  205. statement2 = 'SELECT value FROM record_tower WHERE record_tower.key = "coldTempData2"'
  206. for temp2 in db.query(statement2):
  207. print(temp2['value'])
  208. y=temp2['value']
  209. statement3 = 'SELECT value FROM record_tower WHERE record_tower.key = "wetTemp"'
  210. for temp3 in db.query(statement3):
  211. print(temp3['value'])
  212. z=temp3['value']
  213. statement4 = 'SELECT value FROM record_tower WHERE record_tower.key = "count"'
  214. for tower in db.query(statement4):
  215. print(tower['value'])
  216. count=tower['value']
  217. try:
  218. Authorize.jwt_required()
  219. except Exception as e:
  220. print(e)
  221. return RedirectResponse('/login')
  222. return templates.TemplateResponse(name='optim.html',context={'request': request,"x":x,"y":y,"z":z,"count":count})
  223. @app.get('/vibration', response_class=HTMLResponse)
  224. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  225. try:
  226. Authorize.jwt_required()
  227. except Exception as e:
  228. print(e)
  229. return RedirectResponse('/login')
  230. return templates.TemplateResponse(name='vibration_test.html', context={'request': request})
  231. @app.get('/channel', response_class=HTMLResponse)
  232. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  233. try:
  234. Authorize.jwt_required()
  235. except Exception as e:
  236. print(e)
  237. return RedirectResponse('/login')
  238. return templates.TemplateResponse(name='channel.html', context={'request': request})
  239. @app.get('/channel/{tower_id}/{channel_id}', response_class=HTMLResponse)
  240. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  241. try:
  242. Authorize.jwt_required()
  243. except Exception as e:
  244. print(e)
  245. return RedirectResponse('/login')
  246. print(find_vibration_id(tower_id,channel_id))
  247. result = get_channel_info(find_vibration_id(tower_id,channel_id))
  248. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  249. @app.get('/channel_chart/{tower_id}/{channel_id}', response_class=HTMLResponse)
  250. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  251. try:
  252. Authorize.jwt_required()
  253. except Exception as e:
  254. print(e)
  255. return RedirectResponse('/login')
  256. print(find_vibration_id(tower_id,channel_id))
  257. result = get_channel_health(find_vibration_id(tower_id,channel_id))
  258. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  259. @app.get('/channel_predict/{tower_id}/{channel_id}', response_class=HTMLResponse)
  260. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  261. try:
  262. Authorize.jwt_required()
  263. except Exception as e:
  264. print(e)
  265. return RedirectResponse('/login')
  266. #print(find_vibration_id(tower_id,channel_id))
  267. result = get_predect_data(find_vibration_id(tower_id,channel_id))
  268. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  269. @app.get('/channel_frequency/{tower_id}/{channel_id}', response_class=HTMLResponse)
  270. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  271. try:
  272. Authorize.jwt_required()
  273. except Exception as e:
  274. print(e)
  275. return RedirectResponse('/login')
  276. #print(find_vibration_id(tower_id,channel_id))
  277. result = get_frequency(find_vibration_id(tower_id,channel_id))
  278. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  279. @app.get('/history', response_class=HTMLResponse)
  280. async def history(request: Request, Authorize: AuthJWT = Depends()):
  281. try:
  282. Authorize.jwt_required()
  283. except Exception as e:
  284. print(e)
  285. return RedirectResponse('/login')
  286. # current_user = Authorize.get_jwt_subject()
  287. return templates.TemplateResponse(name='history.html', context={'request': request})
  288. @app.get('/device', response_class=HTMLResponse)
  289. async def device(request: Request, Authorize: AuthJWT = Depends()):
  290. try:
  291. Authorize.jwt_required()
  292. except Exception as e:
  293. print(e)
  294. return RedirectResponse('/login')
  295. # current_user = Authorize.get_jwt_subject()
  296. return templates.TemplateResponse(name='device.html', context={'request': request})
  297. @app.get('/system', response_class=HTMLResponse)
  298. async def system(request: Request, Authorize: AuthJWT = Depends()):
  299. try:
  300. Authorize.jwt_required()
  301. except Exception as e:
  302. print(e)
  303. return RedirectResponse('/login')
  304. # current_user = Authorize.get_jwt_subject()
  305. return templates.TemplateResponse(name='system.html', context={'request': request})
  306. @app.get('/member', response_class=HTMLResponse)
  307. async def get_member(request: Request, Authorize: AuthJWT = Depends()):
  308. """獲取所有帳號資訊"""
  309. try:
  310. Authorize.jwt_required()
  311. except Exception as e:
  312. print(e)
  313. return RedirectResponse('/login')
  314. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  315. statement = 'SELECT id,username,isAdmin FROM users'
  316. json_dic = []
  317. for row in db.query(statement):
  318. #print(row['id'],row['username'])
  319. 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']))})
  320. result = json.dumps(json_dic,ensure_ascii=False)
  321. return result
  322. @app.get('/member/edit/', response_class=HTMLResponse)
  323. async def login(request: Request, name:str,isAdmin:int,isEnable:int ,Authorize: AuthJWT = Depends()):
  324. try:
  325. Authorize.jwt_required()
  326. except Exception as e:
  327. print(e)
  328. return RedirectResponse('/login')
  329. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  330. current_user = Authorize.get_jwt_subject()
  331. current_user_roleType = check_role_type(current_user)
  332. del_user_roleType = check_role_type(name)
  333. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  334. for row in db.query(statement):
  335. if row['isAdmin']!=1:
  336. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  337. if del_user_roleType == None:
  338. return json.dumps([{'msg':'不存在使用者'}],ensure_ascii=False)
  339. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  340. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  341. user_dic = get_user(name)
  342. print(user_dic)
  343. user_dic.isAdmin = isAdmin
  344. user_dic.isEnable = isEnable
  345. table = db['users']
  346. table.update(dict(user_dic), ['username'])
  347. return json.dumps([{'msg':"成功更改"}],ensure_ascii=False)
  348. @app.get('/member_delete', response_class=HTMLResponse)
  349. async def login(request: Request, Authorize: AuthJWT = Depends()):
  350. try:
  351. Authorize.jwt_required()
  352. except Exception as e:
  353. print(e)
  354. return RedirectResponse('/login')
  355. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  356. @app.post('/member_delete')
  357. async def delete_member(request: Request):
  358. """刪除成員"""
  359. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  360. del_user = models.del_user(**await request.form())
  361. delete_name = del_user.del_name
  362. statement = 'SELECT * FROM users'
  363. current_user = ''
  364. for row in db.query(statement):
  365. if row['token'] != None :
  366. if compare_jwt_token(row['token'],del_user.access_token):
  367. current_user = row['username']
  368. if current_user == '':
  369. return {'msg':'尚未登入'}
  370. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  371. for row in db.query(statement):
  372. if row['isAdmin']!=1:
  373. return {'msg': ' 你沒有權限'}
  374. current_user_roleType = check_role_type(current_user)
  375. del_user_roleType = check_role_type(delete_name)
  376. if del_user_roleType == None:
  377. return {'msg':'不存在使用者'}
  378. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  379. return {'msg': ' 你沒有權限'}
  380. else :
  381. table = db['users']
  382. table.delete(username=delete_name)
  383. return {'msg': ' 成功刪除'}
  384. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  385. async def member_authority(request:Request,edit_one: int,Authorize: AuthJWT = Depends()):
  386. """設定成員權限"""
  387. try:
  388. Authorize.jwt_required()
  389. except Exception as e:
  390. print(e)
  391. return RedirectResponse('/login')
  392. context = {'request': request}
  393. current_user = Authorize.get_jwt_subject()
  394. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  395. statement = check_isAdmin(current_user)
  396. if statement == "no user":
  397. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no user' })
  398. elif statement == 0:
  399. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  400. current_user_roleType = check_role_type(current_user)
  401. if edit_one == None:
  402. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no role' })
  403. elif int(current_user_roleType)>int(edit_one) or int(current_user_roleType)==int(edit_one):
  404. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  405. result = check_role_acl(edit_one)
  406. if result == []:
  407. cmd = 'SELECT id FROM module'
  408. for row in db.query(cmd):
  409. dic_tmp = {'id':0,'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : edit_one}
  410. context[get_modul_name(row['id']) ] = dic_tmp
  411. else:
  412. for dic in result:
  413. modul_name = get_modul_name(dic['module_id'])
  414. del dic['module_id']
  415. context[modul_name ] = dic
  416. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  417. @app.post('/member_authority')
  418. async def member_authority(request: Request):
  419. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  420. edit_one = models.user_authority(**await request.form())
  421. statement = 'SELECT * FROM users'
  422. current_user = ''
  423. for row in db.query(statement):
  424. if row['token'] != None :
  425. if compare_jwt_token(row['token'],edit_one.access_token):
  426. current_user = row['username']
  427. if current_user == '':
  428. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'尚未登入'})
  429. statement = check_isAdmin(current_user)
  430. if statement == "no user":
  431. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':statement })
  432. elif statement == 0:
  433. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'你沒有權限' })
  434. current_user_roleType = check_role_type(current_user)
  435. edit_one_roleType = edit_one.role_id
  436. if current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  437. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': ' 你沒有權限'})
  438. else :
  439. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  440. if check_role_acl(edit_one.role_id) == []:
  441. for module in row :
  442. new_dict = edit_one.get_acl_from_module_name(module)
  443. new_dict["id"]= None
  444. table = db['role_acl']
  445. table.insert(new_dict)
  446. else:
  447. for module in row :
  448. new_dict = edit_one.get_acl_from_module_name(module)
  449. table = db['role_acl']
  450. table.update(new_dict, ['id'])
  451. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': '成功更改權限'})
  452. # 溫度API
  453. @app.get('/temperature')
  454. async def get_temperatures():
  455. """ 撈DB溫度 """
  456. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  457. @app.post("/example")
  458. async def example(request: Request,Authorize: AuthJWT = Depends()):
  459. try:
  460. Authorize.jwt_required()
  461. except Exception as e:
  462. print(e)
  463. current_user = Authorize.get_jwt_subject()
  464. #form_data = await request.form()
  465. print( current_user)
  466. return current_user
  467. @app.post('/user')
  468. def user(Authorize: AuthJWT = Depends()):
  469. Authorize.jwt_required()
  470. current_user = Authorize.get_jwt_subject()
  471. return {"user": current_user}
  472. @app.get("/add_data", response_class=HTMLResponse)
  473. async def example(request: Request,Authorize: AuthJWT = Depends()):
  474. try:
  475. Authorize.jwt_required()
  476. except Exception as e:
  477. print(e)
  478. return RedirectResponse('/login')
  479. add_data()
  480. return templates.TemplateResponse(name='test.html', context={'request': request})
  481. @app.get('/health')
  482. async def get_health(date: str):
  483. """ 撈健康指標、預設健康指標 """
  484. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  485. print(date)
  486. print(str(datetime.today()))
  487. print(str(datetime.today()-timedelta(days=1)))
  488. fake_data = {
  489. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  490. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  491. }
  492. return fake_data[date]
  493. @app.get('/history_data')
  494. async def get_history(time_end: str):
  495. """ 透過終點時間,抓取歷史資料。 """
  496. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  497. print(date)
  498. print(str(datetime.today()))
  499. print(str(datetime.today()-timedelta(days=1)))
  500. fake_data = {
  501. str(datetime.today())[:10]: {
  502. 'curr_history': {
  503. 'RPM_1X': list(np.random.rand(13)),
  504. 'RPM_2X': list(np.random.rand(13)),
  505. 'RPM_3X': list(np.random.rand(13)),
  506. 'RPM_4X': list(np.random.rand(13)),
  507. 'RPM_5X': list(np.random.rand(13)),
  508. 'RPM_6X': list(np.random.rand(13)),
  509. 'RPM_7X': list(np.random.rand(13)),
  510. 'RPM_8X': list(np.random.rand(13)),
  511. 'Gear_1X': list(np.random.rand(13)),
  512. 'Gear_2X': list(np.random.rand(13)),
  513. 'Gear_3X': list(np.random.rand(13)),
  514. 'Gear_4X': list(np.random.rand(13)),
  515. },
  516. 'past_history': {
  517. 'RPM_1X': list(np.random.rand(13)),
  518. 'RPM_2X': list(np.random.rand(13)),
  519. 'RPM_3X': list(np.random.rand(13)),
  520. 'RPM_4X': list(np.random.rand(13)),
  521. 'RPM_5X': list(np.random.rand(13)),
  522. 'RPM_6X': list(np.random.rand(13)),
  523. 'RPM_7X': list(np.random.rand(13)),
  524. 'RPM_8X': list(np.random.rand(13)),
  525. 'Gear_1X': list(np.random.rand(13)),
  526. 'Gear_2X': list(np.random.rand(13)),
  527. 'Gear_3X': list(np.random.rand(13)),
  528. 'Gear_4X': list(np.random.rand(13)),
  529. }
  530. },
  531. str(datetime.today()-timedelta(days=1))[:10]: {
  532. 'curr_history': {
  533. 'RPM_1X': list(np.random.rand(13)),
  534. 'RPM_2X': list(np.random.rand(13)),
  535. 'RPM_3X': list(np.random.rand(13)),
  536. 'RPM_4X': list(np.random.rand(13)),
  537. 'RPM_5X': list(np.random.rand(13)),
  538. 'RPM_6X': list(np.random.rand(13)),
  539. 'RPM_7X': list(np.random.rand(13)),
  540. 'RPM_8X': list(np.random.rand(13)),
  541. 'Gear_1X': list(np.random.rand(13)),
  542. 'Gear_2X': list(np.random.rand(13)),
  543. 'Gear_3X': list(np.random.rand(13)),
  544. 'Gear_4X': list(np.random.rand(13)),
  545. },
  546. 'past_history': {
  547. 'RPM_1X': list(np.random.rand(13)),
  548. 'RPM_2X': list(np.random.rand(13)),
  549. 'RPM_3X': list(np.random.rand(13)),
  550. 'RPM_4X': list(np.random.rand(13)),
  551. 'RPM_5X': list(np.random.rand(13)),
  552. 'RPM_6X': list(np.random.rand(13)),
  553. 'RPM_7X': list(np.random.rand(13)),
  554. 'RPM_8X': list(np.random.rand(13)),
  555. 'Gear_1X': list(np.random.rand(13)),
  556. 'Gear_2X': list(np.random.rand(13)),
  557. 'Gear_3X': list(np.random.rand(13)),
  558. 'Gear_4X': list(np.random.rand(13)),
  559. }
  560. },
  561. }
  562. return fake_data[date]
  563. # Login funtion part
  564. def check_user_exists(username):
  565. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  566. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  567. return True
  568. else:
  569. return False
  570. def get_user(username: str):
  571. """ 取得使用者資訊(Model) """
  572. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  573. if not check_user_exists(username): # if user don't exist
  574. return False
  575. user_dict = next(
  576. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  577. user = models.User(**user_dict)
  578. return user
  579. def user_register(user):
  580. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  581. table = db['users']
  582. #user.password = get_password_hash(user.password)
  583. table.insert(dict(user))
  584. def get_password_hash(password):
  585. """ 加密密碼 """
  586. return pwd_context.hash(password)
  587. def verify_password(plain_password, hashed_password):
  588. """ 驗證密碼(hashed) """
  589. return pwd_context.verify(plain_password, hashed_password)
  590. def authenticate_user(username: str, password: str):
  591. """ 連線DB,讀取使用者是否存在。 """
  592. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  593. if not check_user_exists(username): # if user don't exist
  594. return False
  595. if not check_user_isEnable(username):
  596. return False
  597. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  598. user = models.User(**user_dict)
  599. #if not verify_password(password, user.password):
  600. #return False
  601. return user
  602. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  603. """ 創建token,並設定過期時間。 """
  604. to_encode = data.copy()
  605. if expires_delta:
  606. expire = datetime.utcnow() + expires_delta
  607. else:
  608. expire = datetime.utcnow() + timedelta(minutes=15)
  609. to_encode.update({"exp": expire})
  610. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  611. return encoded_jwt
  612. def compare_jwt_token(access_token: str, token: str):
  613. """比對jwt token"""
  614. if len(access_token) < len(token):
  615. if access_token in token:
  616. return True
  617. else :
  618. return False
  619. elif len(access_token) > len(token):
  620. if token in access_token:
  621. return True
  622. else :
  623. return False
  624. else :
  625. if token == access_token:
  626. return True
  627. else :
  628. return False
  629. def check_isAdmin(user_name:str):
  630. """查看是否為管理員"""
  631. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  632. isAdmin = None
  633. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  634. for row in db.query(cmd) :
  635. isAdmin = row['isAdmin']
  636. if isAdmin== None:
  637. return "no user"
  638. return isAdmin
  639. def check_role_type(user_name:str)->int:
  640. """查看使用者權限"""
  641. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  642. cmd = 'SELECT user_role.role_id FROM `users` JOIN `user_role` ON `users`.id = `user_role`.user_id where `users`.username = "'+user_name+'"'
  643. role_type = None
  644. for row in db.query(cmd) :
  645. role_type = row['role_id']
  646. return role_type
  647. def check_role_acl(role:int):
  648. """查看權限"""
  649. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  650. cmd = 'SELECT * FROM role_acl where role_id = '+str(role)
  651. result = []
  652. for row in db.query(cmd) :
  653. dic ={}
  654. for col_name in db['role_acl'].columns:
  655. dic[col_name] = row[col_name]
  656. if dic != {}:
  657. result.append(dic)
  658. return result
  659. def get_role_name(role_id:int):
  660. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  661. cmd = 'SELECT * FROM role where id = '+str(role_id)
  662. role:str
  663. for row in db.query(cmd) :
  664. role = row['name']
  665. return role
  666. def check_user_isEnable(user_name:str)->bool:
  667. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  668. cmd = 'SELECT isEnable FROM users where username = "'+str(user_name)+'"'
  669. able:bool
  670. for row in db.query(cmd) :
  671. able = row['isEnable']
  672. return able
  673. def get_user_under_organization(user_name:str):
  674. """查看所屬公司"""
  675. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  676. user_role = check_role_type(user_name)
  677. print(user_name,user_role)
  678. cmd = 'SELECT * FROM organization'
  679. result = []
  680. if int(user_role) == 1 :
  681. for row in db.query(cmd) :
  682. company = row['Company']
  683. factory = row['Factory']
  684. department = row['Department']
  685. cmd2 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  686. group = []
  687. for row2 in db.query(cmd2):
  688. if row2['TowerGroupCode'] not in group :
  689. group.append(row2['TowerGroupCode'])
  690. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  691. elif int(user_role) == 2:
  692. cmd2 = 'SELECT company FROM user WHERE user.username ="'+user_name +'"'
  693. company_able:str
  694. for row in db.query(cmd2) :
  695. company_able = row['company']
  696. for row in db.query(cmd) :
  697. company = row['Company']
  698. factory = row['Factory']
  699. department = row['Department']
  700. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  701. group = []
  702. for row2 in db.query(cmd3):
  703. if row2['TowerGroupCode'] not in group :
  704. group.append(row2['TowerGroupCode'])
  705. if company == company_able:
  706. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  707. else:
  708. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  709. elif int(user_role) == 3:
  710. cmd2 = 'SELECT company,factory FROM users WHERE users.username = "'+user_name +'"'
  711. company_able:str
  712. factory_able:str
  713. num = 0
  714. for row in db.query(cmd2) :
  715. company_able = row['company']
  716. factory_able = row['factory']
  717. for row in db.query(cmd) :
  718. company = row['Company']
  719. factory = row['Factory']
  720. department = row['Department']
  721. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  722. group = []
  723. for row2 in db.query(cmd3):
  724. if row2['TowerGroupCode'] not in group :
  725. group.append(row2['TowerGroupCode'])
  726. if company == company_able and factory==factory_able:
  727. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  728. else:
  729. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  730. elif int(user_role) == 4:
  731. cmd2 = 'SELECT company,factory,department FROM users WHERE username = "'+user_name +'"'
  732. company_able:str
  733. factory_able:str
  734. department_able:str
  735. for row in db.query(cmd2) :
  736. company_able = row['company']
  737. factory_able = row['factory']
  738. department_able = row['department']
  739. for row in db.query(cmd) :
  740. company = row['Company']
  741. factory = row['Factory']
  742. department = row['Department']
  743. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  744. group = []
  745. for row2 in db.query(cmd3):
  746. if row2['TowerGroupCode'] not in group :
  747. group.append(row2['TowerGroupCode'])
  748. if company == company_able and factory==factory_able and department==department_able:
  749. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  750. else:
  751. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  752. else :
  753. result =[ {'msg':"error"}]
  754. return result
  755. def get_user_id(user_name:str):
  756. """獲取user id"""
  757. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  758. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  759. id = None
  760. for row in db.query(cmd) :
  761. id = row['id']
  762. return id
  763. def get_user_name(user_id:int):
  764. """獲取user name"""
  765. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  766. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  767. id = None
  768. for row in db.query(cmd) :
  769. id = row['username']
  770. return id
  771. def get_modul_name(modul_id:str):
  772. """獲取modul名稱"""
  773. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  774. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  775. modul_name = None
  776. for row in db.query(cmd) :
  777. modul_name = row['moduleName']
  778. return modul_name
  779. def get_tower_info(tower_id:str):
  780. """獲取水塔資料"""
  781. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  782. cmd = 'SELECT * FROM `record_dcs` where device_id = "'+tower_id+'"'
  783. result ={'DCS':{},'Fan':{},'Moter':{},'Device_info':{}}
  784. for row in db.query(cmd) :
  785. result['DCS'][row['key']]=row['value']
  786. cmd = 'SELECT * FROM `record_tower` where device_id = "'+tower_id+'"'
  787. for row in db.query(cmd) :
  788. result['Fan'][row['key']]=row['value']
  789. result['Moter'] = []
  790. cmd = 'SELECT * FROM `vibration` where device_id = "'+tower_id+'"'
  791. tmp = {}
  792. for row in db.query(cmd) :
  793. for col in db['vibration'].columns :
  794. tmp[col] = row[col]
  795. result['Moter'].append(tmp)
  796. tmp = {}
  797. cmd = 'SELECT * FROM `device` where id = "'+tower_id+'"'
  798. for row in db.query(cmd):
  799. for col in db['device'].columns :
  800. if col != 'createTime':
  801. result['Device_info'][col] = row[col]
  802. return result
  803. def get_tower_perform(tower_id:str):
  804. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  805. cmd = 'SELECT * FROM `record_performance` where deviceCode = "'+tower_id+'" AND designWFR = 27000'
  806. result = [{}]
  807. for row in db.query(cmd):
  808. for col in db['record_performance'].columns :
  809. if col != 'createTime':
  810. result[0][col] = row[col]
  811. #print(result)
  812. return result
  813. def get_tower(company:str,factory:str,department:str,towerGroup:str):
  814. towergroup_arr =[]
  815. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  816. cmd = 'SELECT id FROM `device` where CompanyCode = "'+company+'" AND FactoryCode = "' +factory+'" AND DepartmentCode = "'+department+'" AND TowerGroupCode = "' + towerGroup + '"'
  817. for row in db.query(cmd) :
  818. towergroup_arr.append(row['id'])
  819. return towergroup_arr
  820. def check_tower_health(user_name:str):
  821. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  822. org = get_user_under_organization(user_name)
  823. #print(org)
  824. towers : list
  825. result = []
  826. for dic in org:
  827. #print(dic)
  828. if dic['able'] == 1:
  829. for group in dic['group']:
  830. towers = get_tower(dic['company'],dic['factory'],dic['department'],group)
  831. for tower in towers:
  832. cmd = 'SELECT CVIndex,threshold FROM `vibration` where device_id = "'+tower+'"'
  833. health =1
  834. for row in db.query(cmd) :
  835. if int(row['CVIndex']) < int(row['threshold']):
  836. health = 0
  837. result.append({'company':dic['company'], 'factory':dic['factory'], 'department':dic['department'], 'group': group, 'tower': tower, 'health': health})
  838. return result
  839. def find_vibration_id(tower_id:str,channel_id:str):
  840. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  841. cmd = 'SELECT id FROM `vibration` where device_id = "'+tower_id+'" AND channelName = "' +channel_id+'"'
  842. for row in db.query(cmd) :
  843. return row['id']
  844. def get_channel_info(vibration_id):
  845. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  846. cmd = 'SELECT * FROM `record_diagnosis` where vibration_id = "'+vibration_id+'"'
  847. result = {}
  848. for row in db.query(cmd) :
  849. for col in db['record_diagnosis'].columns :
  850. result[col] = row[col]
  851. cmd2='SELECT CVIndex,threshold FROM `vibration` where id = "'+vibration_id+'"'
  852. for row2 in db.query(cmd2) :
  853. result['CVIndex'] = row2['CVIndex']
  854. result['threshold'] = row2['threshold']
  855. print(result)
  856. return result
  857. def get_channel_health(vibration_id:str):
  858. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  859. result = []
  860. data_name = ['CV_index', 'Vrms' ,'RPM']
  861. for row in data_name:
  862. result.append({'name':row,'data':[]})
  863. cmd = 'SELECT * FROM record_health where vibration_id = "'+vibration_id+'"'
  864. for row in db.query(cmd) :
  865. for dic in result:
  866. dic['data'].append(row[dic['name']])
  867. return result
  868. def get_predect_data(vibration_id:str):
  869. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  870. result = {}
  871. cmd = 'SELECT * FROM record_prediction_upd where vibration_id = "'+vibration_id+'"'
  872. for row in db.query(cmd) :
  873. arr = row['predictData'].split(',')
  874. result['data']=arr
  875. return result
  876. def get_frequency(vibration_id:str):
  877. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  878. result = {'Hz':[],'value':[]}
  879. print(vibration_id)
  880. cmd = 'SELECT * FROM record_frequency where vibration_id = "'+vibration_id+'"'
  881. for row in db.query(cmd) :
  882. result['Hz'].append(row['MFHz'])
  883. result['value'].append(row['MFValue'])
  884. return result
  885. def add_data():
  886. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  887. loc_dt = datetime.today()
  888. loc_dt_format = loc_dt.strftime("%Y-%m-%d %H:%M:%S")
  889. cmd = "TRUNCATE TABLE record_health"
  890. db.query(cmd)
  891. for j in range(1,5):
  892. for i in range(0,7):
  893. time_del = timedelta(days=i)
  894. date=loc_dt-time_del
  895. 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))
  896. cmd = "TRUNCATE TABLE record_frequency"
  897. db.query(cmd)
  898. for i in range(0,5000):
  899. print(i)
  900. db['record_frequency'].insert(dict(time_stamp=loc_dt_format, MFHz=i, MFValue=uniform(0,0.12),vibration_id = 1))