main.py 53 KB

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