Mia преди 3 години
родител
ревизия
0bd892f923
променени са 1 файла, в които са добавени 231 реда и са изтрити 41 реда
  1. 231 41
      main.py

+ 231 - 41
main.py

@@ -20,17 +20,26 @@ from datetime import timedelta, datetime
 # db
 import dataset
 from passlib import context
+from sqlalchemy.sql.expression import true
 import models
-from random import randint
+from random import randint,uniform
 # authorize
 from passlib.context import CryptContext
 pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
+
 import jwt
 from fastapi_jwt_auth import AuthJWT
 from fastapi_jwt_auth.exceptions import AuthJWTException
 from fastapi.security import OAuth2AuthorizationCodeBearer, OAuth2PasswordRequestForm
 import numpy as np
 import pymysql
+
+class dateEncode(json.JSONEncoder):
+    def default(self, obj):
+        if isinstance(obj, datetime):
+            return obj.strftime('%Y-%m-%d %H:%M:%S')
+        else:
+            return json.JSONEncoder.default(self, obj)
 pymysql.install_as_MySQLdb()
 db_settings = {
     "host": "db.ptt.cx",
@@ -137,9 +146,39 @@ async def register(request: Request, form_data: OAuth2PasswordRequestForm = Depe
 
 
 @app.get('/home', response_class=HTMLResponse)
-async def home(request: Request):
+async def home(request: Request, Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login')
+    #add_data()
     return templates.TemplateResponse(name='home.html', context={'request': request})
 
+@app.get('/home/show', response_class=HTMLResponse)
+async def home(request: Request, Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login')
+    current_user = Authorize.get_jwt_subject()
+    result = [{'user_role':check_role_type(current_user)}]
+    result.append(check_tower_health(current_user))
+    #print(result)
+    return json.dumps(result,ensure_ascii=False)
+
+@app.get('/org', response_class=HTMLResponse)
+async def tower(request: Request, Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login')
+    current_user = Authorize.get_jwt_subject()
+    result = get_user_under_organization(current_user)
+    return json.dumps(result,ensure_ascii=False)
+
 
 @app.get('/tower', response_class=HTMLResponse)
 async def tower(request: Request, Authorize: AuthJWT = Depends()):
@@ -176,9 +215,23 @@ async def tower(request: Request,company:str,factory:str,department:str,towerGro
     result = []
     for tower in tower_arr:
         result.append({'tower_name': tower,'tower_data': get_tower_info(tower)})
-    print(result)
-    return json.dumps(result,ensure_ascii=False)
     
+    return json.dumps(result,ensure_ascii=False, cls = dateEncode)
+
+@app.get('/tower/performance/{tower_id}', response_class=HTMLResponse)
+async def member_authority(request:Request,tower_id: str,Authorize: AuthJWT = Depends()):
+    """設定成員權限"""
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login') 
+
+    result = get_tower_perform(tower_id)
+    print(result)
+    return json.dumps(result,ensure_ascii=False, cls = dateEncode)
+
+       
 
 @app.get('/optim', response_class=HTMLResponse)
 async def optim(request: Request, Authorize: AuthJWT = Depends()):
@@ -213,8 +266,43 @@ async def vibration(request: Request, Authorize: AuthJWT = Depends()):
     except Exception as e:
         print(e)
         return RedirectResponse('/login')
-    # current_user = Authorize.get_jwt_subject()
-    return templates.TemplateResponse(name='vibration.html', context={'request': request})
+    return templates.TemplateResponse(name='vibration_test.html', context={'request': request})
+
+@app.get('/channel/{tower_id}/{channel_id}', response_class=HTMLResponse)
+async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login')
+    
+    print(find_vibration_id(tower_id,channel_id))
+    result = get_channel_info(find_vibration_id(tower_id,channel_id))
+    return json.dumps(result,ensure_ascii=False, cls = dateEncode)
+
+@app.get('/channel_chart/{tower_id}/{channel_id}', response_class=HTMLResponse)
+async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login')
+    
+    print(find_vibration_id(tower_id,channel_id))
+    result = get_channel_health(find_vibration_id(tower_id,channel_id))
+    return json.dumps(result,ensure_ascii=False, cls = dateEncode)
+
+@app.get('/channel_predict/{tower_id}/{channel_id}', response_class=HTMLResponse)
+async def vibration(request: Request,tower_id:str,channel_id:str,Authorize: AuthJWT = Depends()):
+    try:
+        Authorize.jwt_required()
+    except Exception as e:
+        print(e)
+        return RedirectResponse('/login')
+    
+    #print(find_vibration_id(tower_id,channel_id))
+    result = get_predect_data(find_vibration_id(tower_id,channel_id))
+    return json.dumps(result,ensure_ascii=False, cls = dateEncode)
 
 
 @app.get('/history', response_class=HTMLResponse)
@@ -445,16 +533,15 @@ def user(Authorize: AuthJWT = Depends()):
     current_user = Authorize.get_jwt_subject()
     return {"user": current_user}
 
-@app.get("/example", response_class=HTMLResponse)
+@app.get("/add_data", response_class=HTMLResponse)
 async def example(request: Request,Authorize: AuthJWT = Depends()):
     try:
         Authorize.jwt_required()
     except Exception as e:
         print(e)
         return RedirectResponse('/login')
-    current_user = Authorize.get_jwt_subject()
-    print( current_user)
-    return  current_user
+    add_data()
+    return  templates.TemplateResponse(name='test.html', context={'request': request})
 
 
 @app.get('/health')
@@ -590,6 +677,8 @@ def authenticate_user(username: str, password: str):
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
     if not check_user_exists(username):  # if user don't exist
         return False
+    if not check_user_isEnable(username):
+        return False
     user_dict = next(iter(db.query('SELECT * FROM Water_tower.users where userName ="'+username+'"')))
     user = models.User(**user_dict)
     #if not verify_password(password, user.password):
@@ -669,35 +758,37 @@ def get_role_name(role_id:int):
         role = row['name']
     return role
 
-
+def check_user_isEnable(user_name:str)->bool:
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    cmd = 'SELECT isEnable FROM users where username = "'+str(user_name)+'"'
+    able:bool
+    for row in db.query(cmd) :
+        able = row['isEnable']
+    return able
 
 def get_user_under_organization(user_name:str):
     """查看所屬公司"""
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
     user_role = check_role_type(user_name)
-    #print(user_name,user_role)
+    print(user_name,user_role)
     cmd = 'SELECT * FROM organization'
     result = []
     if int(user_role) == 1 :
-        num=0
         for row in db.query(cmd) :
             company = row['Company']
             factory = row['Factory']
             department = row['Department']
-            result.append({})
             cmd2 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
             group = []
             for row2 in db.query(cmd2):
                 if row2['TowerGroupCode'] not in group :
                     group.append(row2['TowerGroupCode'])
-            result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1} 
-            num = num +1
-
-
+            result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1}) 
+            
     elif int(user_role) == 2:
-        cmd2 = 'SELECT company FROM user WHERE user.username = '+user_name
+        cmd2 = 'SELECT company FROM user WHERE user.username ="'+user_name +'"'
         company_able:str
-        num = 0
+        
         for row in db.query(cmd2) : 
             company_able = row['company']
         for row in db.query(cmd) :
@@ -708,21 +799,21 @@ def get_user_under_organization(user_name:str):
             cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
             group = []
             for row2 in db.query(cmd3):
-                group.append(row2['TowerGroupCode'])
+                if row2['TowerGroupCode'] not in group :
+                    group.append(row2['TowerGroupCode'])
             if company == company_able:
-                result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
+                result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1}) 
             else:
-                result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':0}
-            num = num +1
+                result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0}) 
 
     elif int(user_role) == 3:
-        cmd2 = 'SELECT company,factory FROM users WHERE users.username = '+user_name
+        cmd2 = 'SELECT company,factory FROM users WHERE users.username = "'+user_name +'"'
         company_able:str
         factory_able:str
         num = 0
         for row in db.query(cmd2) : 
-            company = row['company']
-            factory = row['factory']
+            company_able = row['company']
+            factory_able = row['factory']
         for row in db.query(cmd) :
             company = row['Company']
             factory = row['Factory']
@@ -731,22 +822,23 @@ def get_user_under_organization(user_name:str):
             cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
             group = []
             for row2 in db.query(cmd3):
-                group.append(row2['TowerGroupCode'])
+                if row2['TowerGroupCode'] not in group :
+                    group.append(row2['TowerGroupCode'])
             if company == company_able and factory==factory_able:
-                result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
+                result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1}) 
             else:
-                result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':0}
-            num=num+1
+                result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0})
+            
     elif int(user_role) == 4:
-        cmd2 = 'SELECT company,factory,department FROM users WHERE username = '+user_name
+        cmd2 = 'SELECT company,factory,department FROM users WHERE username = "'+user_name +'"'
         company_able:str
         factory_able:str
         department_able:str
-        num = 0
+        
         for row in db.query(cmd2) :
             company_able = row['company']
             factory_able = row['factory']
-            department_able = row['Department']
+            department_able = row['department']
         for row in db.query(cmd) :
             company = row['Company']
             factory = row['Factory']
@@ -755,12 +847,13 @@ def get_user_under_organization(user_name:str):
             cmd3 = 'SELECT TowerGroupCode FROM device WHERE CompanyCode = "' + company + '" AND FactoryCode = "' + factory + '" AND DepartmentCode = "' + department + '"'
             group = []
             for row2 in db.query(cmd3):
-                group.append(row2['TowerGroupCode'])
+                if row2['TowerGroupCode'] not in group :
+                    group.append(row2['TowerGroupCode'])
             if company == company_able and factory==factory_able and department==department_able:
-                result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
+                result.append({'company':company,'factory':factory,'department':department,'group':group,'able':1}) 
             else:
-                result[num] = {'company':company,'factory':factory,'department':department,'group':group,'able':1}
-            num = num +1
+                result.append({'company':company,'factory':factory,'department':department,'group':group,'able':0}) 
+            
     else :
         result =[ {'msg':"error"}]
     return result
@@ -796,20 +889,42 @@ def get_tower_info(tower_id:str):
     """獲取水塔資料"""
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
     cmd = 'SELECT * FROM  `record_dcs` where device_id = "'+tower_id+'"'
-    result ={'DCS':{},'Fan':{},'Moter':{}}
+    result ={'DCS':{},'Fan':{},'Moter':{},'Device_info':{}}
     for row in db.query(cmd) :
         result['DCS'][row['key']]=row['value']
     
     cmd = 'SELECT * FROM  `record_tower` where device_id = "'+tower_id+'"'
     for row in db.query(cmd) :
         result['Fan'][row['key']]=row['value']
+
     result['Moter'] = []
     cmd = 'SELECT * FROM  `vibration` where device_id = "'+tower_id+'"'
+    tmp = {}
     for row in db.query(cmd) :
-        result['Moter'].append({'channel_name':row['channelName'],'Vrms':row['DataValue'],'CV' :row['CVIndex'],'threshold':row['threshold']})
+        for col in db['vibration'].columns :
+                tmp[col] = row[col]
+        result['Moter'].append(tmp)
+        tmp = {}
+ 
+    cmd = 'SELECT * FROM  `device` where id = "'+tower_id+'"'
+    for row in db.query(cmd):
+        for col in db['device'].columns :
+            if col != 'createTime':
+                result['Device_info'][col] = row[col]
 
     return result
 
+def get_tower_perform(tower_id:str):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    cmd = 'SELECT * FROM  `record_performance` where deviceCode = "'+tower_id+'" AND designWFR = 27000'
+    result = [{}]
+    for row in db.query(cmd):
+        for col in db['record_performance'].columns :
+            if col != 'createTime':
+                result[0][col] = row[col]
+    #print(result)
+    return result
+
 def get_tower(company:str,factory:str,department:str,towerGroup:str):
     towergroup_arr =[]
     db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
@@ -817,4 +932,79 @@ def get_tower(company:str,factory:str,department:str,towerGroup:str):
     for row in db.query(cmd) :
         towergroup_arr.append(row['id'])
     
-    return towergroup_arr
+    return towergroup_arr
+
+def check_tower_health(user_name:str):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    org = get_user_under_organization(user_name)
+    #print(org)
+    towers : list
+    result = []
+    for dic in org:
+        #print(dic)
+        if dic['able'] == 1:
+            for group in dic['group']:
+                towers = get_tower(dic['company'],dic['factory'],dic['department'],group)
+                for tower in towers:
+                    cmd = 'SELECT CVIndex,threshold FROM  `vibration` where device_id = "'+tower+'"'
+                    health =1
+                    for row in db.query(cmd) :
+                        if int(row['CVIndex']) < int(row['threshold']):
+                            health = 0
+                    result.append({'company':dic['company'], 'factory':dic['factory'], 'department':dic['department'], 'group': group, 'tower':  tower, 'health': health})
+    return result 
+
+def find_vibration_id(tower_id:str,channel_id:str):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    cmd = 'SELECT id FROM  `vibration` where device_id = "'+tower_id+'" AND channelName = "' +channel_id+'"'
+    for row in db.query(cmd) :
+        return row['id']
+
+def get_channel_info(vibration_id):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    cmd = 'SELECT * FROM  `record_diagnosis` where vibration_id = "'+vibration_id+'"'
+    result = {'CVIndex':'','threshold':''}
+    for row in db.query(cmd) :
+        for col in db['record_diagnosis'].columns :
+                result[col] = row[col]
+        cmd2='SELECT CVIndex,threshold FROM  `vibration` where id = "'+vibration_id+'"'
+        for row2 in db.query(cmd2) :
+            result['CVIndex'] = row['CVIndex']
+            result['threshold'] = row['threshold']
+    print(result)
+    return result
+
+def get_channel_health(vibration_id:str):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    result = []
+    data_name = ['CV_index', 'Vrms' ,'RPM']
+    for row in data_name:
+        result.append({'name':row,'data':[]}) 
+    cmd = 'SELECT * FROM record_health where vibration_id = "'+vibration_id+'"'
+    for row in db.query(cmd) :
+        for dic in result:
+            dic['data'].append(row[dic['name']])
+    return result
+
+def get_predect_data(vibration_id:str):
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    result = {}
+    cmd = 'SELECT * FROM record_prediction_upd where vibration_id = "'+vibration_id+'"'
+    for row in db.query(cmd) :
+        arr = row['predictData'].split(',')
+        result['data']=arr
+
+    return result
+
+
+def add_data():
+    db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/Water_tower?charset=utf8mb4')
+    loc_dt = datetime.today() 
+    loc_dt_format = loc_dt.strftime("%Y-%m-%d %H:%M:%S")
+    cmd = "TRUNCATE TABLE record_health"
+    db.query(cmd)
+    for j in range(1,5):
+        for i in range(0,7):
+            time_del = timedelta(days=i)
+            date=loc_dt-time_del
+            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))