main.py 38 KB

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