main.py 40 KB

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