main.py 46 KB

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