main.py 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283
  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_dcs(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. db['record_diagnosis'].update(dict(dict_tmp),['vibration_id'])
  186. result={'msg':'success insert'}
  187. return json.dumps(result,ensure_ascii=False)
  188. @app.get('/add_tower')
  189. async def home(request: Request, Authorize: AuthJWT = Depends()):
  190. return templates.TemplateResponse(name='add_tower.html', context={'request': request})
  191. @app.post('/add_tower')
  192. async def home(request: Request, Authorize: AuthJWT = Depends()):
  193. data=request.form()
  194. print(data.device)
  195. @app.get('/home', response_class=HTMLResponse)
  196. async def home(request: Request, Authorize: AuthJWT = Depends()):
  197. try:
  198. Authorize.jwt_required()
  199. except Exception as e:
  200. print(e)
  201. return RedirectResponse('/login')
  202. #add_data()
  203. return templates.TemplateResponse(name='home.html', context={'request': request})
  204. @app.get('/home/show', response_class=HTMLResponse)
  205. async def home(request: Request, Authorize: AuthJWT = Depends()):
  206. try:
  207. Authorize.jwt_required()
  208. except Exception as e:
  209. print(e)
  210. return RedirectResponse('/login')
  211. current_user = Authorize.get_jwt_subject()
  212. result = [{'user_role':check_role_type(current_user)}]
  213. result.append(check_tower_health(current_user))
  214. #print(result)
  215. return json.dumps(result,ensure_ascii=False)
  216. @app.get('/org', response_class=HTMLResponse)
  217. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  218. try:
  219. Authorize.jwt_required()
  220. except Exception as e:
  221. print(e)
  222. return RedirectResponse('/login')
  223. current_user = Authorize.get_jwt_subject()
  224. result = get_user_under_organization(current_user)
  225. return json.dumps(result,ensure_ascii=False)
  226. @app.get('/user_role', response_class=HTMLResponse)
  227. async def user_role(request: Request, Authorize: AuthJWT = Depends()):
  228. try:
  229. Authorize.jwt_required()
  230. except Exception as e:
  231. print(e)
  232. return RedirectResponse('/login')
  233. current_user = Authorize.get_jwt_subject()
  234. result = {'role':check_role_type(current_user)}
  235. print(result)
  236. return json.dumps(result,ensure_ascii=False)
  237. @app.get('/tower', response_class=HTMLResponse)
  238. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  239. try:
  240. Authorize.jwt_required()
  241. except Exception as e:
  242. print(e)
  243. return RedirectResponse('/login')
  244. current_user = Authorize.get_jwt_subject()
  245. result = get_user_under_organization(current_user)
  246. result.append({'Data' : get_tower_info('dev001')})
  247. return templates.TemplateResponse(name='tower.html', context={"request":request})
  248. @app.get('/tower/org', response_class=HTMLResponse)
  249. async def tower(request: Request, Authorize: AuthJWT = Depends()):
  250. try:
  251. Authorize.jwt_required()
  252. except Exception as e:
  253. print(e)
  254. return RedirectResponse('/login')
  255. current_user = Authorize.get_jwt_subject()
  256. result = get_user_under_organization(current_user)
  257. return json.dumps(result,ensure_ascii=False)
  258. @app.get('/tower/', response_class=HTMLResponse)
  259. async def tower(request: Request,company:str,factory:str,department:str,towerGroup:str, Authorize: AuthJWT = Depends()):
  260. try:
  261. Authorize.jwt_required()
  262. except Exception as e:
  263. print(e)
  264. return RedirectResponse('/login')
  265. #current_user = Authorize.get_jwt_subject()
  266. tower_arr = get_tower(company,factory,department,towerGroup)
  267. result = []
  268. for tower in tower_arr:
  269. result.append({'tower_name': tower,'tower_data': get_tower_info(tower)})
  270. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  271. @app.get('/tower/performance/{tower_id}', response_class=HTMLResponse)
  272. async def member_authority(request:Request,tower_id: str,Authorize: AuthJWT = Depends()):
  273. """設定成員權限"""
  274. try:
  275. Authorize.jwt_required()
  276. except Exception as e:
  277. print(e)
  278. return RedirectResponse('/login')
  279. result = get_tower_perform(tower_id)
  280. #print(result)
  281. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  282. @app.get('/optim', response_class=HTMLResponse)
  283. async def optim(request: Request, Authorize: AuthJWT = Depends()):
  284. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  285. statement = 'SELECT value FROM record_tower WHERE record_tower.key = "hotTemp"'
  286. x = 0
  287. y = 0
  288. z = 0
  289. count = 0
  290. waterflow = 0
  291. fannum = 0
  292. savewater = 0
  293. fanchange = 0
  294. saveelec = 0
  295. total = 0
  296. flowchange = 0
  297. try:
  298. Authorize.jwt_required()
  299. except Exception as e:
  300. print(e)
  301. return RedirectResponse('/login')
  302. current_user = Authorize.get_jwt_subject()
  303. print(check_role_type(current_user))
  304. role = int(check_role_type(current_user))
  305. print(check_role_type(current_user))
  306. if role == 1:
  307. statement = 'SELECT value FROM record_tower WHERE record_tower.key = "hotTemp"'
  308. for temp in db.query(statement):
  309. print(temp['value'])
  310. x=temp['value']
  311. statement2 = 'SELECT value FROM record_tower WHERE record_tower.key = "coldTempData1"'
  312. for temp2 in db.query(statement2):
  313. print(temp2['value'])
  314. y=temp2['value']
  315. statement3 = 'SELECT value FROM record_tower WHERE record_tower.key = "wetTemp"'
  316. for temp3 in db.query(statement3):
  317. print(temp3['value'])
  318. z=temp3['value']
  319. statement4 = 'SELECT value FROM record_tower WHERE record_tower.key = "count"'
  320. for tower in db.query(statement4):
  321. print(tower['value'])
  322. count=tower['value']
  323. statement5 = 'SELECT value FROM record_tower WHERE record_tower.key = "waterflow"'
  324. for tower in db.query(statement5):
  325. waterflow=tower['value']
  326. statement6 = 'SELECT value FROM record_tower WHERE record_tower.key = "fannum"'
  327. for tower in db.query(statement6):
  328. fannum=tower['value']
  329. statement7 = 'SELECT value FROM record_tower WHERE record_tower.key = "flowchange"'
  330. for tower in db.query(statement7):
  331. flowchange=tower['value']
  332. statement8 = 'SELECT value FROM record_tower WHERE record_tower.key = "savewater"'
  333. for tower in db.query(statement8):
  334. savewater=tower['value']
  335. statement9 = 'SELECT value FROM record_tower WHERE record_tower.key = "fanchange"'
  336. for tower in db.query(statement9):
  337. fanchange=tower['value']
  338. statement10 = 'SELECT value FROM record_tower WHERE record_tower.key = "saveelec"'
  339. for tower in db.query(statement10):
  340. saveelec=tower['value']
  341. statement11 = 'SELECT value FROM record_tower WHERE record_tower.key = "total"'
  342. for tower in db.query(statement11):
  343. total=tower['value']
  344. elif role == 3 :
  345. statement = 'SELECT value FROM record_tower WHERE record_tower.key = "hotTemp1"'
  346. for temp in db.query(statement):
  347. print(temp['value'])
  348. x=temp['value']
  349. statement2 = 'SELECT value FROM record_tower WHERE record_tower.key = "coldTempData2"'
  350. for temp2 in db.query(statement2):
  351. print(temp2['value'])
  352. y=temp2['value']
  353. statement3 = 'SELECT value FROM record_tower WHERE record_tower.key = "wetTemp1"'
  354. for temp3 in db.query(statement3):
  355. print(temp3['value'])
  356. z=temp3['value']
  357. statement4 = 'SELECT value FROM record_tower WHERE record_tower.key = "count1"'
  358. for tower in db.query(statement4):
  359. print(tower['value'])
  360. count=tower['value']
  361. statement5 = 'SELECT value FROM record_tower WHERE record_tower.key = "waterflow1"'
  362. for tower in db.query(statement5):
  363. waterflow=tower['value']
  364. statement6 = 'SELECT value FROM record_tower WHERE record_tower.key = "fannum1"'
  365. for tower in db.query(statement6):
  366. fannum=tower['value']
  367. statement7 = 'SELECT value FROM record_tower WHERE record_tower.key = "flowchange1"'
  368. for tower in db.query(statement7):
  369. flowchange=tower['value']
  370. statement8 = 'SELECT value FROM record_tower WHERE record_tower.key = "savewater1"'
  371. for tower in db.query(statement8):
  372. savewater=tower['value']
  373. statement9 = 'SELECT value FROM record_tower WHERE record_tower.key = "fanchange1"'
  374. for tower in db.query(statement9):
  375. fanchange=tower['value']
  376. statement10 = 'SELECT value FROM record_tower WHERE record_tower.key = "saveelec1"'
  377. for tower in db.query(statement10):
  378. saveelec=tower['value']
  379. statement11 = 'SELECT value FROM record_tower WHERE record_tower.key = "total1"'
  380. for tower in db.query(statement11):
  381. total=tower['value']
  382. elif role == 4 :
  383. statement = 'SELECT value FROM record_tower WHERE record_tower.key = "hotTemp2"'
  384. for temp in db.query(statement):
  385. print(temp['value'])
  386. x=temp['value']
  387. statement2 = 'SELECT value FROM record_tower WHERE record_tower.key = "coldTempData3"'
  388. for temp2 in db.query(statement2):
  389. print(temp2['value'])
  390. y=temp2['value']
  391. statement3 = 'SELECT value FROM record_tower WHERE record_tower.key = "wetTemp2"'
  392. for temp3 in db.query(statement3):
  393. print(temp3['value'])
  394. z=temp3['value']
  395. statement4 = 'SELECT value FROM record_tower WHERE record_tower.key = "count2"'
  396. for tower in db.query(statement4):
  397. print(tower['value'])
  398. count=tower['value']
  399. statement5 = 'SELECT value FROM record_tower WHERE record_tower.key = "waterflow2"'
  400. for tower in db.query(statement5):
  401. waterflow=tower['value']
  402. statement6 = 'SELECT value FROM record_tower WHERE record_tower.key = "fannum2"'
  403. for tower in db.query(statement6):
  404. fannum=tower['value']
  405. statement7 = 'SELECT value FROM record_tower WHERE record_tower.key = "flowchange2"'
  406. for tower in db.query(statement7):
  407. flowchange=tower['value']
  408. statement8 = 'SELECT value FROM record_tower WHERE record_tower.key = "savewater2"'
  409. for tower in db.query(statement8):
  410. savewater=tower['value']
  411. statement9 = 'SELECT value FROM record_tower WHERE record_tower.key = "fanchange2"'
  412. for tower in db.query(statement9):
  413. fanchange=tower['value']
  414. statement10 = 'SELECT value FROM record_tower WHERE record_tower.key = "saveelec2"'
  415. for tower in db.query(statement10):
  416. saveelec=tower['value']
  417. statement11 = 'SELECT value FROM record_tower WHERE record_tower.key = "total2"'
  418. for tower in db.query(statement11):
  419. total=tower['value']
  420. else :
  421. print("noright")
  422. return templates.TemplateResponse(name='optim.html',context=
  423. {
  424. 'request': request,"x":x,"y":y,"z":z,"count":count,"waterflow":waterflow
  425. ,"fannum":fannum , "flowchange":flowchange , "savewater":savewater
  426. , "fanchange":fanchange , "saveelec":saveelec , "total":total
  427. })
  428. @app.get('/vibration', response_class=HTMLResponse)
  429. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  430. try:
  431. Authorize.jwt_required()
  432. except Exception as e:
  433. print(e)
  434. return RedirectResponse('/login')
  435. return templates.TemplateResponse(name='vibration_test.html', context={'request': request})
  436. @app.get('/channel', response_class=HTMLResponse)
  437. async def vibration(request: Request, Authorize: AuthJWT = Depends()):
  438. try:
  439. Authorize.jwt_required()
  440. except Exception as e:
  441. print(e)
  442. return RedirectResponse('/login')
  443. return templates.TemplateResponse(name='channel.html', context={'request': request})
  444. @app.get('/channel/{tower_id}/{channel_id}', response_class=HTMLResponse)
  445. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  446. try:
  447. Authorize.jwt_required()
  448. except Exception as e:
  449. print(e)
  450. return RedirectResponse('/login')
  451. print(find_vibration_id(tower_id,channel_id))
  452. result = get_channel_info(find_vibration_id(tower_id,channel_id))
  453. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  454. @app.get('/channel_chart/{tower_id}/{channel_id}', response_class=HTMLResponse)
  455. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  456. try:
  457. Authorize.jwt_required()
  458. except Exception as e:
  459. print(e)
  460. return RedirectResponse('/login')
  461. print(find_vibration_id(tower_id,channel_id))
  462. result = get_channel_health(find_vibration_id(tower_id,channel_id))
  463. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  464. @app.get('/channel_predict/{tower_id}/{channel_id}', response_class=HTMLResponse)
  465. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  466. try:
  467. Authorize.jwt_required()
  468. except Exception as e:
  469. print(e)
  470. return RedirectResponse('/login')
  471. #print(find_vibration_id(tower_id,channel_id))
  472. result = get_predect_data(find_vibration_id(tower_id,channel_id))
  473. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  474. @app.get('/channel_frequency/{tower_id}/{channel_id}', response_class=HTMLResponse)
  475. async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
  476. try:
  477. Authorize.jwt_required()
  478. except Exception as e:
  479. print(e)
  480. return RedirectResponse('/login')
  481. #print(find_vibration_id(tower_id,channel_id))
  482. result = get_frequency(find_vibration_id(tower_id,channel_id))
  483. return json.dumps(result,ensure_ascii=False, cls = dateEncode)
  484. @app.get('/history', response_class=HTMLResponse)
  485. async def history(request: Request, Authorize: AuthJWT = Depends()):
  486. try:
  487. Authorize.jwt_required()
  488. except Exception as e:
  489. print(e)
  490. return RedirectResponse('/login')
  491. # current_user = Authorize.get_jwt_subject()
  492. return templates.TemplateResponse(name='history.html', context={'request': request})
  493. @app.get('/device', response_class=HTMLResponse)
  494. async def device(request: Request, Authorize: AuthJWT = Depends()):
  495. try:
  496. Authorize.jwt_required()
  497. except Exception as e:
  498. print(e)
  499. return RedirectResponse('/login')
  500. # current_user = Authorize.get_jwt_subject()
  501. return templates.TemplateResponse(name='device.html', context={'request': request})
  502. @app.get('/system', response_class=HTMLResponse)
  503. async def system(request: Request, Authorize: AuthJWT = Depends()):
  504. try:
  505. Authorize.jwt_required()
  506. except Exception as e:
  507. print(e)
  508. return RedirectResponse('/login')
  509. # current_user = Authorize.get_jwt_subject()
  510. return templates.TemplateResponse(name='system.html', context={'request': request})
  511. @app.get('/member', response_class=HTMLResponse)
  512. async def get_member(request: Request, Authorize: AuthJWT = Depends()):
  513. """獲取所有帳號資訊"""
  514. try:
  515. Authorize.jwt_required()
  516. except Exception as e:
  517. print(e)
  518. return RedirectResponse('/login')
  519. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  520. statement = 'SELECT id,username,isAdmin FROM users'
  521. json_dic = []
  522. for row in db.query(statement):
  523. #print(row['id'],row['username'])
  524. 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']))})
  525. result = json.dumps(json_dic,ensure_ascii=False)
  526. return result
  527. @app.get('/member/edit/', response_class=HTMLResponse)
  528. async def login(request: Request, name:str,isAdmin:int,isEnable:int ,Authorize: AuthJWT = Depends()):
  529. try:
  530. Authorize.jwt_required()
  531. except Exception as e:
  532. print(e)
  533. return RedirectResponse('/login')
  534. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  535. current_user = Authorize.get_jwt_subject()
  536. current_user_roleType = check_role_type(current_user)
  537. del_user_roleType = check_role_type(name)
  538. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  539. for row in db.query(statement):
  540. if row['isAdmin']!=1:
  541. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  542. if del_user_roleType == None:
  543. return json.dumps([{'msg':'不存在使用者'}],ensure_ascii=False)
  544. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  545. return json.dumps([{'msg':'你沒有權限'}],ensure_ascii=False)
  546. user_dic = get_user(name)
  547. print(user_dic)
  548. user_dic.isAdmin = isAdmin
  549. user_dic.isEnable = isEnable
  550. table = db['users']
  551. table.update(dict(user_dic), ['username'])
  552. return json.dumps([{'msg':"成功更改"}],ensure_ascii=False)
  553. @app.get('/member_delete', response_class=HTMLResponse)
  554. async def login(request: Request, Authorize: AuthJWT = Depends()):
  555. try:
  556. Authorize.jwt_required()
  557. except Exception as e:
  558. print(e)
  559. return RedirectResponse('/login')
  560. return templates.TemplateResponse(name='delete_member_test2.html', context={'request': request})
  561. @app.post('/member_delete')
  562. async def delete_member(request: Request):
  563. """刪除成員"""
  564. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  565. del_user = models.del_user(**await request.form())
  566. delete_name = del_user.del_name
  567. statement = 'SELECT * FROM users'
  568. current_user = ''
  569. for row in db.query(statement):
  570. if row['token'] != None :
  571. if compare_jwt_token(row['token'],del_user.access_token):
  572. current_user = row['username']
  573. if current_user == '':
  574. return {'msg':'尚未登入'}
  575. statement = 'SELECT isAdmin FROM users WHERE userName = "'+current_user+'"'
  576. for row in db.query(statement):
  577. if row['isAdmin']!=1:
  578. return {'msg': ' 你沒有權限'}
  579. current_user_roleType = check_role_type(current_user)
  580. del_user_roleType = check_role_type(delete_name)
  581. if del_user_roleType == None:
  582. return {'msg':'不存在使用者'}
  583. elif current_user_roleType>del_user_roleType or current_user_roleType==del_user_roleType:
  584. return {'msg': ' 你沒有權限'}
  585. else :
  586. table = db['users']
  587. table.delete(username=delete_name)
  588. return {'msg': ' 成功刪除'}
  589. @app.get('/member_authority/{edit_one}', response_class=HTMLResponse)
  590. async def member_authority(request:Request,edit_one: int,Authorize: AuthJWT = Depends()):
  591. """設定成員權限"""
  592. try:
  593. Authorize.jwt_required()
  594. except Exception as e:
  595. print(e)
  596. return RedirectResponse('/login')
  597. context = {'request': request}
  598. current_user = Authorize.get_jwt_subject()
  599. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  600. statement = check_isAdmin(current_user)
  601. if statement == "no user":
  602. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no user' })
  603. elif statement == 0:
  604. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  605. current_user_roleType = check_role_type(current_user)
  606. if edit_one == None:
  607. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'no role' })
  608. elif int(current_user_roleType)>int(edit_one) or int(current_user_roleType)==int(edit_one):
  609. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':"沒有權限" })
  610. result = check_role_acl(edit_one)
  611. if result == []:
  612. cmd = 'SELECT id FROM module'
  613. for row in db.query(cmd):
  614. dic_tmp = {'id':0,'isView':0,'isAdd':0 ,'isEdit':0,'isDel':0,'role_id' : edit_one}
  615. context[get_modul_name(row['id']) ] = dic_tmp
  616. else:
  617. for dic in result:
  618. modul_name = get_modul_name(dic['module_id'])
  619. del dic['module_id']
  620. context[modul_name ] = dic
  621. return templates.TemplateResponse(name='member_authority_test.html', context=context)
  622. @app.post('/member_authority')
  623. async def member_authority(request: Request):
  624. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  625. edit_one = models.user_authority(**await request.form())
  626. statement = 'SELECT * FROM users'
  627. current_user = ''
  628. for row in db.query(statement):
  629. if row['token'] != None :
  630. if compare_jwt_token(row['token'],edit_one.access_token):
  631. current_user = row['username']
  632. if current_user == '':
  633. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'尚未登入'})
  634. statement = check_isAdmin(current_user)
  635. if statement == "no user":
  636. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':statement })
  637. elif statement == 0:
  638. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg':'你沒有權限' })
  639. current_user_roleType = check_role_type(current_user)
  640. edit_one_roleType = edit_one.role_id
  641. if current_user_roleType>edit_one_roleType or current_user_roleType==edit_one_roleType:
  642. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': ' 你沒有權限'})
  643. else :
  644. row = ['ai_prediction' ,'channel' ,'device', 'event', 'index' ,'performance', 'record', 'setting_device' ,'setting_system','tower']
  645. if check_role_acl(edit_one.role_id) == []:
  646. for module in row :
  647. new_dict = edit_one.get_acl_from_module_name(module)
  648. new_dict["id"]= None
  649. table = db['role_acl']
  650. table.insert(new_dict)
  651. else:
  652. for module in row :
  653. new_dict = edit_one.get_acl_from_module_name(module)
  654. table = db['role_acl']
  655. table.update(new_dict, ['id'])
  656. return templates.TemplateResponse(name='notice.html', context={"request":request,'msg': '成功更改權限'})
  657. # 溫度API
  658. @app.get('/temperature')
  659. async def get_temperatures():
  660. """ 撈DB溫度 """
  661. return {'hot_water': 30.48, 'cold_water': 28.10, 'wet_ball': 25.14}
  662. @app.post("/example")
  663. async def example(request: Request,Authorize: AuthJWT = Depends()):
  664. try:
  665. Authorize.jwt_required()
  666. except Exception as e:
  667. print(e)
  668. current_user = Authorize.get_jwt_subject()
  669. #form_data = await request.form()
  670. print( current_user)
  671. return current_user
  672. @app.post('/user')
  673. def user(Authorize: AuthJWT = Depends()):
  674. Authorize.jwt_required()
  675. current_user = Authorize.get_jwt_subject()
  676. return {"user": current_user}
  677. @app.get("/add_data", response_class=HTMLResponse)
  678. async def example(request: Request,Authorize: AuthJWT = Depends()):
  679. try:
  680. Authorize.jwt_required()
  681. except Exception as e:
  682. print(e)
  683. return RedirectResponse('/login')
  684. add_data()
  685. return templates.TemplateResponse(name='test.html', context={'request': request})
  686. @app.get('/health')
  687. async def get_health(date: str):
  688. """ 撈健康指標、預設健康指標 """
  689. date = str(datetime.strptime(date, "%Y-%m-%d"))[:10]
  690. print(date)
  691. print(str(datetime.today()))
  692. print(str(datetime.today()-timedelta(days=1)))
  693. fake_data = {
  694. str(datetime.today())[:10]: {'curr_health': 0.7, 'pred_health': 0.8},
  695. str(datetime.today()-timedelta(days=1))[:10]: {'curr_health': 0.6, 'pred_health': 0.7},
  696. }
  697. return fake_data[date]
  698. @app.get('/history_data')
  699. async def get_history(time_end: str):
  700. """ 透過終點時間,抓取歷史資料。 """
  701. date = str(datetime.strptime(time_end, "%Y-%m-%d"))[:10]
  702. print(date)
  703. print(str(datetime.today()))
  704. print(str(datetime.today()-timedelta(days=1)))
  705. fake_data = {
  706. str(datetime.today())[:10]: {
  707. 'curr_history': {
  708. 'RPM_1X': list(np.random.rand(13)),
  709. 'RPM_2X': list(np.random.rand(13)),
  710. 'RPM_3X': list(np.random.rand(13)),
  711. 'RPM_4X': list(np.random.rand(13)),
  712. 'RPM_5X': list(np.random.rand(13)),
  713. 'RPM_6X': list(np.random.rand(13)),
  714. 'RPM_7X': list(np.random.rand(13)),
  715. 'RPM_8X': list(np.random.rand(13)),
  716. 'Gear_1X': list(np.random.rand(13)),
  717. 'Gear_2X': list(np.random.rand(13)),
  718. 'Gear_3X': list(np.random.rand(13)),
  719. 'Gear_4X': list(np.random.rand(13)),
  720. },
  721. 'past_history': {
  722. 'RPM_1X': list(np.random.rand(13)),
  723. 'RPM_2X': list(np.random.rand(13)),
  724. 'RPM_3X': list(np.random.rand(13)),
  725. 'RPM_4X': list(np.random.rand(13)),
  726. 'RPM_5X': list(np.random.rand(13)),
  727. 'RPM_6X': list(np.random.rand(13)),
  728. 'RPM_7X': list(np.random.rand(13)),
  729. 'RPM_8X': list(np.random.rand(13)),
  730. 'Gear_1X': list(np.random.rand(13)),
  731. 'Gear_2X': list(np.random.rand(13)),
  732. 'Gear_3X': list(np.random.rand(13)),
  733. 'Gear_4X': list(np.random.rand(13)),
  734. }
  735. },
  736. str(datetime.today()-timedelta(days=1))[:10]: {
  737. 'curr_history': {
  738. 'RPM_1X': list(np.random.rand(13)),
  739. 'RPM_2X': list(np.random.rand(13)),
  740. 'RPM_3X': list(np.random.rand(13)),
  741. 'RPM_4X': list(np.random.rand(13)),
  742. 'RPM_5X': list(np.random.rand(13)),
  743. 'RPM_6X': list(np.random.rand(13)),
  744. 'RPM_7X': list(np.random.rand(13)),
  745. 'RPM_8X': list(np.random.rand(13)),
  746. 'Gear_1X': list(np.random.rand(13)),
  747. 'Gear_2X': list(np.random.rand(13)),
  748. 'Gear_3X': list(np.random.rand(13)),
  749. 'Gear_4X': list(np.random.rand(13)),
  750. },
  751. 'past_history': {
  752. 'RPM_1X': list(np.random.rand(13)),
  753. 'RPM_2X': list(np.random.rand(13)),
  754. 'RPM_3X': list(np.random.rand(13)),
  755. 'RPM_4X': list(np.random.rand(13)),
  756. 'RPM_5X': list(np.random.rand(13)),
  757. 'RPM_6X': list(np.random.rand(13)),
  758. 'RPM_7X': list(np.random.rand(13)),
  759. 'RPM_8X': list(np.random.rand(13)),
  760. 'Gear_1X': list(np.random.rand(13)),
  761. 'Gear_2X': list(np.random.rand(13)),
  762. 'Gear_3X': list(np.random.rand(13)),
  763. 'Gear_4X': list(np.random.rand(13)),
  764. }
  765. },
  766. }
  767. return fake_data[date]
  768. # Login funtion part
  769. def check_user_exists(username):
  770. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  771. if int(next(iter(db.query('SELECT COUNT(*) FROM Water_tower.users WHERE userName = "'+username+'"')))['COUNT(*)']) > 0:
  772. return True
  773. else:
  774. return False
  775. def get_user(username: str):
  776. """ 取得使用者資訊(Model) """
  777. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  778. if not check_user_exists(username): # if user don't exist
  779. return False
  780. user_dict = next(
  781. iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  782. user = models.User(**user_dict)
  783. return user
  784. def user_register(user):
  785. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  786. table = db['users']
  787. #user.password = get_password_hash(user.password)
  788. table.insert(dict(user))
  789. def get_password_hash(password):
  790. """ 加密密碼 """
  791. return pwd_context.hash(password)
  792. def verify_password(plain_password, hashed_password):
  793. """ 驗證密碼(hashed) """
  794. return pwd_context.verify(plain_password, hashed_password)
  795. def authenticate_user(username: str, password: str):
  796. """ 連線DB,讀取使用者是否存在。 """
  797. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  798. if not check_user_exists(username): # if user don't exist
  799. return False
  800. if not check_user_isEnable(username):
  801. return False
  802. user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
  803. user = models.User(**user_dict)
  804. #if not verify_password(password, user.password):
  805. #return False
  806. return user
  807. def create_access_token(data: dict, expires_delta: Optional[timedelta] = None):
  808. """ 創建token,並設定過期時間。 """
  809. to_encode = data.copy()
  810. if expires_delta:
  811. expire = datetime.utcnow() + expires_delta
  812. else:
  813. expire = datetime.utcnow() + timedelta(minutes=15)
  814. to_encode.update({"exp": expire})
  815. encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
  816. return encoded_jwt
  817. def compare_jwt_token(access_token: str, token: str):
  818. """比對jwt token"""
  819. if len(access_token) < len(token):
  820. if access_token in token:
  821. return True
  822. else :
  823. return False
  824. elif len(access_token) > len(token):
  825. if token in access_token:
  826. return True
  827. else :
  828. return False
  829. else :
  830. if token == access_token:
  831. return True
  832. else :
  833. return False
  834. def check_isAdmin(user_name:str):
  835. """查看是否為管理員"""
  836. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  837. isAdmin = None
  838. cmd = 'SELECT isAdmin FROM users WHERE userName = "'+user_name+'"'
  839. for row in db.query(cmd) :
  840. isAdmin = row['isAdmin']
  841. if isAdmin== None:
  842. return "no user"
  843. return isAdmin
  844. def check_role_type(user_name:str)->int:
  845. """查看使用者權限"""
  846. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  847. cmd = 'SELECT user_role.role_id FROM `users` JOIN `user_role` ON `users`.id = `user_role`.user_id where `users`.username = "'+user_name+'"'
  848. role_type = None
  849. for row in db.query(cmd) :
  850. role_type = row['role_id']
  851. return role_type
  852. def check_role_acl(role:int):
  853. """查看權限"""
  854. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  855. cmd = 'SELECT * FROM role_acl where role_id = '+str(role)
  856. result = []
  857. for row in db.query(cmd) :
  858. dic ={}
  859. for col_name in db['role_acl'].columns:
  860. dic[col_name] = row[col_name]
  861. if dic != {}:
  862. result.append(dic)
  863. return result
  864. def get_role_name(role_id:int):
  865. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  866. cmd = 'SELECT * FROM role where id = '+str(role_id)
  867. role:str
  868. for row in db.query(cmd) :
  869. role = row['name']
  870. return role
  871. def check_user_isEnable(user_name:str)->bool:
  872. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  873. cmd = 'SELECT isEnable FROM users where username = "'+str(user_name)+'"'
  874. able:bool
  875. for row in db.query(cmd) :
  876. able = row['isEnable']
  877. return able
  878. def get_user_under_organization(user_name:str):
  879. """查看所屬公司"""
  880. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  881. user_role = check_role_type(user_name)
  882. print(user_name,user_role)
  883. cmd = 'SELECT * FROM organization'
  884. result = []
  885. if int(user_role) == 1 :
  886. for row in db.query(cmd) :
  887. company = row['Company']
  888. factory = row['Factory']
  889. department = row['Department']
  890. cmd2 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  891. group = []
  892. for row2 in db.query(cmd2):
  893. if row2['TowerGroupCode'] not in group :
  894. group.append(row2['TowerGroupCode'])
  895. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  896. elif int(user_role) == 2:
  897. cmd2 = 'SELECT company FROM user WHERE user.username ="'+user_name +'"'
  898. company_able:str
  899. for row in db.query(cmd2) :
  900. company_able = row['company']
  901. for row in db.query(cmd) :
  902. company = row['Company']
  903. factory = row['Factory']
  904. department = row['Department']
  905. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  906. group = []
  907. for row2 in db.query(cmd3):
  908. if row2['TowerGroupCode'] not in group :
  909. group.append(row2['TowerGroupCode'])
  910. if company == company_able:
  911. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  912. else:
  913. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  914. elif int(user_role) == 3:
  915. cmd2 = 'SELECT company,factory FROM users WHERE users.username = "'+user_name +'"'
  916. company_able:str
  917. factory_able:str
  918. num = 0
  919. for row in db.query(cmd2) :
  920. company_able = row['company']
  921. factory_able = row['factory']
  922. for row in db.query(cmd) :
  923. company = row['Company']
  924. factory = row['Factory']
  925. department = row['Department']
  926. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  927. group = []
  928. for row2 in db.query(cmd3):
  929. if row2['TowerGroupCode'] not in group :
  930. group.append(row2['TowerGroupCode'])
  931. if company == company_able and factory==factory_able:
  932. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  933. else:
  934. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  935. elif int(user_role) == 4:
  936. cmd2 = 'SELECT company,factory,department FROM users WHERE username = "'+user_name +'"'
  937. company_able:str
  938. factory_able:str
  939. department_able:str
  940. for row in db.query(cmd2) :
  941. company_able = row['company']
  942. factory_able = row['factory']
  943. department_able = row['department']
  944. for row in db.query(cmd) :
  945. company = row['Company']
  946. factory = row['Factory']
  947. department = row['Department']
  948. cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
  949. group = []
  950. for row2 in db.query(cmd3):
  951. if row2['TowerGroupCode'] not in group :
  952. group.append(row2['TowerGroupCode'])
  953. if company == company_able and factory==factory_able and department==department_able:
  954. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1})
  955. else:
  956. result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
  957. else :
  958. result =[ {'msg':"error"}]
  959. return result
  960. def get_user_id(user_name:str):
  961. """獲取user id"""
  962. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  963. cmd = 'SELECT id FROM `users` where username = "'+user_name+'"'
  964. id = None
  965. for row in db.query(cmd) :
  966. id = row['id']
  967. return id
  968. def get_user_name(user_id:int):
  969. """獲取user name"""
  970. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  971. cmd = 'SELECT username FROM `users` where id = "'+user_id+'"'
  972. id = None
  973. for row in db.query(cmd) :
  974. id = row['username']
  975. return id
  976. def get_modul_name(modul_id:str):
  977. """獲取modul名稱"""
  978. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  979. cmd = 'SELECT moduleName FROM `module` where id = "'+modul_id+'"'
  980. modul_name = None
  981. for row in db.query(cmd) :
  982. modul_name = row['moduleName']
  983. return modul_name
  984. def get_tower_info(tower_id:str):
  985. """獲取水塔資料"""
  986. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  987. cmd = 'SELECT * FROM `record_dcs` where device_id = "'+tower_id+'"'
  988. result ={'DCS':{},'Fan':{},'Moter':{},'Device_info':{}}
  989. for row in db.query(cmd) :
  990. result['DCS'][row['key']]=row['value']
  991. cmd = 'SELECT * FROM `record_tower` where device_id = "'+tower_id+'"'
  992. for row in db.query(cmd) :
  993. result['Fan'][row['key']]=row['value']
  994. result['Moter'] = []
  995. cmd = 'SELECT * FROM `vibration` where device_id = "'+tower_id+'"'
  996. tmp = {}
  997. for row in db.query(cmd) :
  998. for col in db['vibration'].columns :
  999. tmp[col] = row[col]
  1000. result['Moter'].append(tmp)
  1001. tmp = {}
  1002. cmd = 'SELECT * FROM `device` where id = "'+tower_id+'"'
  1003. for row in db.query(cmd):
  1004. for col in db['device'].columns :
  1005. if col != 'createTime':
  1006. result['Device_info'][col] = row[col]
  1007. return result
  1008. def get_tower_perform(tower_id:str):
  1009. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1010. cmd = 'SELECT * FROM `record_performance` where deviceCode = "'+tower_id+'" AND designWFR = 27000'
  1011. result = [{}]
  1012. for row in db.query(cmd):
  1013. for col in db['record_performance'].columns :
  1014. if col != 'createTime':
  1015. result[0][col] = row[col]
  1016. #print(result)
  1017. return result
  1018. def get_tower(company:str,factory:str,department:str,towerGroup:str):
  1019. towergroup_arr =[]
  1020. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1021. cmd = 'SELECT id FROM `device` where CompanyCode = "'+company+'" AND FactoryCode = "' +factory+'" AND DepartmentCode = "'+department+'" AND TowerGroupCode = "' + towerGroup + '"'
  1022. for row in db.query(cmd) :
  1023. towergroup_arr.append(row['id'])
  1024. return towergroup_arr
  1025. def check_tower_health(user_name:str):
  1026. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1027. org = get_user_under_organization(user_name)
  1028. #print(org)
  1029. towers : list
  1030. result = []
  1031. for dic in org:
  1032. #print(dic)
  1033. if dic['able'] == 1:
  1034. for group in dic['group']:
  1035. towers = get_tower(dic['company'],dic['factory'],dic['department'],group)
  1036. for tower in towers:
  1037. cmd = 'SELECT CVIndex,threshold FROM `vibration` where device_id = "'+tower+'"'
  1038. health =1
  1039. for row in db.query(cmd) :
  1040. print(row['CVIndex'],row['threshold'])
  1041. if row['CVIndex'] < int(row['threshold']):
  1042. health = 0
  1043. print("heheh")
  1044. print(health)
  1045. result.append({'company':dic['company'], 'factory':dic['factory'], 'department':dic['department'], 'group': group, 'tower': tower, 'health': health})
  1046. return result
  1047. def find_vibration_id(tower_id:str,channel_id:str):
  1048. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1049. cmd = 'SELECT id FROM `vibration` where device_id = "'+tower_id+'" AND channelName = "' +channel_id+'"'
  1050. for row in db.query(cmd) :
  1051. return row['id']
  1052. def get_channel_info(vibration_id):
  1053. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1054. cmd = 'SELECT * FROM `record_diagnosis` where vibration_id = "'+vibration_id+'"'
  1055. result = {}
  1056. for row in db.query(cmd) :
  1057. for col in db['record_diagnosis'].columns :
  1058. result[col] = row[col]
  1059. cmd2='SELECT CVIndex,threshold FROM `vibration` where id = "'+vibration_id+'"'
  1060. for row2 in db.query(cmd2) :
  1061. result['CVIndex'] = row2['CVIndex']
  1062. result['threshold'] = row2['threshold']
  1063. print(result)
  1064. return result
  1065. def get_channel_health(vibration_id:str):
  1066. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1067. result = []
  1068. data_name = ['CV_index', 'Vrms' ,'RPM']
  1069. for row in data_name:
  1070. result.append({'name':row,'data':[]})
  1071. cmd = 'SELECT * FROM record_health where vibration_id = "'+vibration_id+'"'
  1072. for row in db.query(cmd) :
  1073. for dic in result:
  1074. dic['data'].append(row[dic['name']])
  1075. return result
  1076. def get_predect_data(vibration_id:str):
  1077. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1078. result = {}
  1079. cmd = 'SELECT * FROM record_prediction_upd where vibration_id = "'+vibration_id+'"'
  1080. for row in db.query(cmd) :
  1081. arr = row['predictData'].split(',')
  1082. result['data']=arr
  1083. return result
  1084. def get_frequency(vibration_id:str):
  1085. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1086. result = {'Hz':[],'value':[]}
  1087. print(vibration_id)
  1088. cmd = 'SELECT * FROM record_frequency where vibration_id = "'+vibration_id+'"'
  1089. for row in db.query(cmd) :
  1090. result['Hz'].append(row['MFHz'])
  1091. result['value'].append(row['MFValue'])
  1092. return result
  1093. def add_data():
  1094. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1095. loc_dt = datetime.today()
  1096. loc_dt_format = loc_dt.strftime("%Y-%m-%d %H:%M:%S")
  1097. cmd = "TRUNCATE TABLE record_health"
  1098. db.query(cmd)
  1099. for j in range(1,5):
  1100. for i in range(0,7):
  1101. time_del = timedelta(days=i)
  1102. date=loc_dt-time_del
  1103. 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))
  1104. cmd = "TRUNCATE TABLE record_frequency"
  1105. db.query(cmd)
  1106. for i in range(0,1000):
  1107. print(i)
  1108. db['record_frequency'].insert(dict(time_stamp=loc_dt_format, MFHz=i, MFValue=uniform(0,0.12),vibration_id = 1))
  1109. cmd = "TRUNCATE TABLE record_frequency"
  1110. db.query(cmd)
  1111. for i in range(0,1000):
  1112. print(i)
  1113. db['record_frequency'].insert(dict(time_stamp=loc_dt_format, MFHz=i, MFValue=uniform(0,0.12),vibration_id = 1))
  1114. def add_tower():
  1115. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
  1116. loc_dt = datetime.today()
  1117. loc_dt_format = loc_dt.strftime("%Y-%m-%d %H:%M:%S")
  1118. for device in ['dev005','dev006','dev007','dev008','dev009']:
  1119. for key in ['hotTemp','waterFlow','coldTemp','fanMotorCur','fanMotorSpeedFreq']:
  1120. db['record_dcs'].insert(dict(time_stamp=loc_dt_format, MFValue=uniform(0,0.12),vibration_id = 1))