main.py 56 KB

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