main.py 38 KB

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