Browse Source

Merge branch 'dev' of http://git.fast-fun.cn:92/lmstack/data_analyze_platform into dev

lmstack 3 years ago
parent
commit
3fba2bc34e
32 changed files with 2811 additions and 431 deletions
  1. 32 11
      LIB/MIDDLE/CellStateEstimation/BatSafetyAlarm/V1_0_1/CBMSSafetyAlarm.py
  2. 46 38
      LIB/MIDDLE/CellStateEstimation/BatSafetyAlarm/main.py
  3. 674 0
      LIB/MIDDLE/CellStateEstimation/BatSafetyWarning/V1_0_1/CBMSBatInterShort.py
  4. 89 0
      LIB/MIDDLE/CellStateEstimation/BatSafetyWarning/V1_0_1/CBMSSafetyWarning.py
  5. 191 0
      LIB/MIDDLE/CellStateEstimation/BatSafetyWarning/main.py
  6. 19 0
      LIB/MIDDLE/CellStateEstimation/Common/BatParam.py
  7. 95 31
      LIB/MIDDLE/CellStateEstimation/Common/V1_0_1/BatParam.py
  8. 2 1
      LIB/MIDDLE/CellStateEstimation/Common/V1_0_1/log.py
  9. 90 0
      LIB/MIDDLE/ExcessTemp/V1_0_0/ExcessTemp.py
  10. BIN
      LIB/MIDDLE/ExcessTemp/V1_0_0/温度过高预警表单.xlsx
  11. 2 0
      LIB/MIDDLE/SaftyCenter/Common/DBDownload.py
  12. 19 1
      LIB/MIDDLE/SaftyCenter/Common/QX_BatteryParam.py
  13. 79 148
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/CBMSBatDiag.py
  14. 37 15
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/DataStatistics.py
  15. 36 0
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/DiagDataMerge.py
  16. 73 0
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/SC_CtrlSafty.py
  17. 356 0
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/SC_SamplingSafty.py
  18. 308 0
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/main.py
  19. 0 0
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/各项目sn号.xlsx
  20. 0 0
      LIB/MIDDLE/SaftyCenter/DataDiag_Static/故障表头及数据类型.xlsx
  21. 0 141
      LIB/MIDDLE/SaftyCenter/DataSta/main.py
  22. 221 0
      LIB/MIDDLE/SaftyCenter/Liplated/BatParam.py
  23. 164 0
      LIB/MIDDLE/SaftyCenter/Liplated/Li_plated.py
  24. 94 0
      LIB/MIDDLE/SaftyCenter/Liplated/main.py
  25. BIN
      LIB/MIDDLE/SaftyCenter/Liplated/析锂.xlsx
  26. 35 0
      LIB/MIDDLE/SaftyCenter/Low_Soc_Alarm/low_soc_alarm.py
  27. 86 0
      LIB/MIDDLE/SaftyCenter/Low_Soc_Alarm/main.py
  28. 1 1
      LIB/MIDDLE/SaftyCenter/diagfault/SC_SamplingSafty.py
  29. 38 44
      LIB/MIDDLE/SaftyCenter/diagfault/main.py
  30. 24 0
      LIB/MIDDLE/SaftyCenter/log.py
  31. BIN
      Low_Soc_Alarm.xlsx
  32. BIN
      df_file.xlsx

+ 32 - 11
LIB/MIDDLE/CellStateEstimation/BatSafetyAlarm/V1_0_1/CBMSSafetyAlarm.py

@@ -42,7 +42,7 @@ class SafetyAlarm:
     
     #寻找当前行数据的所有温度值...................................................................................
     def _celltemp_get(self,num):   
-        celltemp = list(self.df_bms.loc[num,self.celltemp_name])
+        celltemp = np.array(self.df_bms.loc[num,self.celltemp_name])
         return celltemp
 
     #获取当前行所有电压数据............................................................................................
@@ -93,7 +93,7 @@ class SafetyAlarm:
 
                         delttime=(time2-time1).total_seconds()
                         celltemp_rate=(max(temp2-temp1)*60)/delttime    #计算最大温升速率
-                        if celltemp_rate>self.param.TrwTempRate and self.param.CellTempLwLmt<min(temp1) and max(temp1)<self.param.CellTempUpLmt:
+                        if celltemp_rate>self.param.TrwTempRate and self.param.CellTempLwLmt<min(temp1) and max(temp1)<self.param.CellTempUpLmt and max(temp2-temp1)>3:
                             celltemprise=1
                         else:
                             pass
@@ -115,19 +115,41 @@ class SafetyAlarm:
                 pass
             
             #电压诊断功能.........................................................................................................................................
-            cellvolt=self._cellvolt_get(i)
-            cellvolt2=np.array(cellvolt)
-            cellvoltmin=min(cellvolt)
-            cellvoltmax=max(cellvolt)
-            cellvoltmin_index=cellvolt.index(cellvoltmin)
-            cellvoltmax_index=cellvolt.index(cellvoltmax)
+            if i<1:
+                cellvolt2=self._cellvolt_get(i)
+                cellvoltmin2=min(cellvolt2)
+                cellvoltmax2=max(cellvolt2)
+                cellvoltmin_index2=list(cellvolt2).index(cellvoltmin2)
+                cellvoltmax_index2=list(cellvolt2).index(cellvoltmax2)
+                if not self.df_bms_ram.empty:
+                    cellvolt1=np.array(self.df_bms_ram.iloc[-1]['cellvolt'])
+                    cellvoltmin1=min(cellvolt1)
+                    cellvoltmax1=max(cellvolt1)
+                    cellvoltmin_index1=list(cellvolt1).index(cellvoltmin1)
+                    cellvoltmax_index1=list(cellvolt1).index(cellvoltmax1)
+                else:
+                    cellvoltmin1=cellvoltmin2
+                    cellvoltmax1=cellvoltmax2
+                    cellvoltmin_index1=cellvoltmin_index2
+                    cellvoltmax_index1=cellvoltmax_index2
+            else:
+                cellvolt2=self._cellvolt_get(i)
+                cellvoltmin2=min(cellvolt2)
+                cellvoltmax2=max(cellvolt2)
+                cellvoltmin_index2=list(cellvolt2).index(cellvoltmin2)
+                cellvoltmax_index2=list(cellvolt2).index(cellvoltmax2)
+                cellvolt1=self._cellvolt_get(i-1)
+                cellvoltmin1=min(cellvolt1)
+                cellvoltmax1=max(cellvolt1)
+                cellvoltmin_index1=list(cellvolt1).index(cellvoltmin1)
+                cellvoltmax_index1=list(cellvolt1).index(cellvoltmax1)
 
             #电压有效性..........................................................................................................................................
-            if (cellvoltmin<2 and cellvoltmax>4.5 and (cellvoltmax_index-cellvoltmin_index)==1) or cellvoltmin<0.01:   #电压断线故障进入
+            if (cellvoltmin2<2 and cellvoltmax2>4.5 and abs(cellvoltmax_index2-cellvoltmin_index2)==1) or cellvoltmin2<0.01 or (cellvoltmin1<2 and cellvoltmax1>4.5 and abs(cellvoltmax_index1-cellvoltmin_index1)==1) or cellvoltmin1<0.01:   #电压断线故障进入
                 cellvoltvalid=0
             else:
                 cellvoltvalid=1
-   
+
             if cellvoltvalid==1:
                 #单体电压跌落诊断...........................................................................................................................
                 if i<1:
@@ -135,7 +157,6 @@ class SafetyAlarm:
                         time1=self.df_bms_ram.iloc[-1]['time']
                         time2=self.bmstime[i]
                         delttime=(time2-time1).total_seconds()
-                        cellvolt1=np.array(self.df_bms_ram.iloc[-1]['cellvolt'])
                         if delttime<310:
                             if self.packcrnt[i]<0.5 and max(cellvolt1-cellvolt2)>self.param.TrwCellVoltFall:
                                 cellvoltfall=1

+ 46 - 38
LIB/MIDDLE/CellStateEstimation/BatSafetyAlarm/main.py

@@ -1,4 +1,5 @@
 import CBMSSafetyAlarm
+import pymysql
 import datetime
 import pandas as pd
 import multiprocessing
@@ -9,14 +10,33 @@ from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
 
 
 #...................................电池包电芯安全诊断函数......................................................................................................................
-def diag_cal(sn_list, df_diag_ram, df_bms_ram):
-    
-    start=time.time()
+def diag_cal(sn_list, df_bms_ram):
+
+    # start=time.time()
     now_time=datetime.datetime.now()
     start_time=now_time-datetime.timedelta(seconds=70)
     start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
     end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
 
+    #数据库配置
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    user='qx_algo_readonly'
+    password = 'qx@123456'
+
+    #读取故障结果库中code==119且end_time='0000-00-00 00:00:00'...............................
+    db='safety_platform'
+    mysql = pymysql.connect (host=host, port=port, user=user, password=password, database=db)
+    cursor = mysql.cursor()
+    param='start_time,end_time,product_id,code,level,info,advice'
+    tablename='all_fault_info'
+    sql =  "select %s from %s where code=119 and end_time='0000-00-00 00:00:00'" %(param,tablename)
+    cursor.execute(sql)
+    res = cursor.fetchall()
+    df_diag_ram= pd.DataFrame(res,columns=param.split(','))
+    cursor.close()
+    mysql.close()
+
     for sn in sn_list:
         if 'PK500' in sn:
             celltype=1 #6040三元电芯
@@ -37,57 +57,47 @@ def diag_cal(sn_list, df_diag_ram, df_bms_ram):
         dbManager = DBManager.DBManager()
         df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
         df_bms = df_data['bms']
-        # print(df_bms)
+        print(df_bms)
 
         #电池诊断................................................................................................................................................................
-        if not df_bms.empty:
-            df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
-            df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
-            if df_diag_ram_sn.empty:
+        df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
+        df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
+        if df_diag_ram_sn.empty:   
+            if not df_bms.empty:
                 SafetyAlarm=CBMSSafetyAlarm.SafetyAlarm(sn,celltype,df_bms, df_bms_ram_sn)
                 df_diag_res, df_bms_res=SafetyAlarm.diag() 
 
-                #更新bms的ram数据 和 diag的Ram数据
+                #更新bms的ram数据
                 sn_index=df_bms_ram.loc[df_bms_ram['sn']==sn].index
                 df_bms_ram=df_bms_ram.drop(index=sn_index)
                 df_bms_ram=df_bms_ram.append(df_bms_res)
 
-                sn_index=df_diag_ram.loc[df_diag_ram['product_id']==sn].index
-                df_diag_ram=df_diag_ram.drop(index=sn_index)
-                df_diag_ram=df_diag_ram.append(df_diag_res)
-                df_diag_ram.reset_index(inplace=True,drop=True)     #重置索引
-
                 #当前热失控故障写入数据库
                 if not df_diag_res.empty:
-                    with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控.txt','a') as file:
+                    with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控报警.txt','a') as file:
                         file.write(str(tuple(df_diag_res.iloc[-1]))+'\n')
                 
-            #当前热失控已超过三天变为历史故障并写入数据库,并删除原有数据库中的当前故障和ram中的当前故障
-            elif (now_time-df_bms_ram_sn.iloc[-1]['time']).total_seconds()>3*24*3600:
-                df_diag_ram=df_diag_ram.drop(df_diag_ram['sn']==sn)    #删除ram中的当前故障
-                df_bms_ram_sn.iloc[-1]['end_time']=now_time
-                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控.txt','a') as file:
-                        file.write(str(tuple(df_diag_res.iloc[-1]))+'\n')
-
-
-
-        #故障处理........................................................................................................................................................
-
-        end=time.time()
-        print(end-start)
-        # print(df_soh)
-
+        #当前热失控已超过一天变为历史故障并更改数据库
+        else:
+            fault_time=datetime.datetime.strptime(df_diag_ram_sn.iloc[-1]['start_time'], '%Y-%m-%d %H:%M:%S')
+            if (now_time-fault_time).total_seconds()>24*3600:
+                df_diag_ram_sn['end_time']=end_time
+                df_diag_ram_sn['Batpos']=1
+                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\热失控报警.txt','a') as file:
+                    file.write(str(tuple(df_diag_ram_sn.iloc[-1]))+'\n')
+
+        # end=time.time()
+        # print(end-start)
 #...................................................主进程...........................................................................................................
 def mainprocess():
     global SNnums
-    global df_diag_ram
     global df_bms_ram
     process = 2
     pool = multiprocessing.Pool(processes = process)
 
     for i in range(process):
         sn_list = SNnums[i]
-        pool.apply_async(diag_cal, (sn_list,df_diag_ram,df_bms_ram))
+        pool.apply_async(diag_cal, (sn_list,df_bms_ram))
 
     pool.close()
     pool.join()
@@ -110,19 +120,17 @@ if __name__ == "__main__":
     SNnums_C7255=SNdata_C7255['SN号'].tolist()
     SNnums_U7255=SNdata_U7255['SN号'].tolist()
     SNnums=[SNnums_L7255 + SNnums_C7255 + SNnums_U7255, SNnums_6040 + SNnums_4840 + SNnums_6060]
-    # SNnums=['PK50201A000002201']
+    SNnums=[[], ['PK504B10100004447']]
     
     mylog=log.Mylog('log_diag.txt','error')
     mylog.logcfg()
-
-    #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取...................................
-    result=pd.read_excel(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\06BatSafetyAlarm\result.xlsx')
-    df_diag_ram=result[(result['end_time']=='0000-00-00 00:00:00') & (result['code']==119)]
+    
+    #参数初始化
     df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
 
     #定时任务.......................................................................................................................................................................
     scheduler = BlockingScheduler()
-    scheduler.add_job(mainprocess, 'interval', seconds=60, id='diag_job')
+    scheduler.add_job(mainprocess, 'interval', seconds=10, id='diag_job')
 
     try:  
         scheduler.start()

+ 674 - 0
LIB/MIDDLE/CellStateEstimation/BatSafetyWarning/V1_0_1/CBMSBatInterShort.py

@@ -0,0 +1,674 @@
+import pandas as pd
+import numpy as np
+import matplotlib.pyplot as plt
+# from pymysql import paramstyle
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import BatParam
+
+class BatInterShort():
+    def __init__(self,sn,celltype,df_bms,df_soh,df_last,df_last1,df_last2,df_last3,df_lfp):  #参数初始化
+
+        if (not df_lfp.empty) and celltype>50:
+            df_lfp.drop(['sn'],axis=1)
+            df_bms=pd.concat([df_lfp, df_bms], ignore_index=True)
+        else:
+            pass
+
+        self.sn=sn
+        self.celltype=celltype
+        self.param=BatParam.BatParam(celltype)
+        self.df_bms=df_bms
+        self.packcrnt=df_bms['总电流[A]']*self.param.PackCrntDec
+        self.packvolt=df_bms['总电压[V]']
+        self.bms_soc=df_bms['SOC[%]']
+        self.bmstime= pd.to_datetime(df_bms['时间戳'], format='%Y-%m-%d %H:%M:%S')
+
+        self.df_soh=df_soh
+        self.df_last=df_last
+        self.df_last1=df_last1
+        self.df_last2=df_last2
+        self.df_last3=df_last3
+        self.df_lfp=df_lfp
+
+        self.cellvolt_name=['单体电压'+str(x) for x in range(1,self.param.CellVoltNums+1)]
+        self.celltemp_name=['单体温度'+str(x) for x in range(1,self.param.CellTempNums+1)]
+    
+    def intershort(self):
+        if self.celltype<=50:
+            df_res, df_ram_last, df_ram_last1, df_ram_last3=self._ncm_intershort()
+            return df_res, df_ram_last, df_ram_last1,self.df_last2, df_ram_last3,self.df_lfp
+            
+        else:
+            df_res, df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3, df_ram_lfp=self._lfp_intershort()
+            return df_res, df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3, df_ram_lfp
+
+
+    #定义滑动滤波函数....................................................................................
+    def _np_move_avg(self,a, n, mode="same"): 
+        return (np.convolve(a, np.ones((n,)) / n, mode=mode))
+    
+    #寻找当前行数据的最小温度值.............................................................................
+    def _celltemp_weight(self,num):   
+        celltemp = list(self.df_bms.loc[num,self.celltemp_name])
+        celltemp=np.mean(celltemp)
+        self.celltemp=celltemp
+        if self.celltype==99:
+            if celltemp>=25:
+                self.tempweight=1
+                self.StandardStandingTime=3600
+            elif celltemp>=15:
+                self.tempweight=0.6
+                self.StandardStandingTime=7200
+            elif celltemp>=5:
+                self.tempweight=0.
+                self.StandardStandingTime=10800
+            else:
+                self.tempweight=0.1
+                self.StandardStandingTime=10800
+        else:
+            if celltemp>=20:
+                self.tempweight=1
+                self.StandardStandingTime=3600
+            elif celltemp>=10:
+                self.tempweight=0.8
+                self.StandardStandingTime=3600
+            elif celltemp>=5:
+                self.tempweight=0.6
+                self.StandardStandingTime=7200
+            else:
+                self.tempweight=0.2
+                self.StandardStandingTime=10800
+
+    #获取当前行所有电压数据........................................................................................
+    def _cellvolt_get(self,num): 
+        cellvolt = np.array(self.df_bms.loc[num,self.cellvolt_name])/1000
+        return cellvolt
+
+    #获取当前行所有soc差...........................................................................................
+    def _celldeltsoc_get(self,num,dict_baltime,capacity): 
+        cellsoc=[]
+        celldeltsoc=[]
+        for j in range(1, self.param.CellVoltNums+1):   #获取每个电芯电压对应的SOC值
+            cellvolt=self.df_bms.loc[num,'单体电压' + str(j)]/1000
+            ocv_soc=np.interp(cellvolt,self.param.LookTab_OCV,self.param.LookTab_SOC)
+            if j in dict_baltime.keys():
+                ocv_soc=ocv_soc+dict_baltime[j]*self.param.BalCurrent/(capacity*3600)   #补偿均衡电流
+            else:
+                pass
+            cellsoc.append(ocv_soc)
+        
+        if self.celltype==1 or self.celltype==2:
+            consum_num=7
+            cellsoc1=cellsoc[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
+            cellsocmean1=(sum(cellsoc1)-max(cellsoc1)-min(cellsoc1))/(len(cellsoc1)-2)
+            cellsoc2=cellsoc[self.param.CellVoltNums-consum_num:]
+            cellsocmean2=(sum(cellsoc2)-max(cellsoc2)-min(cellsoc2))/(len(cellsoc2)-2)
+            
+            for j in range(len(cellsoc)):   #计算每个电芯的soc差
+                if j<self.param.CellVoltNums-consum_num:
+                    celldeltsoc.append(cellsoc[j]-cellsocmean1)
+                else:
+                    celldeltsoc.append(cellsoc[j]-cellsocmean2)
+            return np.array(celldeltsoc), np.array(cellsoc)
+
+        else:
+            cellsocmean=(sum(cellsoc)-max(cellsoc)-min(cellsoc))/(len(cellsoc)-2)
+            for j in range(len(cellsoc)):   #计算每个电芯的soc差
+                celldeltsoc.append(cellsoc[j]-cellsocmean)
+            return np.array(celldeltsoc), np.array(cellsoc)
+ 
+    #获取所有电芯的As差
+    def _cellDeltAs_get(self,chrg_st,chrg_end,dict_baltime):
+        cellAs=[]
+        celldeltAs=[]
+        for j in range(1, self.param.CellVoltNums+1):   #获取每个电芯电压>峰值电压的充入As数
+            if j in dict_baltime.keys():    #补偿均衡电流
+                As=-self.param.BalCurrent*dict_baltime[j]
+            else:    
+                As=0
+            As_tatol=0
+            symbol=0
+            for m in range(chrg_st+1,chrg_end):
+                As=As-self.packcrnt[m]*(self.bmstime[m]-self.bmstime[m-1]).total_seconds()
+                if symbol<5:
+                    if self.df_bms.loc[m,'单体电压'+str(j)]/1000>self.param.PeakCellVolt[symbol]:
+                        As_tatol=As_tatol+As
+                        symbol=symbol+1
+                    else:
+                        continue
+                else:
+                    cellAs.append(As_tatol/5)
+                    break
+        
+        if self.celltype==99:
+            consum_num=10
+            cellAs1=cellAs[:self.param.CellVoltNums-consum_num]    #切片,将bms耗电的电芯和非耗电的电芯分离开
+            cellAsmean1=(sum(cellAs1)-max(cellAs1)-min(cellAs1))/(len(cellAs1)-2)
+            cellAs2=cellAs[self.param.CellVoltNums-consum_num:]
+            cellAsmean2=(sum(cellAs2)-max(cellAs2)-min(cellAs2))/(len(cellAs2)-2)
+            
+            for j in range(len(cellAs)):   #计算每个电芯的soc差
+                if j<self.param.CellVoltNums-consum_num:
+                    celldeltAs.append(cellAs[j]-cellAsmean1)
+                else:
+                    celldeltAs.append(cellAs[j]-cellAsmean2)
+        else:
+            cellAsmean=(sum(cellAs)-max(cellAs)-min(cellAs))/(len(cellAs)-2)
+            for j in range(len(cellAs)):   #计算每个电芯的soc差
+                celldeltAs.append(cellAs[j]-cellAsmean)
+            
+        return np.array(celldeltAs)
+
+    #计算每个电芯的均衡时长..........................................................................................................................
+    def _bal_time(self,dict_bal):
+        dict_baltime={}
+        dict_baltime1={}
+        for key in dict_bal:
+            count=1
+            x=eval(key)
+            while x>0:
+                if x & 1==1:    #判断最后一位是否为1
+                    if count in dict_baltime.keys():
+                        dict_baltime[count] = dict_baltime[count] + dict_bal[key]
+                    else:
+                        dict_baltime[count] = dict_bal[key]
+                else:
+                    pass
+                count += 1
+                x >>= 1    #右移一位
+        
+        dict_baltime=dict(sorted(dict_baltime.items(),key=lambda dict_baltime:dict_baltime[0]))
+        for key in dict_baltime:    #解析均衡的电芯编号
+            if self.celltype==1:    #科易6040
+                if key<14:
+                    dict_baltime1[key]=dict_baltime[key]
+                elif key<18:
+                    dict_baltime1[key-1]=dict_baltime[key]
+                else:
+                    dict_baltime1[key-3]=dict_baltime[key]
+            elif self.celltype==1:    #科易4840
+                if key<4:
+                    dict_baltime1[key-1]=dict_baltime[key]
+                elif key<8:
+                    dict_baltime1[key-1]=dict_baltime[key]
+                elif key<14:
+                    dict_baltime1[key-3]=dict_baltime[key]
+                elif key<18:
+                    dict_baltime1[key-4]=dict_baltime[key]
+                else:
+                    dict_baltime1[key-6]=dict_baltime[key]
+            else:
+                dict_baltime1=dict_baltime
+        return dict_baltime1
+
+    #三元电池的内短路电流计算...........................................................................................................................................................
+    def _ncm_intershort(self):
+        df_res=pd.DataFrame(columns=['time_st', 'time_sp', 'sn', 'method','short_current','baltime'])
+        df_ram_last=self.df_last
+        df_ram_last1=self.df_last1
+        df_ram_last3=self.df_last3
+
+        #容量初始化
+        if self.df_soh.empty:
+            batsoh=self.df_bms.loc[0,'SOH[%]']
+            capacity=self.param.Capacity*batsoh/100
+        else:
+            batsoh=self.df_soh.loc[len(self.df_soh)-1,'soh']
+            capacity=self.param.Capacity*batsoh/100
+
+        #参数初始化
+        if df_ram_last.empty:  
+            firsttime=1
+            dict_bal={}
+        else:
+            deltsoc_last=df_ram_last.loc[0,'deltsoc']
+            cellsoc_last=df_ram_last.loc[0,'cellsoc']
+            time_last=df_ram_last.loc[0,'time']
+            firsttime=0
+            dict_bal={}
+        if df_ram_last1.empty:
+            firsttime1=1
+            dict_bal1={}
+        else:
+            deltsoc_last1=df_ram_last1.loc[0,'deltsoc1']
+            time_last1=df_ram_last1.loc[0,'time1']
+            firsttime1=0
+            dict_bal1={}
+        if df_ram_last3.empty:
+            standingtime=0
+            standingtime1=0
+        else:
+            standingtime=df_ram_last3.loc[0,'standingtime']
+            standingtime1=df_ram_last3.loc[0,'standingtime1']
+            dict_bal1={}
+            if abs(self.packcrnt[0])<0.01 and standingtime>1 and standingtime1>1:
+                standingtime=standingtime+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
+                standingtime1=standingtime1+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
+            else:
+                pass
+
+        for i in range(1,len(self.df_bms)-1):
+
+            if firsttime1==0:   #满电静置算法--计算均衡状态对应的均衡时间
+                try:
+                    balstat=int(self.df_bms.loc[i,'单体均衡状态'])
+                    if balstat>0.5:
+                        bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
+                        bal_step=int(bal_step)
+                        if str(balstat) in dict_bal1.keys():
+                            dict_bal1[str(balstat)]=dict_bal1[str(balstat)]+bal_step
+                        else:
+                            dict_bal1[str(balstat)]=bal_step
+                    else:
+                        pass
+                except:
+                    dict_bal1={}
+            else:
+                pass
+
+            if abs(self.packcrnt[i]) < 0.1 and abs(self.packcrnt[i-1]) < 0.1 and abs(self.packcrnt[i+1]) < 0.1:     
+                delttime=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
+                standingtime=standingtime+delttime
+                standingtime1=standingtime1+delttime
+                self._celltemp_weight(i)
+
+                #长时间静置法计算内短路-开始.....................................................................................................................................
+                if firsttime==1:    
+                    if standingtime>self.StandardStandingTime*2:      #静置时间满足要求
+                        standingtime=0
+                        cellvolt_now=self._cellvolt_get(i)
+                        cellvolt_min=min(cellvolt_now)
+                        cellvolt_max=max(cellvolt_now)
+                        cellvolt_last=self._cellvolt_get(i-1)
+                        deltvolt=max(abs(cellvolt_now-cellvolt_last))
+
+                        if 2<cellvolt_min<4.5 and 2<cellvolt_max<4.5 and deltvolt<0.005: 
+                            dict_baltime={}   #获取每个电芯的均衡时间
+                            deltsoc_last, cellsoc_last=self._celldeltsoc_get(i,dict_baltime,capacity)
+                            time_last=self.bmstime[i]
+                            firsttime=0
+                            df_ram_last.loc[0]=[self.sn,time_last,deltsoc_last,cellsoc_last]   #更新RAM信息
+                    else:
+                        pass                
+                elif standingtime>3600*10:
+                    standingtime=0
+                    cellvolt_now=self._cellvolt_get(i)
+                    cellvolt_min=min(cellvolt_now)
+                    cellvolt_max=max(cellvolt_now)
+                    cellvolt_last=self._cellvolt_get(i-1)
+                    deltvolt=max(abs(cellvolt_now-cellvolt_last))
+                    
+                    if 2<cellvolt_min<4.5 and 2<cellvolt_max<4.5 and deltvolt<0.005:
+                        dict_baltime=self._bal_time(dict_bal)   #获取每个电芯的均衡时间
+                        deltsoc_now, cellsoc_now=self._celldeltsoc_get(i,dict_baltime,capacity)
+                        time_now=self.bmstime[i]
+                        if -5<max(cellsoc_now-cellsoc_last)<5:
+                            df_ram_last.loc[0]=[self.sn,time_now,deltsoc_now,cellsoc_now] #更新RAM信息
+                            
+                            list_sub=deltsoc_now-deltsoc_last
+                            list_pud=(0.01*capacity*3600*1000)/(time_now-time_last).total_seconds()
+                            leak_current=list_sub*list_pud
+                            # leak_current=np.array(leak_current)
+                            leak_current=np.round(leak_current,3)
+                            leak_current=list(leak_current)
+                            
+                            df_res.loc[len(df_res)]=[time_last,time_now,self.sn,1,str(leak_current),str(dict_baltime)]  #计算结果存入Dataframe
+                            time_last=time_now  #更新时间
+                            deltsoc_last=deltsoc_now    #更新soc差
+                            dict_bal={}
+                        else:
+                            firsttime=1
+                else: 
+                    try:  
+                        balstat=int(self.df_bms.loc[i,'单体均衡状态'])
+                        if balstat>0.5:
+                            bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
+                            bal_step=int(bal_step)
+                            if str(balstat) in dict_bal.keys():
+                                dict_bal[str(balstat)]=dict_bal[str(balstat)]+bal_step
+                            else:
+                                dict_bal[str(balstat)]=bal_step
+                        else:
+                            pass
+                    except:
+                        dict_bal={}
+
+                #满电静置法计算内短路-开始.....................................................................................................................................................
+                if self.StandardStandingTime<standingtime1:  
+                    standingtime1=0
+                    cellvolt_now1=self._cellvolt_get(i)
+                    cellvolt_max1=max(cellvolt_now1)
+                    cellvolt_min1=min(cellvolt_now1)
+                    cellvolt_last1=self._cellvolt_get(i-1)
+                    deltvolt1=max(abs(cellvolt_now1-cellvolt_last1))
+                    cellsoc_now1=np.interp(cellvolt_max1,self.param.LookTab_OCV,self.param.LookTab_SOC)
+
+                    if cellsoc_now1>=self.param.FullChrgSoc-10 and 2<cellvolt_min1<4.5 and 2<cellvolt_max1<4.5 and deltvolt1<0.005:
+                        if firsttime1==1:
+                            dict_baltime1={}   #获取每个电芯的均衡时间
+                            deltsoc_last1, cellsoc_last1=self._celldeltsoc_get(i,dict_baltime1,capacity)
+                            time_last1=self.bmstime[i]
+                            firsttime1=0
+                            df_ram_last1.loc[0]=[self.sn,time_last1,deltsoc_last1]    #更新RAM信息
+                        else:
+                            dict_baltime1=self._bal_time(dict_bal1)   #获取每个电芯的均衡时间
+                            time_now1=self.bmstime[i]
+                            if (time_now1-time_last1).total_seconds()>3600*12:
+                                deltsoc_now1, cellsoc_now1=self._celldeltsoc_get(i,dict_baltime1,capacity)
+                                df_ram_last1.loc[0]=[self.sn,time_now1,deltsoc_now1] #更新RAM信息
+
+                                list_sub1=deltsoc_now1-deltsoc_last1
+                                list_pud1=(0.01*capacity*3600*1000)/(time_now1-time_last1).total_seconds()
+                                leak_current1=list_sub1*list_pud1
+                                # leak_current1=np.array(leak_current1)
+                                leak_current1=np.round(leak_current1,3)
+                                leak_current1=list(leak_current1)
+                                
+                                df_res.loc[len(df_res)]=[time_last1,time_now1,self.sn,2,str(leak_current1),str(dict_baltime1)]  #计算结果存入Dataframe
+                                time_last1=time_now1  #更新时间
+                                deltsoc_last1=deltsoc_now1    #更新soc差
+                                dict_bal1={}
+                            else:
+                                pass
+                    else:
+                        pass
+                else:   
+                    pass
+
+            else:
+                df_ram_last=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])   #电流>0,清空上次静置的SOC差
+                dict_bal={} 
+                firsttime=1
+                standingtime=0
+                standingtime1=0
+                pass
+        
+        #更新RAM的standingtime
+        df_ram_last3.loc[0]=[self.sn,self.bmstime[len(self.bmstime)-1],standingtime,standingtime1]
+
+        #返回计算结果
+        if df_res.empty:    
+            return pd.DataFrame(), df_ram_last, df_ram_last1, df_ram_last3
+        else:
+            return df_res, df_ram_last, df_ram_last1, df_ram_last3
+
+    #磷酸铁锂电池内短路计算程序.............................................................................................................................
+    def _lfp_intershort(self):
+        column_name=['time_st', 'time_sp', 'sn', 'method','short_current','baltime']
+        df_res=pd.DataFrame(columns=column_name)
+        df_ram_last=self.df_last
+        df_ram_last1=self.df_last1
+        df_ram_last2=self.df_last2
+        df_ram_last3=self.df_last3
+        df_ram_lfp=pd.DataFrame(columns=self.df_bms.columns.tolist())
+
+        #容量初始化
+        if self.df_soh.empty:
+            batsoh=self.df_bms.loc[0,'SOH[%]']
+            capacity=self.param.Capacity*batsoh/100
+        else:
+            batsoh=self.df_soh.loc[len(self.df_soh)-1,'soh']
+            capacity=self.param.Capacity*batsoh/100
+        #参数初始化
+        if df_ram_last.empty:  
+            firsttime=1
+            dict_bal={}
+        else:
+            deltsoc_last=df_ram_last.loc[0,'deltsoc']
+            cellsoc_last=df_ram_last.loc[0,'cellsoc']
+            time_last=df_ram_last.loc[0,'time']
+            firsttime=0
+            dict_bal={}
+        if df_ram_last1.empty:
+            firsttime1=1
+            dict_bal1={}
+        else:
+            deltsoc_last1=df_ram_last1.loc[0,'deltsoc1']
+            time_last1=df_ram_last1.loc[0,'time1']
+            firsttime1=0
+            dict_bal1={}
+        if df_ram_last2.empty:
+            firsttime2=1
+            charging=0
+            dict_bal2={}
+        else:
+            deltAs_last2=df_ram_last2.loc[0,'deltAs2']
+            time_last2=df_ram_last2.loc[0,'time2']
+            firsttime2=0
+            charging=0
+            dict_bal2={}
+        if df_ram_last3.empty:
+            standingtime=0
+            standingtime1=0
+        else:
+            standingtime=df_ram_last3.loc[0,'standingtime']
+            standingtime1=df_ram_last3.loc[0,'standingtime1']
+            dict_bal1={}
+            if abs(self.packcrnt[0])<0.01 and standingtime>1 and standingtime1>1:
+                standingtime=standingtime+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
+                standingtime1=standingtime1+(self.bmstime[0]-df_ram_last3.loc[0,'time3']).total_seconds()
+            else:
+                pass
+
+        for i in range(1,len(self.df_bms)-1):
+
+            #静置法计算内短路..........................................................................................................................
+            if firsttime1==0:   #满电静置算法--计算均衡状态对应的均衡时间
+                try:
+                    balstat=int(self.df_bms.loc[i,'单体均衡状态'])
+                    if balstat>0.5:
+                        bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
+                        bal_step=int(bal_step)
+                        if str(balstat) in dict_bal1.keys():
+                            dict_bal1[str(balstat)]=dict_bal1[str(balstat)]+bal_step
+                        else:
+                            dict_bal1[str(balstat)]=bal_step
+                    else:
+                        pass
+                except:
+                    dict_bal1={}
+            else:
+                pass
+
+            if abs(self.packcrnt[i]) < 0.1 and abs(self.packcrnt[i-1]) < 0.1 and abs(self.packcrnt[i+1]) < 0.1:     
+                delttime=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
+                standingtime=standingtime+delttime
+                standingtime1=standingtime1+delttime
+                self._celltemp_weight(i)
+
+                #长时间静置法计算内短路-开始.....................................................................................................................................
+                if firsttime==1:    
+                    if standingtime>self.StandardStandingTime:      #静置时间满足要求
+                        standingtime=0
+                        cellvolt_now=self._cellvolt_get(i)
+                        cellvolt_min=min(cellvolt_now)
+                        cellvolt_max=max(cellvolt_now)
+                        cellvolt_last=self._cellvolt_get(i-1)
+                        deltvolt=max(abs(cellvolt_now-cellvolt_last))
+
+                        if 2<cellvolt_max<self.param.OcvInflexionBelow-0.002 and 2<cellvolt_min<4.5 and abs(deltvolt)<0.003:
+                            dict_baltime={}  #获取每个电芯的均衡时间
+                            deltsoc_last, cellsoc_last=self._celldeltsoc_get(i,dict_baltime,capacity)
+                            time_last=self.bmstime[i]
+                            firsttime=0
+                            df_ram_last.loc[0]=[self.sn,time_last,deltsoc_last,cellsoc_last]   #更新RAM信息
+                        else:
+                            pass
+                    else:
+                        pass                
+                elif standingtime>3600*10:
+                    standingtime=0
+                    cellvolt_now=np.array(self._cellvolt_get(i))
+                    cellvolt_min=min(cellvolt_now)
+                    cellvolt_max=max(cellvolt_now)
+                    cellvolt_last=np.array(self._cellvolt_get(i-1))
+                    deltvolt=max(abs(cellvolt_now-cellvolt_last))
+
+                    if 2<cellvolt_max<self.param.OcvInflexionBelow-0.002 and 2<cellvolt_min<4.5  and abs(deltvolt)<0.003:
+                        dict_baltime=self._bal_time(dict_bal)   #获取每个电芯的均衡时间
+                        deltsoc_now, cellsoc_now=self._celldeltsoc_get(i, dict_baltime,capacity)    #获取每个电芯的SOC差
+                        time_now=self.bmstime[i]
+                        if -5<max(cellsoc_now-cellsoc_last)<5:
+                            df_ram_last.loc[0]=[self.sn,time_now,deltsoc_now,cellsoc_now]   #更新RAM信息
+
+                            list_sub=deltsoc_now-deltsoc_last
+                            list_pud=(0.01*capacity*3600*1000)/(time_now-time_last).total_seconds()
+                            leak_current=list_sub*list_pud
+                            # leak_current=np.array(leak_current)
+                            leak_current=np.round(leak_current,3)
+                            leak_current=list(leak_current)
+                            
+                            df_res.loc[len(df_res)]=[time_last,time_now,self.sn,1,str(leak_current),str(dict_baltime)]  #计算结果存入Dataframe
+                            time_last=time_now  #更新时间
+                            deltsoc_last=deltsoc_now    #更新soc差
+                            dict_bal={}
+                        else:
+                            firsttime=1
+                    else:
+                        pass
+                else: 
+                    try:  
+                        balstat=int(self.df_bms.loc[i,'单体均衡状态'])
+                        if balstat>0.5:
+                            bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
+                            bal_step=int(bal_step)
+                            if str(balstat) in dict_bal.keys():
+                                dict_bal[str(balstat)]=dict_bal[str(balstat)]+bal_step
+                            else:
+                                dict_bal[str(balstat)]=bal_step
+                        else:
+                            pass
+                    except:
+                        dict_bal={}
+
+                #非平台区间静置法计算内短路-开始.....................................................................................................................................................
+                if standingtime1>self.StandardStandingTime: 
+                    standingtime1=0
+                    cellvolt_now1=self._cellvolt_get(i)
+                    cellvolt_max1=max(cellvolt_now1)
+                    cellvolt_min1=min(cellvolt_now1)
+                    cellvolt_last1=self._cellvolt_get(i-1)
+                    deltvolt1=max(abs(cellvolt_now1-cellvolt_last1))
+                
+                    if 2<cellvolt_max1<self.param.OcvInflexionBelow-0.002 and 2<cellvolt_min1<4.5 and deltvolt1<0.005:
+                        if firsttime1==1:
+                            dict_baltime1=self._bal_time(dict_bal1)   #获取每个电芯的均衡时间
+                            deltsoc_last1, cellsoc_last1=self._celldeltsoc_get(i,dict_baltime1,capacity)
+                            time_last1=self.bmstime[i]
+                            firsttime1=0
+                            df_ram_last1.loc[0]=[self.sn,time_last1,deltsoc_last1]    #更新RAM信息
+                        else:
+                            dict_baltime1=self._bal_time(dict_bal1)   #获取每个电芯的均衡时间
+                            deltsoc_now1, cellsoc_now1=self._celldeltsoc_get(i,dict_baltime1,capacity)
+                            time_now1=self.bmstime[i]
+                            df_ram_last1.loc[0]=[self.sn,time_now1,deltsoc_now1]    #更新RAM信息
+
+                            if (time_now1-time_last1).total_seconds()>3600*12:
+                                list_sub1=deltsoc_now1-deltsoc_last1
+                                list_pud1=(0.01*capacity*3600*1000)/(time_now1-time_last1).total_seconds()
+                                leak_current1=list_sub1*list_pud1
+                                # leak_current1=np.array(leak_current1)
+                                leak_current1=np.round(leak_current1,3)
+                                leak_current1=list(leak_current1)
+                                
+                                df_res.loc[len(df_res)]=[time_last1,time_now1,self.sn,2,str(leak_current1),str(dict_baltime1)]  #计算结果存入Dataframe
+                                time_last1=time_now1  #更新时间
+                                deltsoc_last1=deltsoc_now1    #更新soc差
+                                dict_bal1={}
+                            else:
+                                pass
+                    else:
+                        pass
+                else:   
+                    pass
+
+            else:
+                df_ram_last=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])   #电流>0,清空上次静置的SOC差
+                dict_bal={} 
+                firsttime=1
+                standingtime=0
+                standingtime1=0
+                pass
+
+            #获取充电数据——开始..............................................................................................................
+            try:
+                balstat=int(self.df_bms.loc[i,'单体均衡状态'])  #统计均衡状态
+                if balstat>0.5:
+                    bal_step=(self.bmstime[i+1]-self.bmstime[i]).total_seconds()  #均衡步长
+                    bal_step=int(bal_step)
+                    if str(balstat) in dict_bal2.keys():
+                        dict_bal2[str(balstat)]=dict_bal2[str(balstat)]+bal_step
+                    else:
+                        dict_bal2[str(balstat)]=bal_step
+                else:
+                    pass
+            except:
+                dict_bal2={}
+
+            #判断充电状态
+            if self.packcrnt[i]<=-1 and self.packcrnt[i+1]<=-1 and self.packcrnt[i-1]<=-1:
+                if charging==0:
+                    if self.bms_soc[i]<40:
+                        cellvolt_now=self._cellvolt_get(i)
+                        if min(cellvolt_now)<self.param.CellFullChrgVolt-0.15:
+                            charging=1
+                            chrg_start=i
+                        else:
+                            pass
+                    else:
+                        pass
+
+                else: #充电中
+                    cellvolt_now=self._cellvolt_get(i)
+                    if (self.bmstime[i+1]-self.bmstime[i]).total_seconds()>180 or (self.packcrnt[i]>self.param.Capacity/3 and self.packcrnt[i+1]>self.param.Capacity/3):  #如果充电过程中时间间隔>180s,则舍弃该次充电
+                        charging=0
+                        continue
+                    elif min(cellvolt_now)>self.param.CellFullChrgVolt-0.13:   #电压>满充电压-0.13V,即3.37V
+                        self._celltemp_weight(i)
+                        if i-chrg_start>10 and self.celltemp>10:
+                            chrg_end=i+1
+                            charging=0
+
+                            #计算漏电流值...................................................................
+                            if firsttime2==1:
+                                dict_baltime={}
+                                deltAs_last2=self._cellDeltAs_get(chrg_start,chrg_end,dict_baltime)
+                                time_last2=self.bmstime[chrg_end]
+                                df_ram_last2.loc[0]=[self.sn,time_last2,deltAs_last2]    #更新RAM信息
+                            else:
+                                dict_baltime=self._bal_time(dict_bal2)   #获取每个电芯的均衡时间
+                                deltAs_now2=self._cellDeltAs_get(chrg_start,chrg_end,dict_baltime)  #获取每个电芯的As差
+                                time_now2=self.bmstime[chrg_end]
+                                df_ram_last2.loc[0]=[self.sn,time_now2,deltAs_now2]    #更新RAM信息
+
+                                list_sub2=deltAs_now2-deltAs_last2
+                                list_pud2=-1000/(time_now2-time_last2).total_seconds()
+                                leak_current2=list_sub2*list_pud2
+                                # leak_current=np.array(leak_current)
+                                leak_current2=np.round(leak_current2,3)
+                                leak_current2=list(leak_current2)
+
+                                df_res.loc[len(df_res)]=[time_last2,time_now2,self.sn,3,str(leak_current2),str(dict_baltime)]  #计算结果存入Dataframe
+                                deltAs_last2=deltAs_now2
+                                time_last2=time_now2
+                                dict_bal2={}
+
+                        else:
+                            charging=0
+                            continue
+                    elif i==len(self.df_bms)-2:  #数据中断后仍在充电,将前段充电数据写入RAM
+                        df_ram_lfp=self.df_bms.iloc[chrg_start:]
+                        df_ram_lfp['sn']=self.sn
+                    else:
+                        pass
+            else:
+                pass
+
+    
+        #更新RAM
+        df_ram_last3.loc[0]=[self.sn,self.bmstime[len(self.bmstime)-1],standingtime,standingtime1]
+
+        #返回结果
+        if df_res.empty:    
+            return pd.DataFrame(), df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3,df_ram_lfp
+        else:
+            return df_res, df_ram_last, df_ram_last1, df_ram_last2, df_ram_last3, df_ram_lfp

+ 89 - 0
LIB/MIDDLE/CellStateEstimation/BatSafetyWarning/V1_0_1/CBMSSafetyWarning.py

@@ -0,0 +1,89 @@
+import pandas as pd
+import numpy as np
+import datetime
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import BatParam
+
+class SafetyWarning:
+    def __init__(self,sn,celltype,df_short,df_liplated,df_uniform):  #参数初始化
+
+        self.sn=sn
+        self.celltype=celltype
+        self.param=BatParam.BatParam(celltype)
+        self.df_short=df_short
+        self.df_liplated=df_liplated
+        self.df_uniform=df_uniform
+    
+    def diag(self):
+        if self.celltype<=50:
+            df_res=self._warning_diag()
+            return df_res    
+        else:
+            df_res=self._warning_diag()
+            return df_res
+        
+
+    #电池热安全预警诊断功能.................................................................................................
+    def _warning_diag(self):
+
+        df_res=pd.DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
+
+        time=datetime.datetime.now()
+        time_sp='0000-00-00 00:00:00'
+
+        #参数初始化
+        shortfault=0
+        liplatedfault=0
+        uniformfault=0
+
+        for i in range(self.param.CellVoltNums):
+
+            #漏电流故障判断...........................................................................
+            if not self.df_short.empty:
+                short_current=self.df_short['short_current']
+                short_current=short_current.str.replace("[", '')
+                short_current=short_current.str.replace("]", '')
+                self.df_short['cellshort'+str(i+1)]=short_current.map(lambda x:eval(x.split(',')[i]))
+
+                cellshort=self.df_short['cellshort'+str(i+1)]
+                index_list=cellshort[cellshort<self.param.LeakCurrentLv2].index
+                if len(index_list)==2 and (index_list[1]-index_list[0])==1:
+                    shortfault=1
+                elif len(index_list)>3:
+                    shortfault=1
+                else:
+                    shortfault=0
+            
+            #析锂故障判断...............................................................................
+            if not self.df_liplated.empty:
+                liplated=self.df_liplated['liplated_amount']
+                liplated=liplated.str.replace("[", '')
+                liplated=liplated.str.replace("]", '')
+                self.df_liplated['liplated_amount'+str(i+1)]=liplated.map(lambda x:eval(x.split(',')[i]))
+
+                if max(self.df_liplated['liplated_amount'+str(i+1)])>30:
+                    liplatedfault=1
+                else:
+                    liplatedfault=0
+            else:
+                liplatedfault=0
+
+            #电芯SOC排名判断.............................................................................
+            if not self.df_uniform.empty:
+                if (i+1) in self.df_uniform['cellmin_num'].tolist():
+                    uniformfault=1
+                else:
+                    uniformfault=0
+            else:
+                uniformfault=0
+            
+            #电池热安全预警
+            if shortfault==1 and (liplatedfault==1 or uniformfault==1):
+                faultcode=110
+                faultlv=4
+                faultinfo='电芯{}发生热失控安全预警'.format(i+1)
+                faultadvice='联系用户远离电池,立刻召回电池'
+                df_res.loc[0]=[time, time_sp, self.sn, faultcode, faultlv, faultinfo, faultadvice]
+            else:
+                pass
+            
+        return df_res

+ 191 - 0
LIB/MIDDLE/CellStateEstimation/BatSafetyWarning/main.py

@@ -0,0 +1,191 @@
+import pandas as pd
+import pymysql
+from LIB.BACKEND import DBManager, Log
+from apscheduler.schedulers.blocking import BlockingScheduler
+import time, datetime
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
+import CBMSBatInterShort
+import CBMSSafetyWarning
+
+#电池热安全预警核心算法函数......................................................................................................................
+def saftywarning_cal():
+    global SNnums
+    global df_warning_ram
+    global df_warning_ram1
+    global df_warning_ram2
+    global df_warning_ram3
+    global df_lfp_ram
+    global now_time
+
+    now_time=datetime.datetime.now()
+    start_time=now_time-datetime.timedelta(hours=12)
+    start_time1=now_time-datetime.timedelta(days=7)
+    start_time2=now_time-datetime.timedelta(days=90)
+    start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
+    start_time1=start_time1.strftime('%Y-%m-%d %H:%M:%S')
+    end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
+
+    #数据库配置
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    user='qx_read'
+    password='Qx@123456'
+
+    #读取故障结果库中code==110且end_time='0000-00-00 00:00:00'...............................
+    db='safety_platform'
+    mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
+    cursor = mysql.cursor()
+    param='start_time,end_time,product_id,code,level,info,advice'
+    tablename='all_fault_info'
+    sql =  "select %s from %s where code=110 and end_time='0000-00-00 00:00:00'" %(param,tablename)
+    cursor.execute(sql)
+    res = cursor.fetchall()
+    df_fault_ram= pd.DataFrame(res,columns=param.split(','))
+    cursor.close()
+    mysql.close()
+
+    for sn in SNnums:
+        if 'PK500' in sn:
+            celltype=1 #6040三元电芯
+        elif 'PK502' in sn:
+            celltype=2 #4840三元电芯
+        elif 'K504B' in sn:
+            celltype=99    #60ah林磷酸铁锂电芯
+        elif 'MGMLXN750' in sn:
+            celltype=3 #力信50ah三元电芯
+        elif 'MGMCLN750' or 'UD' in sn: 
+            celltype=4 #CATL 50ah三元电芯
+        else:
+            print('SN:{},未找到对应电池类型!!!'.format(sn))
+            continue
+            # sys.exit()
+
+        #读取原始数据库数据........................................................................................................................................................
+        dbManager = DBManager.DBManager()
+        df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
+        df_bms = df_data['bms']
+        # tim=start_time.replace(':','_')
+        # df_bms.to_csv(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\98Download\\'+sn+'_BMS_'+tim+'.csv',encoding='GB18030')
+
+        #读取结果数据库数据........................................................................................................................................................
+        db='qx_cas'
+        mode=1
+        tablename='cellstateestimation_soh'
+        DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
+        with DBRead as DBRead:
+            df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename=tablename, sn=sn, timename='time_sp', st=start_time, sp=end_time)
+
+        if not df_bms.empty:
+            #电池内短路计算................................................................................................................................................................
+            df_warning_ram_sn=df_warning_ram[df_warning_ram['sn']==sn]
+            df_warning_ram_sn1=df_warning_ram1[df_warning_ram1['sn']==sn]
+            df_warning_ram_sn2=df_warning_ram2[df_warning_ram2['sn']==sn]
+            df_warning_ram_sn3=df_warning_ram3[df_warning_ram3['sn']==sn]
+            df_warning_ram_sn.reset_index(inplace=True,drop=True)     #重置索引
+            df_warning_ram_sn1.reset_index(inplace=True,drop=True)     #重置索引
+            df_warning_ram_sn2.reset_index(inplace=True,drop=True)     #重置索引
+            df_warning_ram_sn3.reset_index(inplace=True,drop=True)     #重置索引
+            if celltype>50:
+                df_lfp_ram=df_lfp_ram.reindex(columns=df_bms.columns.tolist()+['sn'])
+                df_lfp_ram_sn=df_lfp_ram[df_lfp_ram['sn']==sn]
+                df_lfp_ram_sn.reset_index(inplace=True,drop=True)     #重置索引
+            else:
+                df_lfp_ram_sn=pd.DataFrame()
+
+            BatShort=CBMSBatInterShort.BatInterShort(sn,celltype,df_bms,df_soh,df_warning_ram_sn,df_warning_ram_sn1,df_warning_ram_sn2,df_warning_ram_sn3,df_lfp_ram_sn)
+            df_short_res, df_ram_res, df_ram_res1, df_ram_res2, df_ram_res3, df_ram_res4=BatShort.intershort() 
+
+            if not df_short_res.empty:
+                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\07BatSafetyWarning\内短路.txt','a') as file:
+                    file.write(str(df_short_res)+'\n')
+
+            #内短路ram处理.........................................................
+            df_warning_ram=df_warning_ram.drop(df_warning_ram[df_warning_ram.sn==sn].index)
+            df_warning_ram1=df_warning_ram1.drop(df_warning_ram1[df_warning_ram1.sn==sn].index)
+            df_warning_ram2=df_warning_ram2.drop(df_warning_ram2[df_warning_ram2.sn==sn].index)
+            df_warning_ram3=df_warning_ram3.drop(df_warning_ram3[df_warning_ram3.sn==sn].index)
+
+            df_warning_ram=pd.concat([df_warning_ram,df_ram_res],ignore_index=True)
+            df_warning_ram1=pd.concat([df_warning_ram1,df_ram_res1],ignore_index=True)
+            df_warning_ram2=pd.concat([df_warning_ram2,df_ram_res2],ignore_index=True)
+            df_warning_ram3=pd.concat([df_warning_ram3,df_ram_res3],ignore_index=True)
+            
+            if celltype>50:
+                df_lfp_ram=df_lfp_ram.drop(df_lfp_ram[df_lfp_ram.sn==sn].index)
+                df_lfp_ram=pd.concat([df_lfp_ram,df_ram_res4],ignore_index=True)
+            
+
+        #电池热安全预警..............................................................................................................................................................
+        #读取内短路、析锂和一致性结果数据库数据
+        db='qx_cas'
+        mode=2
+        tablename1='cellstateestimation_intershort'
+        tablename2='mechanism_liplated'   #析锂表单
+        tablename3='cellstateestimation_uniform_socvoltdiff'
+        DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
+        with DBRead as DBRead:
+            df_short=DBRead.getdata('time_sp,sn,short_current', tablename=tablename1, sn=sn, timename='time_sp', st=start_time1, sp=end_time)
+            df_liplated=DBRead.getdata('time,sn,liplated,liplated_amount', tablename=tablename2, sn=sn, timename='time', st=start_time2, sp=end_time)
+            df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellmin_num', tablename=tablename3, sn=sn, timename='time', st=start_time1, sp=end_time)
+        
+        #获取sn的故障RAM
+        df_fault_ram_sn=df_fault_ram[df_fault_ram['product_id']==sn]
+        
+        #热安全预警
+        if df_fault_ram_sn.empty:
+            BatWarning=CBMSSafetyWarning.SafetyWarning(sn,celltype,df_short,df_liplated,df_uniform)
+            df_warning_res=BatWarning.diag()
+            #当前热失控故障写入数据库
+            if not df_warning_res.empty:
+                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\07BatSafetyWarning\热失控预警.txt','a') as file:
+                    file.write(str(tuple(df_warning_res.iloc[-1]))+'\n')
+        
+        else:
+            fault_time=datetime.datetime.strptime(df_fault_ram_sn.iloc[-1]['start_time'], '%Y-%m-%d %H:%M:%S')
+            if (now_time-fault_time).total_seconds()>24*3600:   #df_warning_end历史故障筛选并更改数据库故障结束时间
+                df_fault_ram_sn['end_time']=end_time
+                df_fault_ram_sn['Batpos']=1
+                with open(r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\07BatSafetyWarning\热失控预警.txt','a') as file:
+                    file.write(str(tuple(df_warning_res.iloc[-1]))+'\n')
+
+
+#...............................................主函数起定时作用.......................................................................................................................
+if __name__ == "__main__":
+    
+    excelpath=r'D:\Platform\platform_python\data_analyze_platform\USER\spf\01qixiang\sn-20210903.xlsx'
+    SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
+    SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
+    SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
+    SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
+    SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
+    SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
+    SNnums_6060=SNdata_6060['SN号'].tolist()
+    SNnums_6040=SNdata_6040['SN号'].tolist()
+    SNnums_4840=SNdata_4840['SN号'].tolist()
+    SNnums_L7255=SNdata_L7255['SN号'].tolist()
+    SNnums_C7255=SNdata_C7255['SN号'].tolist()
+    SNnums_U7255=SNdata_U7255['SN号'].tolist()
+    SNnums=SNnums_L7255 + SNnums_C7255 + SNnums_U7255, SNnums_6040 + SNnums_4840 + SNnums_6060
+    SNnums=['MGMCLN750N215N155']
+    
+    mylog=log.Mylog('log_warning.txt','error')
+    mylog.logcfg()
+
+    #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取...................................
+    df_warning_ram=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])
+    df_warning_ram1=pd.DataFrame(columns=['sn','time1','deltsoc1'])
+    df_warning_ram2=pd.DataFrame(columns=['sn','time2','deltAs2'])
+    df_warning_ram3=pd.DataFrame(columns=['sn','time3','standingtime','standingtime1'])
+    df_lfp_ram=pd.DataFrame()
+
+    #定时任务.......................................................................................................................................................................
+    scheduler = BlockingScheduler()
+    scheduler.add_job(saftywarning_cal, 'interval', hours=12)
+
+    try:  
+        scheduler.start()
+    except Exception as e:
+        scheduler.shutdown()
+        print(repr(e))
+        mylog.logopt(e)

+ 19 - 0
LIB/MIDDLE/CellStateEstimation/Common/BatParam.py

@@ -93,6 +93,25 @@ class BatParam:
             self.LookTab_SOC = [0.00, 	2.40, 	6.38, 	10.37, 	14.35, 	18.33, 	22.32, 	26.30, 	30.28, 	35.26, 	40.24, 	45.22, 	50.20, 	54.19, 	58.17, 	60.16, 	65.14, 	70.12, 	75.10, 	80.08, 	84.06, 	88.05, 	92.03, 	96.02, 	100.00]
             self.LookTab_OCV = [2.7151,	3.0298,	3.1935,	3.2009,	3.2167,	3.2393,	3.2561,	3.2703,	3.2843,	3.2871,	3.2874,	3.2868,	3.2896,	3.2917,	3.2967,	3.3128,	3.3283,	3.3286,	3.3287,	3.3288,	3.3289,	3.3296,	3.3302,	3.3314,	3.3429]
         
+        elif celltype==100:
+            self.Capacity = 228*2
+            self.PackFullChrgVolt=3.65*192
+            self.CellFullChrgVolt=3.5
+            self.OcvInflexionBelow=3.285
+            self.OcvInflexion2=3.296
+            self.OcvInflexion3=3.328
+            self.OcvInflexionAbove=3.4
+            self.CellVoltNums=384
+            self.CellTempNums=64
+            self.FullChrgSoc=98
+            self.PeakSoc=59
+            self.PeakVoltLowLmt=3.35
+            self.PeakVoltUpLmt=3.4
+            self.PeakCellVolt=[3.362,3.363,3.365,3.366,3.367]
+            self.PackCrntDec=1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0.00, 	2.40, 	6.38, 	10.37, 	14.35, 	18.33, 	22.32, 	26.30, 	30.28, 	35.26, 	40.24, 	45.22, 	50.20, 	54.19, 	58.17, 	60.16, 	65.14, 	70.12, 	75.10, 	80.08, 	84.06, 	88.05, 	92.03, 	96.02, 	100.00]
+            self.LookTab_OCV = [2.7151,	3.0298,	3.1935,	3.2009,	3.2167,	3.2393,	3.2561,	3.2703,	3.2843,	3.2871,	3.2874,	3.2868,	3.2896,	3.2917,	3.2967,	3.3128,	3.3283,	3.3286,	3.3287,	3.3288,	3.3289,	3.3296,	3.3302,	3.3314,	3.3429]
         else:
             print('未找到对应电池编号!!!')
             # sys.exit()

+ 95 - 31
LIB/MIDDLE/CellStateEstimation/Common/V1_0_1/BatParam.py

@@ -6,12 +6,6 @@ class BatParam:
         #公用参数................................................................................................................................................
         self.CellTempUpLmt=119
         self.CellTempLwLmt=-39
-        self.CellTempHighLv1=45
-        self.CellTempHighLv2=50
-        self.CellTempLowLv1=-20
-        self.CellTempLowLv2=-25
-        self.CellTempDiffLv1=10
-        self.CellTempDiffLv2=15
         self.CellTempRate=5
 
        #热失控参数
@@ -23,13 +17,13 @@ class BatParam:
         self.TrwCellVoltLow=1.5
         self.TrwPackVoltFall=1.5
 
-        self.SocJump=3
+        self.SocJump=10
         self.SocClamp=0.1
         self.SocLow=3
         self.SocDiff=20
 
-        self.SohLow=65
-        self.SohDiff=20
+        self.SohLow=70
+        self.SohDiff=15
 
         self.OcvWeight_Temp=[-30,-20,-10,0,10,20,30,40,50]
         self.OcvWeight_StandingTime=[0,500,600,1200,1800,3600,7200,10800]
@@ -72,10 +66,15 @@ class BatParam:
             self.PackChgOc=-40
             self.PackDisOc=200
 
-            self.LeakCurrentLv1=10
-            self.LeakCurrentLv2=20
-            self.LeakCurrentLv3=50
-
+            self.LeakCurrentLv1=-10
+            self.LeakCurrentLv2=-20
+            self.LeakCurrentLv3=-50
+            self.CellTempHighLv1=45
+            self.CellTempHighLv2=50
+            self.CellTempLowLv1=-20
+            self.CellTempLowLv2=-25
+            self.CellTempDiffLv1=10
+            self.CellTempDiffLv2=15
         elif celltype==2: #4840
             self.Capacity = 41
             self.PackFullChrgVolt=69.99
@@ -104,10 +103,15 @@ class BatParam:
             self.PackChgOc=-40
             self.PackDisOc=200
 
-            self.LeakCurrentLv1=10
-            self.LeakCurrentLv2=20
-            self.LeakCurrentLv3=50
-
+            self.LeakCurrentLv1=-10
+            self.LeakCurrentLv2=-20
+            self.LeakCurrentLv3=-50
+            self.CellTempHighLv1=45
+            self.CellTempHighLv2=50
+            self.CellTempLowLv1=-20
+            self.CellTempLowLv2=-25
+            self.CellTempDiffLv1=10
+            self.CellTempDiffLv2=15
         elif celltype==3:   #力信50ah三元电芯
             self.Capacity = 51
             self.PackFullChrgVolt=80
@@ -136,10 +140,15 @@ class BatParam:
             self.PackChgOc=-40
             self.PackDisOc=200
 
-            self.LeakCurrentLv1=10
-            self.LeakCurrentLv2=20
-            self.LeakCurrentLv3=50
-
+            self.LeakCurrentLv1=-10
+            self.LeakCurrentLv2=-20
+            self.LeakCurrentLv3=-50
+            self.CellTempHighLv1=45
+            self.CellTempHighLv2=50
+            self.CellTempLowLv1=-20
+            self.CellTempLowLv2=-25
+            self.CellTempDiffLv1=10
+            self.CellTempDiffLv2=15            
         elif celltype==4:   #CATL 50ah三元电芯
             self.Capacity = 50
             self.PackFullChrgVolt=80
@@ -169,10 +178,15 @@ class BatParam:
             self.PackChgOc=-40
             self.PackDisOc=200
 
-            self.LeakCurrentLv1=10
-            self.LeakCurrentLv2=20
-            self.LeakCurrentLv3=50
-
+            self.LeakCurrentLv1=-10
+            self.LeakCurrentLv2=-20
+            self.LeakCurrentLv3=-50
+            self.CellTempHighLv1=45
+            self.CellTempHighLv2=50
+            self.CellTempLowLv1=-20
+            self.CellTempLowLv2=-25
+            self.CellTempDiffLv1=10
+            self.CellTempDiffLv2=15            
         elif celltype==99:   #60ah磷酸铁锂电芯
             self.Capacity = 54
             self.PackFullChrgVolt=69.99
@@ -209,13 +223,63 @@ class BatParam:
             self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
             self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
 
-            self.PackChgOc=-40
-            self.PackDisOc=200
+            self.PackChgOc=-600
+            self.PackDisOc=600
+
+            self.LeakCurrentLv1=-20
+            self.LeakCurrentLv2=-50
+            self.LeakCurrentLv3=-100
+            self.CellTempHighLv1=45
+            self.CellTempHighLv2=50
+            self.CellTempLowLv1=-20
+            self.CellTempLowLv2=-25
+            self.CellTempDiffLv1=10
+            self.CellTempDiffLv2=15                       
+        elif celltype==100:
+                self.Capacity = 228*2
+                self.PackFullChrgVolt=3.65*192
+                self.CellFullChrgVolt=3.5
+                self.OcvInflexionBelow=3.285
+                self.OcvInflexion2=3.296
+                self.OcvInflexion3=3.328
+                self.OcvInflexionAbove=3.4
+                self.CellVoltNums=384
+                self.CellTempNums=64
+                self.FullChrgSoc=98
+                self.PeakSoc=59
+                self.PeakVoltLowLmt=3.35
+                self.PeakVoltUpLmt=3.4
+                self.PeakCellVolt=[3.362,3.363,3.365,3.366,3.367]
+                self.PackCrntDec=1
+                self.BalCurrent=0.015
+                self.LookTab_SOC = [0.00, 	2.40, 	6.38, 	10.37, 	14.35, 	18.33, 	22.32, 	26.30, 	30.28, 	35.26, 	40.24, 	45.22, 	50.20, 	54.19, 	58.17, 	60.16, 	65.14, 	70.12, 	75.10, 	80.08, 	84.06, 	88.05, 	92.03, 	96.02, 	100.00]
+                self.LookTab_OCV = [2.7151,	3.0298,	3.1935,	3.2009,	3.2167,	3.2393,	3.2561,	3.2703,	3.2843,	3.2871,	3.2874,	3.2868,	3.2896,	3.2917,	3.2967,	3.3128,	3.3283,	3.3286,	3.3287,	3.3288,	3.3289,	3.3296,	3.3302,	3.3314,	3.3429]
+                
+                self.CellOvLv1=3.75
+                self.CellOvLv2=3.8
+                
+                self.CellUvLv1=2.3
+                self.CellUvLv2=2.2
+                self.CellVoltDiffLv1=0.6
+                self.CellVoltDiffLv2=1
+                self.PackVoltOvLv1=self.CellOvLv1*self.CellVoltNums
+                self.PackVoltOvLv2=self.CellOvLv2*self.CellVoltNums
+                self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
+                self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
 
-            self.LeakCurrentLv1=20
-            self.LeakCurrentLv2=50
-            self.LeakCurrentLv3=100
+                self.PackChgOc=-600
+                self.PackDisOc=600
+
+                self.LeakCurrentLv1=-20
+                self.LeakCurrentLv2=-50
+                self.LeakCurrentLv3=-100
+                self.CellTempHighLv1=65
+                self.CellTempHighLv2=67
+                self.CellTempLowLv1=-30
+                self.CellTempLowLv2=-35
+                self.CellTempDiffLv1=28
+                self.CellTempDiffLv2=32                            
+            
         else:
             print('未找到对应电池编号!!!')
             # sys.exit()
-

+ 2 - 1
LIB/MIDDLE/CellStateEstimation/Common/V1_0_1/log.py

@@ -17,7 +17,8 @@ class Mylog:
                 Level=logging.WARNING
             else:
                 Level=logging.ERROR
-        logging.basicConfig(filename=r'D:\Work\Code_write\data_analyze_platform\USER\lzx\SaftyCenter_CODE_V1_1_DIDI\\'+self.name, level=Level,format='%(asctime)s - %(levelname)s - %(message)s')
+        logging.basicConfig(filename=r'D:\ZLWORK\code\data_analyze_platform\USER\eric\\'+self.name, level=Level,format='%(asctime)s - %(levelname)s - %(message)s')
+
 
     def logopt(self,*info):
         logging.error(info)

+ 90 - 0
LIB/MIDDLE/ExcessTemp/V1_0_0/ExcessTemp.py

@@ -0,0 +1,90 @@
+from LIB.BACKEND import DBManager
+dbManager = DBManager.DBManager()
+import pandas as pd
+import numpy as np
+import datetime
+import seaborn as sns
+import matplotlib.pyplot as plt
+
+now_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')   #type: str
+now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')     #type: datetime
+start_time=now_time-datetime.timedelta(minutes=1)
+end_time=str(now_time)
+start_time=str(start_time)
+
+def makedataset(cellname):
+    dataset = pd.DataFrame()
+    for k in range(len(cellname)):
+        sn = cellname[k]
+        datasn = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
+        datasn = datasn['bms']
+        datasn['SN号']=sn
+        if len(datasn)>0:
+            datasn=datasn.iloc[-1]
+            dataset=dataset.append(datasn)
+    return dataset
+
+fileNamesPK504 = pd.read_excel('sn-20210903.xlsx',sheet_name='科易6060')
+fileNamesPK500 = pd.read_excel('sn-20210903.xlsx',sheet_name='科易6040')
+fileNamesPK502 = pd.read_excel('sn-20210903.xlsx',sheet_name='科易4840')
+fileNamesMGML = pd.read_excel('sn-20210903.xlsx',sheet_name='格林美-力信7255')
+fileNamesMGMC = pd.read_excel('sn-20210903.xlsx',sheet_name='格林美-CATL7255')
+fileNamesUDO = pd.read_excel('sn-20210903.xlsx',sheet_name='优旦7255')
+
+dataPK504=makedataset(list(fileNamesPK504['SN号']))
+dataPK500=makedataset(list(fileNamesPK500['SN号']))
+dataPK502=makedataset(list(fileNamesPK502['SN号']))
+dataMGML=makedataset(list(fileNamesMGML['SN号']))
+dataMGMC=makedataset(list(fileNamesMGMC['SN号']))
+dataUDO=makedataset(list(fileNamesUDO['SN号']))
+
+dataPK504=dataPK504[['SN号','单体温度1','单体温度2','单体温度3','单体温度4','其他温度2','其他温度4','其他温度5']]
+dataPK500=dataPK500[['SN号','单体温度1','单体温度2','单体温度3','单体温度4','其他温度2','其他温度3','其他温度4','其他温度5']]
+dataPK502=dataPK502[['SN号','单体温度1','单体温度2','单体温度3','单体温度4','其他温度2','其他温度3','其他温度4','其他温度5']]
+dataMGML=dataMGML[['SN号','单体温度1','单体温度2','单体温度3','单体温度4','其他温度1','其他温度3','其他温度4','其他温度5','其他温度6']]
+dataMGMC=dataMGMC[['SN号','单体温度1','单体温度2']]
+dataUDO=dataUDO[['SN号','单体温度1','单体温度2']]
+
+datatotal1=pd.concat([dataPK504,dataPK500,dataPK502])
+datatotal2=pd.concat([dataMGMC,dataUDO])
+
+def calculavg(datacell):
+    avg_temp=[]
+    max_temp=[]
+    min_temp=[]
+    for i in range(len(datacell)):
+        avg_temp.append(np.mean(datacell.iloc[i,1:]))
+        max_temp.append(max(datacell.iloc[i,1:]))
+        min_temp.append(min(datacell.iloc[i,1:]))
+    datacell['平均温度']=avg_temp
+    datacell['最高温度']=max_temp
+    datacell['最低温度']=min_temp
+    return datacell
+
+datatotal1=calculavg(datatotal1)
+datatotal2=calculavg(datatotal2)
+dataMGML=calculavg(dataMGML)
+datatotal1=datatotal1[datatotal1['最低温度']>-40]
+datatotal2=datatotal2[datatotal2['最低温度']>-40]
+dataMGML=dataMGML[dataMGML['最低温度']>-40]
+datatotal1=datatotal1.reset_index(drop=True)
+datatotal2=datatotal2.reset_index(drop=True)
+dataMGML=dataMGML.reset_index(drop=True)
+
+def boxplot_fill(col,a):
+    # 计算iqr:数据四分之三分位值与四分之一分位值的差
+    iqr = col.quantile(0.75)-col.quantile(0.25)
+    # 根据iqr计算异常值判断阈值
+    u_th = col.quantile(0.75) + a*iqr # 上界
+    l_th = col.quantile(0.25) - a*iqr # 下界
+    # 定义转换函数:如果数字大于上界则用上界值填充,小于下界则用下界值填充。
+    return l_th,u_th
+
+uptemp_out1=list(boxplot_fill(datatotal1['最高温度'],2.5))[1]
+uptemp_out2=list(boxplot_fill(datatotal2['最高温度'],5))[1]
+uptemp_out3=list(boxplot_fill(dataMGML['最高温度'],3.5))[1]
+
+anomalies1 = datatotal1[(datatotal1['最高温度']>uptemp_out1) & (datatotal1['最高温度']<120) & (datatotal1['最高温度']!=datatotal1['单体温度4']) & (datatotal1['单体温度4']<50) & (datatotal1['最高温度']!=datatotal1['其他温度2']) & (datatotal1['其他温度2']<50)]
+anomalies2 = datatotal2[(datatotal2['最高温度']>uptemp_out2) & (datatotal2['最高温度']<120)]
+anomalies3 = dataMGML[(dataMGML['最高温度']>uptemp_out3) & (dataMGML['最高温度']<120)]
+anomalies=pd.concat([anomalies1,anomalies2,anomalies3])

BIN
LIB/MIDDLE/ExcessTemp/V1_0_0/温度过高预警表单.xlsx


+ 2 - 0
LIB/MIDDLE/SaftyCenter/Common/DBDownload.py

@@ -51,6 +51,8 @@ class DBDownload:
             self.cursor.execute("select %s from %s where factory='%s'" %(str,tablename,factory))
         elif self.mode==3:
             self.cursor.execute("select %s from %s" %(str,tablename))
+        elif self.mode==4:
+            self.cursor.execute("select %s from %s where qrcode='%s' order by id desc limit 1" %(str,tablename,sn))
         res = self.cursor.fetchall()
         df_res = pd.DataFrame(res, columns=param)
         df_res = df_res.reset_index(drop=True)

+ 19 - 1
LIB/MIDDLE/SaftyCenter/Common/QX_BatteryParam.py

@@ -113,7 +113,25 @@ class BatteryInfo():
             self.CantChrgVol=2.6
  
 
-
+        elif celltype==100:
+            self.Capacity = 228*2
+            self.PackFullChrgVolt=3.65*192
+            self.CellFullChrgVolt=3.5
+            self.OcvInflexionBelow=3.285
+            self.OcvInflexion2=3.296
+            self.OcvInflexion3=3.328
+            self.OcvInflexionAbove=3.4
+            self.CellVoltNums=384
+            self.CellTempNums=64
+            self.FullChrgSoc=98
+            self.PeakSoc=59
+            self.PeakVoltLowLmt=3.35
+            self.PeakVoltUpLmt=3.4
+            self.PeakCellVolt=[3.362,3.363,3.365,3.366,3.367]
+            self.PackCrntDec=1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0.00, 	2.40, 	6.38, 	10.37, 	14.35, 	18.33, 	22.32, 	26.30, 	30.28, 	35.26, 	40.24, 	45.22, 	50.20, 	54.19, 	58.17, 	60.16, 	65.14, 	70.12, 	75.10, 	80.08, 	84.06, 	88.05, 	92.03, 	96.02, 	100.00]
+            self.LookTab_OCV = [2.7151,	3.0298,	3.1935,	3.2009,	3.2167,	3.2393,	3.2561,	3.2703,	3.2843,	3.2871,	3.2874,	3.2868,	3.2896,	3.2917,	3.2967,	3.3128,	3.3283,	3.3286,	3.3287,	3.3288,	3.3289,	3.3296,	3.3302,	3.3314,	3.3429]
 
 
         else:

+ 79 - 148
LIB/MIDDLE/SaftyCenter/diagfault/CBMSBatDiag.py → LIB/MIDDLE/SaftyCenter/DataDiag_Static/CBMSBatDiag.py

@@ -45,7 +45,7 @@ class BatDiag:
 
     #获取当前行所有电压数据............................................................................................
     def _cellvolt_get(self,num): 
-        cellvolt = np.array(self.df_bms.loc[num,self.cellvolt_name]/1000)
+        cellvolt = list(self.df_bms.loc[num,self.cellvolt_name]/1000)
         return cellvolt
 
     #..........................................三元电池诊断功能..................................................................
@@ -92,7 +92,7 @@ class BatDiag:
                 else:   #ram当前故障中有该故障,则判断是否退出该故障
                     if celltempmax0<self.param.CellTempHighLv1-5 and celltempmax1<self.param.CellTempHighLv1-5:    #二级高温恢复
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==4].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==4].index, 'end_time'] = time
                     else:
                         pass
             
@@ -110,7 +110,7 @@ class BatDiag:
                 else:   #ram当前故障中有该故障,则判断是否退出该故障
                     if celltempmax0>self.param.CellTempLowLv1+2 and celltempmax1>self.param.CellTempLowLv1+2:    #二级高温恢复
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==6].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==6].index, 'end_time'] = time
                     else:
                         pass
               
@@ -128,7 +128,7 @@ class BatDiag:
                 else:   #ram当前故障中有该故障,则判断是否退出该故障
                     if (celltempmax0-celltempmin0)<self.param.CellTempDiffLv1-2 and (celltempmax1-celltempmax0)>self.param.CellTempDiffLv1-2:  #二级温差恢复
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==8].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==8].index, 'end_time'] = time
                     else:
                         pass
 
@@ -137,12 +137,12 @@ class BatDiag:
                 delttime=(time2-time1).total_seconds()
                 if delttime>20:
                     temp2=np.array(self._celltemp_get(i))
-                    celltemp_rate=(max(temp2-temp1)*60)/delttime    #计算最大温升速率
+                    celltemp_rate=round((max(temp2-temp1)*60)/delttime,2)    #计算最大温升速率
                     temp1=temp2 #更新初始温度
                     time1=time2 #更新初始时间
-                    if celltemp_rate>self.param.CellTempRate:
-                        temprate_cnt=temprate_cnt+1
-                        if not 9 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
+                    if not 9 in list(self.df_diag_ram['code']):#当前故障中没有该故障,则判断是否发生该故障
+                        if celltemp_rate>self.param.CellTempRate:
+                            temprate_cnt=temprate_cnt+1
                             if temprate_cnt>2:  #温升故障进入
                                 time=self.bmstime[i]
                                 code=9
@@ -153,11 +153,11 @@ class BatDiag:
                             else:
                                 pass
                         else:   #ram当前故障中有该故障,则判断是否退出该故障
-                            if celltemp_rate<self.param.CellTempRate-1: #温升故障恢复
-                                time=self.bmstime[i]
-                                self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==9].index, 'end_time'] = time
+                           pass
                     else:
-                        pass
+                        if celltemp_rate<self.param.CellTempRate-1: #温升故障恢复
+                            time=self.bmstime[i]
+                            self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==9].index, 'end_time'] = time
                 else:
                     pass
             
@@ -183,7 +183,7 @@ class BatDiag:
                     if cellvoltmax0>self.param.CellOvLv2 and cellvoltmax1>self.param.CellOvLv2:  #二级过压进入
                         time=self.bmstime[i]
                         code=12
-                        faultlv=3
+                        faultlv=4
                         faultinfo='电芯{}过压二级'.format(cellvolt1.index(cellvoltmax1)+1)
                         faultadvice='联系用户询问用车场景,技术介入诊断'
                         self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
@@ -192,7 +192,7 @@ class BatDiag:
                 else:   #ram当前故障中有该故障,则判断是否退出该故障
                     if cellvoltmax0<self.param.CellOvLv1-0.05 and cellvoltmax1<self.param.CellOvLv1-0.05:   #二级过压故障恢复
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==12].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==12].index, 'end_time'] = time
                     else:
                         pass
               
@@ -211,7 +211,7 @@ class BatDiag:
                 else:
                     if cellvoltmin0>self.param.CellUvLv1+0.1 and cellvoltmin1>self.param.CellUvLv1+0.1:
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==14].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==14].index, 'end_time'] = time
                     else:
                         pass
              
@@ -229,7 +229,7 @@ class BatDiag:
                 else:
                     if (cellvoltmax0-cellvoltmin0)<self.param.CellVoltDiffLv1-0.05 and (cellvoltmax1-cellvoltmin1)>self.param.CellVoltDiffLv1-0.05: #二级欠压恢复
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==16].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==16].index, 'end_time'] = time
                     else:
                         pass
             else:
@@ -240,7 +240,7 @@ class BatDiag:
                 if self.packvolt[i-1]>self.param.PackVoltOvLv2 and self.packvolt[i]>self.param.PackVoltOvLv2:   #电池包过压二级进入
                     time=self.bmstime[i]
                     code=18
-                    faultlv=3
+                    faultlv=4
                     faultinfo='电池包过压二级'
                     faultadvice='联系用户询问用车场景,技术介入诊断'
                     self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
@@ -249,7 +249,7 @@ class BatDiag:
             else:
                 if self.packvolt[i-1]<self.param.PackVoltOvLv1-0.05*self.param.CellVoltNums and self.packvolt[i]<self.param.PackVoltOvLv1-0.05*self.param.CellVoltNums: #电池包过压二级恢复
                     time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==18].index, 'end_time'] = time
+                    self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==18].index, 'end_time'] = time
                 else:
                     pass
           
@@ -267,14 +267,14 @@ class BatDiag:
             else:
                 if self.packvolt[i-1]>self.param.PackVoltUvLv1+0.1*self.param.CellVoltNums and self.packvolt[i]>self.param.PackVoltUvLv1+0.1*self.param.CellVoltNums:   #电池包二级欠压恢复
                     time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==20].index, 'end_time'] = time
+                    self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==20].index, 'end_time'] = time
                 else:
                     pass
             
             #电流过流诊断.......................................................................................................................
             step=(self.bmstime[i]-self.bmstime[i-1]).total_seconds()
             if step<120 and self.packcrnt[i]>self.param.PackDisOc:
-                as_dis=as_dis+(self.packcrnt[i]-self.param.self.PackDisOc)*step    #ah累计
+                as_dis=as_dis+(self.packcrnt[i]-self.param.PackDisOc)*step    #ah累计
             elif step<120 and self.packcrnt[i]<self.param.PackChgOc:
                 as_chg=as_chg+(self.param.PackDisOc-self.packcrnt[i])*step    #ah累计
             else:
@@ -294,7 +294,7 @@ class BatDiag:
             else:
                 if self.packcrnt[i-1]<self.param.PackDisOc-10 and self.packcrnt[i]<self.param.PackDisOc-10:
                     time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==22].index, 'end_time'] = time
+                    self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==22].index, 'end_time'] = time
                 else:
                     pass
             
@@ -311,7 +311,7 @@ class BatDiag:
             else:
                 if self.packcrnt[i-1]>self.param.PackChgOc+10 and self.packcrnt[i]>self.param.PackChgOc+10:
                     time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==22].index, 'end_time'] = time
+                    self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==22].index, 'end_time'] = time
                 else:
                     pass
 
@@ -337,7 +337,7 @@ class BatDiag:
                 else:
                     if abs(bmssoc_now-bmssoc_st)>self.param.SocClamp:   #SOC卡滞故障退出
                         time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==27].index, 'end_time'] = time
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==27].index, 'end_time'] = time
                     else:
                         pass
                 bmssoc_st=bmssoc_now
@@ -346,64 +346,61 @@ class BatDiag:
                 pass
 
             #SOC跳变....................................................................................................................
-            if step<30: 
-                bmssoc_last=float(self.bms_soc[i-1])
-                bmssoc_now=float(self.bms_soc[i])
-                if not 28 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
-                    if abs(bmssoc_now-bmssoc_last)>self.param.SocJump:  #SOC跳变进入
-                        time=self.bmstime[i]
-                        code=28
-                        faultlv=1
-                        faultinfo='电池SOC跳变'
-                        faultadvice='技术介入诊断,检修电池BMS软件'
-                        self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
-                    else:
-                        pass
-                else:   
-                    if abs(bmssoc_now-bmssoc_st)<self.param.SocJump:    #SOC跳变故障退出
-                        time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==28].index, 'end_time'] = time
-                    else:
-                        pass
-            else:
-                pass
-
-            #SOC过低故障报警............................................................................................................
-            if not 26 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
-                if self.bms_soc[i-1]<self.param.SocLow and self.bms_soc[i]<self.param.SocLow:   #SOC过低故障进入
-                    time=self.bmstime[0]
-                    code=26
+            bmssoc_last=float(self.bms_soc[i-1])
+            bmssoc_now=float(self.bms_soc[i])
+            if not 28 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
+                if step<30 and abs(bmssoc_now-bmssoc_last)>self.param.SocJump:  #SOC跳变进入
+                    time=self.bmstime[i]
+                    code=28
                     faultlv=1
-                    faultinfo='电池包电量过低'
-                    faultadvice='联系用户,请立刻充电'
+                    faultinfo='电池SOC跳变'
+                    faultadvice='技术介入诊断,检修电池BMS软件'
                     self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
                 else:
                     pass
-            else:   
-                if self.bms_soc[i-1]>self.param.SocLow and self.bms_soc[i]>self.param.SocLow:   #SOC过低故障退出
+            else:
+                if abs(bmssoc_now-bmssoc_st)<self.param.SocJump:    #SOC跳变故障退出
                     time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==26].index, 'end_time'] = time
+                    self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==28].index, 'end_time'] = time
                 else:
                     pass
 
-            #BMS故障报警........................................................................................................
-            if not 1 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
-                if self.bmsfault1[i-1] is None or self.bmsfault1[i] is None:
-                    self.bmsfault1[i-1]=0
-                    self.bmsfault1[i]=0
-                if self.bmsfault1[i-1]>0 or self.bmsfault1[i]>0:   #BMS故障进入
-                    time=self.bmstime[0]
-                    code=1
-                    faultlv=2
-                    faultinfo='BMS故障报警:{}'.format(self.bmsfault1[i-1])
-                    faultadvice='技术介入诊断'
-                    self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
-                else:
-                    pass
-            else:
-                if self.bmsfault1[i-1]==0 and self.bmsfault1[i]==0:   #BMS故恢复
-                    time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==1].index, 'end_time'] = time
+            # #SOC过低故障报警............................................................................................................
+            # if not 26 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
+            #     if self.bms_soc[i-1]<self.param.SocLow and self.bms_soc[i]<self.param.SocLow:   #SOC过低故障进入
+            #         time=self.bmstime[i]
+            #         code=26
+            #         faultlv=1
+            #         faultinfo='电池包电量过低'
+            #         faultadvice='联系用户,请立刻充电'
+            #         self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
+            #     else:
+            #         pass
+            # else:   
+            #     if self.bms_soc[i-1]>self.param.SocLow and self.bms_soc[i]>self.param.SocLow:   #SOC过低故障退出
+            #         time=self.bmstime[i]
+            #         self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==26].index, 'end_time'] = time
+            #     else:
+            #         pass
+
+            # #BMS故障报警........................................................................................................
+            # if not 1 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
+            #     if self.bmsfault1[i-1] is None or self.bmsfault1[i] is None:
+            #         self.bmsfault1[i-1]=0
+            #         self.bmsfault1[i]=0
+            #     if self.bmsfault1[i-1]>0 or self.bmsfault1[i]>0:   #BMS故障进入
+            #         time=self.bmstime[0]
+            #         code=1
+            #         faultlv=2
+            #         faultinfo='BMS故障报警:{}'.format(self.bmsfault1[i-1])
+            #         faultadvice='技术介入诊断'
+            #         self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
+            #     else:
+            #         pass
+            # else:
+            #     if self.bmsfault1[i-1]==0 and self.bmsfault1[i]==0:   #BMS故恢复
+            #         time=self.bmstime[i]
+            #         self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==1].index, 'end_time'] = time
         
         
         #SOC一致性故障报警..........................................................................................................
@@ -414,15 +411,15 @@ class BatDiag:
                     time=self.bmstime[0]
                     code=25
                     faultlv=1
-                    faultinfo='电芯{}和{}SOC差过大:{}'.format(self.df_uniform.loc[0,'cellmin_num'],self.df_uniform.loc[0,'cellmax_num']),cellsoc_diff
+                    faultinfo='电芯{}和{}SOC差过大:{}'.format(self.df_uniform.loc[0,'cellmin_num'],self.df_uniform.loc[0,'cellmax_num'],cellsoc_diff)
                     faultadvice='技术介入诊断'
                     self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
                 else:
                     pass
             else:
                 if cellsoc_diff<self.param.SocDiff: #SOC一致性差故障恢复
-                    time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==25].index, 'end_time'] = time
+                    time=self.bmstime[0]
+                    self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==25].index, 'end_time'] = time
         else:
             cellsoc_diff=3
 
@@ -434,7 +431,7 @@ class BatDiag:
             cellsoh_lowindex=np.argwhere(cellsoh<self.param.SohLow)
             cellsoh_lowindex=cellsoh_lowindex+1
             if self.celltype==1 or self.celltype==2 or self.celltype==3 or self.celltype==4: 
-                cellsoh_diff=max(cellsoh)-min(cellsoh)
+                cellsoh_diff=np.max(cellsoh)-np.min(cellsoh)
                 if not 23 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
                     if soh<self.param.SohLow:   #soh过低故障进入
                         time=self.bmstime[0]
@@ -447,8 +444,8 @@ class BatDiag:
                         pass
                 else:
                     if soh>self.param.SohLow+2:   #soh过低故障恢复
-                        time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==23].index, 'end_time'] = time
+                        time=self.bmstime[0]
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==23].index, 'end_time'] = time
                     else:
                         pass
 
@@ -464,8 +461,8 @@ class BatDiag:
                         pass
                 else:
                     if cellsoh_diff<self.param.SohDiff-2:
-                        time=self.bmstime[i]
-                        self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==24].index, 'end_time'] = time
+                        time=self.bmstime[0]
+                        self.df_diag_ram.loc[self.df_diag_ram[self.df_diag_ram['code']==24].index, 'end_time'] = time
                     else:
                         pass
             else:
@@ -488,70 +485,4 @@ class BatDiag:
         if not df_res.empty:
             return df_res
         else:
-            return pd.DataFrame()
-
-#............................................................内短路故障诊断.............................................................................
-class ShortDiag():
-    def __init__(self,sn,celltype,df_short):  #参数初始化
-
-        self.sn=sn
-        self.celltype=celltype
-        self.param=BatParam.BatParam(celltype)
-        self.df_short=df_short
-
-    def shortdiag(self):
-        if len(self.df_short)>1:
-            df_res=self._short_diag()
-            return df_res
-        else:
-            return pd.DataFrame()
-
-    #内短路故障检测...................................................................................................................................
-    def _short_diag(self):
-        column_name=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice']
-        df_res=pd.DataFrame(columns=column_name)
-        time=datetime.datetime.now()
-        end_time=datetime.datetime.strftime('0000-00-00 00:00:00')
-        end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d %H:%M:%S')
-
-        # if self.df_diag.empty:
-        #     health_state=100
-        # else:
-        #     health_state=self.df_diag.loc[0,'health_state']
-
-        for i in range(self.param.CellVoltNums):
-            #将字符串分割为多列
-            short_current=self.df_short['short_current']
-            short_current=short_current.str.replace("[", '')
-            short_current=short_current.str.replace("]", '')
-            self.df_short['cellshort'+str(i+1)]=short_current.map(lambda x:x.split(',')[i])
-            self.df_short['cellshort'+str(i+1)]=self.df_short['cellshort'+str(i+1)].map(lambda x:eval(x))
-
-            #漏电流故障判断
-            cellshort=np.array(self.df_short['cellshort'+str(i+1)])
-            shortlv3=np.sum(cellshort>self.param.LeakCurrentLv3)
-            shortlv2=np.sum(cellshort>self.param.LeakCurrentLv2)-shortlv3
-            shortlv1=np.sum(cellshort>self.param.LeakCurrentLv1)-shortlv2-shortlv3
-            shortlv=shortlv3*3 + shortlv2*2 + shortlv1
-
-            if not 31 in list(self.df_diag_ram['code']):  #当前故障中没有该故障,则判断是否发生该故障
-                if shortlv>=5:
-                    time=self.bmstime[0]
-                    code=31
-                    faultlv=3
-                    faultinfo='电芯{}发生严重内短路'.format(i+1)
-                    faultadvice='禁止充放电,检修电池'
-                    self.df_diag_ram.loc[len(self.df_diag_ram)]=[time, end_time, self.sn, code, faultlv, faultinfo, faultadvice]
-                else:
-                    pass
-            else:
-                if shortlv<3:
-                    time=self.bmstime[i]
-                    self.df_diag_ram[self.df_diag_ram[self.df_diag_ram['code']==31].index, 'end_time'] = time
-        
-        if not df_res.empty:
-            return df_res
-        else:
-            return pd.DataFrame()
-
-
+            return pd.DataFrame()

+ 37 - 15
LIB/MIDDLE/SaftyCenter/DataSta/DataStatistics.py → LIB/MIDDLE/SaftyCenter/DataDiag_Static/DataStatistics.py

@@ -10,24 +10,27 @@ from apscheduler.schedulers.blocking import BlockingScheduler
 class DataSta():
     def __init__(self) -> None:
         pass
-    def SaftyWarningSta(CS_Data,df_fltinfo,start_time,end_time):
+    def SaftyWarningSta(df_fltinfo,start_time,end_time):
+        start_time=datetime.datetime.strptime(start_time, '%Y-%m-%d')
+        start_time=start_time+datetime.timedelta(days=1)
+        start_time=start_time.strftime('%Y-%m-%d')
         SftyPlt_Data_Total=len(df_fltinfo)#总报警数
-        CS_Warning_Total_Finish=CS_Data[CS_Data['状态']=='已完结']
-        CS_Warning_Total_Finish=CS_Warning_Total_Finish[CS_Warning_Total_Finish['业务分类A']=='安全平台报警']
+        CS_Warning_Total_Finish=df_fltinfo[df_fltinfo['batpos']==1]
         CS_Warning_Total_Finish_Count=len(CS_Warning_Total_Finish) #平台报警总运维数
-        SftyPlt_Data_day=len(df_fltinfo[df_fltinfo['start_time']>=start_time])#周总报警数
-        CS_Warning_day_Finish=CS_Warning_Total_Finish[CS_Warning_Total_Finish['发生时间']>=start_time]#周运维数
+        SftyPlt_Data_day=len(df_fltinfo[df_fltinfo['start_time']>=start_time])#日、周总报警数
+        CS_Warning_day_Finish=CS_Warning_Total_Finish[CS_Warning_Total_Finish['start_time']>=start_time]#日/周运维数
         CS_Warning_day_Finish_Count=len(CS_Warning_day_Finish)
-        SftyPlt_EmgcyData_day=df_fltinfo[df_fltinfo['start_time']>=start_time] #周紧急报警数
-        SftyPlt_EmgcyData_day=len(SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['level']>3])
-        SftyPlt_EmgcyData_day_Finish=CS_Warning_day_Finish[CS_Warning_day_Finish['运维紧急程度']=='紧急']
+        SftyPlt_EmgcyData_day=df_fltinfo[df_fltinfo['start_time']>=start_time] #紧急报警数
+        SftyPlt_EmgcyData_day=SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['level']>3]
+        SftyPlt_EmgcyData_day_Count=len(SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['level']>3])
+        SftyPlt_EmgcyData_day_Finish=SftyPlt_EmgcyData_day[SftyPlt_EmgcyData_day['batpos']==1]
         SftyPlt_EmgcyData_day_Finish_Count=len(SftyPlt_EmgcyData_day_Finish)
-        if SftyPlt_Data_Total>0:
+        if int(SftyPlt_Data_Total)>0:
             OprationManageRate=round(float(CS_Warning_day_Finish_Count/SftyPlt_Data_day)*100,2)
         else:
             OprationManageRate=100
-        if SftyPlt_EmgcyData_day>0:
-            OprationManageEmgcyRate=round(float(SftyPlt_EmgcyData_day_Finish_Count/SftyPlt_EmgcyData_day)*100,2)
+        if int(SftyPlt_EmgcyData_day_Count)>0:
+            OprationManageEmgcyRate=round(float(SftyPlt_EmgcyData_day_Finish_Count/SftyPlt_EmgcyData_day_Count)*100,2)
         else:
             OprationManageEmgcyRate=100
         PK504FltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('PK504')])
@@ -35,6 +38,7 @@ class DataSta():
         PK500FltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('PK500')])
         MGMCLFltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('MGMCL')])
         MGMLXFltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('MGMLX')])
+        TJMCLFltData_Count=len(df_fltinfo[df_fltinfo['product_id'].str.contains('TJMCL')])
         # print('总报警数=',SftyPlt_Data_Total)
         # print('总完成运维数=',CS_Warning_Total_Finish_Count)
         # print('周报警数=',SftyPlt_Data_day)
@@ -49,15 +53,16 @@ class DataSta():
         # print('格林美总报警=',MGMCLFltData_Count)
         # print('自研总报警=',MGMLXFltData_Count)
         FltAlarmInfo=DataFrame(columns=['SftyPlt_Data_Total','CS_Warning_Total_Finish_Count','SftyPlt_Data_day','CS_Warning_day_Finish_Count','SftyPlt_EmgcyData_day','SftyPlt_EmgcyData_day_Finish_Count','OprationManageRate','OprationManageEmgcyRate'])
-        Celltype=DataFrame(columns=['PK504','PK502','PK500','MGMCL','MGMLX'])
-        FltAlarmInfo.loc[0]=[SftyPlt_Data_Total,CS_Warning_Total_Finish_Count,SftyPlt_Data_day,CS_Warning_day_Finish_Count,SftyPlt_EmgcyData_day,SftyPlt_EmgcyData_day_Finish_Count,OprationManageRate,OprationManageEmgcyRate]
-        Celltype.loc[0]=[PK504FltData_Count,PK502FltData_Count,PK500FltData_Count,MGMCLFltData_Count,MGMLXFltData_Count]
+        Celltype=DataFrame(columns=['PK504','PK502','PK500','MGMCL','MGMLX','TJMCL'])
+        FltAlarmInfo.loc[0]=[SftyPlt_Data_Total,CS_Warning_Total_Finish_Count,SftyPlt_Data_day,CS_Warning_day_Finish_Count,SftyPlt_EmgcyData_day_Count,SftyPlt_EmgcyData_day_Finish_Count,OprationManageRate,OprationManageEmgcyRate]
+        Celltype.loc[0]=[PK504FltData_Count,PK502FltData_Count,PK500FltData_Count,MGMCLFltData_Count,MGMLXFltData_Count,TJMCLFltData_Count]
         return FltAlarmInfo,Celltype
     def WeekInfoSta(df_fltinfo,start_time,end_time):
         df_fltinfo=df_fltinfo[df_fltinfo['start_time']>=start_time]
         FaultLvlCount=DataFrame(columns=['level','count'])
         FaultLvlCount=df_fltinfo.groupby('level').count().T.head(1).T
         FaultLvlCount=FaultLvlCount.reset_index(drop=False)
+        
         return FaultLvlCount
     def SftyWrngClsfy(df_fltinfo):
         DsnSaftyCode=[]
@@ -66,7 +71,7 @@ class DataSta():
         HvSaftyCode=[]
         SysSaftyCode=[]
         CellSaftyCode=[3,5,6,7,8,9,10,11,13,14,15,16,17,19,20,21,15,16,17,19,23,24,25,26,29,30,31,51,119]
-        CtrlSatyCode=[4,12,18,20,21,22]
+        CtrlSatyCode=[4,12,18,20,21,22,57]
         StateSaftyCode=[27,28,52]
         
         DsnSaftyCodeCount=len(df_fltinfo[df_fltinfo['code'].isin(DsnSaftyCode)])
@@ -118,3 +123,20 @@ class DataSta():
         TotalRunHour=int(deltatime['runningdate'].sum())
         return MaxAccumAh,TotalAccumAh,MaxCycle,MaxRunningHour,TotalRunHour
 
+    def FltBatPosition(df_last_pos,df_fltinfo):
+        df_Diag_Ram=df_fltinfo[df_fltinfo['batpos']==0].drop_duplicates(subset=['product_id'],keep=False)
+        all_location_info=DataFrame(columns=['factory','product_id','lat','lon'])
+        df_last_pos.rename(columns={'devcode':'product_id'},inplace=True)
+        df_Diag_Ram_Pos_a=pd.concat([df_Diag_Ram,df_last_pos]).drop_duplicates(subset=['product_id'],keep='first')
+        df_Diag_Ram_Pos_b=pd.concat([df_Diag_Ram,df_last_pos]).drop_duplicates(subset=['product_id'],keep=False)
+        df_Diag_Ram_Pos=df_Diag_Ram_Pos_a.append(df_Diag_Ram_Pos_b).drop_duplicates(subset=['product_id'],keep=False)
+        df_Diag_Ram_Pos=df_Diag_Ram_Pos.reset_index(drop=True)
+        for i in range(0,len(df_Diag_Ram_Pos)):
+            df_last_pos_list=df_last_pos['product_id'].values.tolist()
+            if  str(df_Diag_Ram_Pos.loc[i,'product_id']) in df_last_pos_list:
+                pos_la_temp=df_last_pos[df_last_pos['product_id']==(df_Diag_Ram_Pos.loc[i,'product_id'])].reset_index(drop=True)
+                all_location_info.loc[i,'lat']=pos_la_temp.loc[0,'latitude']
+                all_location_info.loc[i,'lon']=pos_la_temp.loc[0,'longitude']
+                all_location_info.loc[i,'factory']='骑享'
+                all_location_info.loc[i,'product_id']=df_Diag_Ram_Pos.loc[i,'product_id']
+        return all_location_info

+ 36 - 0
LIB/MIDDLE/SaftyCenter/DataDiag_Static/DiagDataMerge.py

@@ -0,0 +1,36 @@
+import pandas as pd
+import datacompy
+
+
+class DiagDataMerge():
+    def DetaMerge(df_Diag_Ram_sn,df_Diag_Batdiag_update,df_OprtnSta,df_Diag_Ram_sn_else):
+        df_Diag_Ram_add = pd.DataFrame()
+        df_Diag_Ram_Update_change = pd.DataFrame()
+        
+        df_Diag_Cal_finish = pd.DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice','Batpos'])
+        df_Diag_Cal_unfinish = pd.DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice','Batpos'])
+        print('处理前',df_Diag_Cal_unfinish)
+        if not df_Diag_Batdiag_update.empty:
+            #------------------------------合并两者故障,并将同一sn号下的车辆故障放一起----------------------------------------------
+            df_Diag_Cal_finish = df_Diag_Batdiag_update[df_Diag_Batdiag_update['end_time'] != '0000-00-00 00:00:00']
+            df_Diag_Cal_unfinish = df_Diag_Batdiag_update[df_Diag_Batdiag_update['end_time'] == '0000-00-00 00:00:00']
+            df_Diag_Cal_finish['Batpos'] = [1]*len(df_Diag_Cal_finish)
+            if len(df_OprtnSta):
+                if df_OprtnSta.loc[0,'status'] !=1:#0禁用 1正常 2故障 3返修 4 损毁 5丢失已赔偿,6丢失未赔偿
+                    if df_Diag_Cal_unfinish['level'].max()>3:
+                        if df_OprtnSta.loc[0,'status'] ==3:
+                            df_Diag_Cal_unfinish['Batpos'] = [1]*len(df_Diag_Cal_unfinish)
+                        else:
+                            df_Diag_Cal_unfinish['Batpos'] = [0]*len(df_Diag_Cal_unfinish)
+                    else:
+                        df_Diag_Cal_unfinish['Batpos'] = [1]*len(df_Diag_Cal_unfinish)
+                else:
+                    df_Diag_Cal_unfinish['Batpos'] = [0]*len(df_Diag_Cal_unfinish)
+                    
+        print('处理后',df_Diag_Cal_unfinish)
+        df_Diag_Cal_Update=pd.concat([df_Diag_Cal_finish,df_Diag_Cal_unfinish])    
+        df_Diag_Ram_add = pd.concat([df_Diag_Cal_Update,df_Diag_Ram_sn,df_Diag_Ram_sn]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
+        df_Diag_Ram_Update_old = pd.concat([df_Diag_Cal_Update,df_Diag_Ram_add,df_Diag_Ram_add]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
+        df_Diag_Ram_Update_change = pd.concat([df_Diag_Ram_Update_old,df_Diag_Ram_sn,df_Diag_Ram_sn]).drop_duplicates(subset=['start_time','code','Batpos'],keep=False)#此次判断中新增故障
+        # df_Diag_Ram = pd.concat([df_Diag_Ram_sn_else,df_Diag_Cal_unfinish])    
+        return df_Diag_Ram_add,df_Diag_Ram_Update_change

+ 73 - 0
LIB/MIDDLE/SaftyCenter/DataDiag_Static/SC_CtrlSafty.py

@@ -0,0 +1,73 @@
+import sys
+import numpy as np
+import pandas as pd
+import string
+import os
+from pandas import Series
+from matplotlib import pyplot as plt
+from pandas.core.frame import DataFrame
+from pandas.core.indexes.base import Index
+from LIB.BACKEND import DBManager
+import datetime
+import time
+import string
+import re
+
+
+
+class CtrlSafty:
+    def __init__(self):
+        pass
+    def main(sn,param,bms_info,df_Diag_Ram_in):
+        df_Diag_Ram_Update_inside=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
+        df_Diag_Ram_Update_inside=df_Diag_Ram_Update_inside.append(df_Diag_Ram_in)
+        global QuitErrCount 
+        VolStarkCount=[0 for i in range(param.CellVoltNums)]
+        VolCount=0
+        QuitErrCount=[0 for i in range(param.FaultCount)]
+
+        #--------------该电池的所有当前故障-------------
+
+
+
+
+        df_Diag_Ram_Update_inside=CtrlSafty.TempCtrlDiag(sn,bms_info,param,df_Diag_Ram_Update_inside) 
+        return df_Diag_Ram_Update_inside
+
+
+
+    def TempCtrlDiag(sn,bms_info,param,df_Diag_Ram):
+        ErrorFlg=0
+        CellTempMax=0
+        OtherTempMax=0
+
+        CellTempNum=['单体温度'+str(i) for i in range(1,param.CellTempNums+1)]
+        if 'MXMLX' in sn:
+            OtherTempNum=['其他温度1','其他温度3','其他温度4','其他温度5']
+        else:
+            OtherTempNum=['其他温度'+str(i) for i in range(1,param.OtherTempNums+1)]
+        
+        CellTempMax=bms_info[bms_info[CellTempNum]>(param.CellMaxUSBTemp-5)]
+        CellTempMax=CellTempMax[CellTempMax<(param.CellMaxUSBTemp+5)].dropna(axis=0,how='all')
+        OtherTempMax=bms_info[bms_info[OtherTempNum]>(param.OtherOTlmt-10)]
+        OtherTempMax=OtherTempMax[OtherTempMax[OtherTempNum]<(param.OtherOTlmt+5)].dropna(axis=0,how='all')
+        if len(CellTempMax) and len(OtherTempMax):
+            QuitErrCount[57]=0
+            if not 57 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_info.loc[len(bms_info)-1,'时间戳'],'0000-00-00 00:00:00',sn,57,4,'电芯温度高','立即联系用户确认电池状态']
+                ErrorFlg=1            
+            else:#如果故障发生当前故障中有该故障,则不进行操作
+                pass
+        else:
+            if 57 in df_Diag_Ram['code'].values.tolist():
+                QuitErrCount[57]=QuitErrCount[57]+1
+                if QuitErrCount[57]>3:
+                    QuitErrCount[57]=4
+                    end_time=datetime.datetime.now()
+                    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                    df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==57].index,['end_time']]=end_time
+                else:
+                    pass
+            else:
+                pass
+        return df_Diag_Ram

+ 356 - 0
LIB/MIDDLE/SaftyCenter/DataDiag_Static/SC_SamplingSafty.py

@@ -0,0 +1,356 @@
+import sys
+import numpy as np
+import pandas as pd
+import string
+import os
+from pandas import Series
+from matplotlib import pyplot as plt
+from pandas.core.frame import DataFrame
+from pandas.core.indexes.base import Index
+from LIB.BACKEND import DBManager
+import datetime
+import time
+import string
+import re
+
+
+
+class SamplingSafty:
+    def __init__(self):
+        pass
+    def main(sn,param,bms_info,df_Diag_Ram_in):
+        df_Diag_Ram_Update_inside=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
+        df_Diag_Ram_Update_inside=df_Diag_Ram_Update_inside.append(df_Diag_Ram_in)
+        global QuitErrCount 
+        VolStarkCount=[0 for i in range(param.CellVoltNums)]
+        VolCount=0
+        QuitErrCount=[0 for i in range(param.FaultCount)]
+
+        #--------------该电池的所有当前故障-------------
+
+
+
+        for i in range(0,len(bms_info)):
+            if i==0:
+                bms_infoP=bms_info.loc[i]
+            elif len(bms_info)>=1:
+                    bms_infoP=bms_info.loc[i-1]
+            df_Diag_Ram_Update_inside,VolStarkCount,VolCount=SamplingSafty.VoltSamplingDiag(sn,bms_info.loc[i],bms_infoP,param,VolStarkCount,VolCount,df_Diag_Ram_Update_inside)   
+            df_Diag_Ram_Update_inside=SamplingSafty.TempSamplingDiag(sn,bms_info.loc[i],bms_infoP,param,df_Diag_Ram_Update_inside)
+                # FltInfo=SamplingSafty.CrntSamplingDiag(sn,bms_info.loc[i],FltInfo,param)
+        return df_Diag_Ram_Update_inside
+
+
+
+    def VoltSamplingDiag(sn,bms_infoN,bms_infoP,param,VolStarkCount,VolCount,df_Diag_Ram):
+        InVMaxBatNo=[]
+        InVMinBatNo=[]
+        StackVolNo=[]
+        OutlierVolNo=[]
+        ErrorFlg=0
+        #——————————————————————取最高最低电压————————————————————————————————
+
+        VoltageNum=['单体电压'+str(i) for i in range(1,param.CellVoltNums+1)]
+        CellVoltage=bms_infoN[VoltageNum]/1000
+        CellVoltageP=bms_infoP[VoltageNum]/1000
+        MaxVolt=CellVoltage.max()
+        MinVolt=CellVoltage.min()
+        MaxVoltNum=CellVoltage[MaxVolt==CellVoltage].index
+        MinVoltNum=CellVoltage[MinVolt==CellVoltage].index
+        InVMaxBatNo=CellVoltage[CellVoltage>=param.CellOVlmt].index
+        InVMinBatNo=CellVoltage[CellVoltage<=param.CellUVlmt].index
+        if param.CellVoltNums>2:
+            AvgVol=(CellVoltage.sum()-MaxVolt-MinVolt)/(param.CellVoltNums-2)
+        else:
+            AvgVol=CellVoltage.mean()
+        #—————————————————————————————电压无效和断线判断———————————————————————
+        if len(InVMaxBatNo):
+            if len(InVMinBatNo):
+                QuitErrCount[10]=0
+                if not 10 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                    df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,10,2,'电池电压采样断线,最高电压为{:.2f}V,电池编号为{},最低电压为{:.2f}V,电池编号为{}'.format(MaxVolt,InVMaxBatNo.values,MinVolt,InVMinBatNo.values),'返厂维修']
+                    ErrorFlg=1  
+                else:#如果故障发生当前故障中有该故障,则不进行操作
+                    pass                 
+            else:#如果没有故障,并且当前故障表中有该故障,则判断故障是否结束
+                QuitErrCount[50]=0
+                if 10 in df_Diag_Ram['code'].values.tolist():
+                    QuitErrCount[10]=QuitErrCount[10]+1
+                    if QuitErrCount[10]>3:
+                        QuitErrCount[10]=4
+                        end_time=datetime.datetime.now()
+                        end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                        df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==10].index,['end_time']]=end_time
+                    else:
+                        pass
+                else:
+                    pass
+                if not 50 in df_Diag_Ram['code'].values.tolist():
+                    df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,50,2,str(InVMaxBatNo.values)+'号电压大于{:.2f}V,采样无效'.format(param.CellOVlmt),'返厂维修']
+                    ErrorFlg=1
+                else:
+                    pass
+        elif len(InVMinBatNo):
+            QuitErrCount[50]=0
+            if not 50 in df_Diag_Ram['code'].values.tolist():
+                df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,50,2,str(InVMinBatNo.values)+'号电压小于{:.2f}V,采样无效'.format(param.CellUVlmt),'返厂维修']
+                ErrorFlg=1
+            else:
+                pass
+        else:
+            if 50 in df_Diag_Ram['code'].values.tolist():
+                QuitErrCount[50]=QuitErrCount[50]+1
+                if QuitErrCount[50]>3:
+                    QuitErrCount[50]=4
+                    end_time=datetime.datetime.now()
+                    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                    df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==50].index,['end_time']]=end_time                   
+                else:
+                    pass
+            else:
+                pass                                      
+       #——————————————————————————————————电压卡滞和离群判断—————————————————————————
+        if ErrorFlg==0:
+            AvgVolGap=CellVoltage-AvgVol
+            OutlierVolNo=AvgVolGap[AvgVolGap>=param.AvgVolGap].index
+            if len(OutlierVolNo) and abs(bms_infoN['总电流[A]'])<2 and not 51 in df_Diag_Ram['code']:
+                VolCount=VolCount+1
+                QuitErrCount[51]=0
+                if VolCount>10:
+                    VolCount=11
+                    if not 51 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                        df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,51,2,str(OutlierVolNo.values)+'号电池电压离群','技术介入诊断']
+                        ErrorFlg=1            
+                    else:#如果故障发生当前故障中有该故障,则不进行操作
+                        pass                
+            else:
+                VolCount=0
+                if 51 in df_Diag_Ram['code'].values.tolist():
+                    QuitErrCount[51]=QuitErrCount[51]+1
+                    if QuitErrCount[51]>3:
+                        QuitErrCount[51]=4
+                        end_time=datetime.datetime.now()
+                        end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                        df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==51].index,['end_time']]=end_time                
+                    else:
+                        pass
+                else:
+                    pass
+            # -------------------卡滞逻辑未加-------------------------------------
+            # if (abs(float(bms_infoN['总电流[A]']))>=10 and not 'PK504' in sn) or (abs(float(bms_infoN['总电流[A]']))>=15 and 'PK504' in sn):
+            #     StackVolNo=CellVoltage[abs(CellVoltage-CellVoltageP)<=0.0001].index
+            #     NotStackVolNo=CellVoltage[abs(CellVoltage-CellVoltageP)>0.0001].index
+            #     if len(StackVolNo) and not 52 in df_Diag_Ram['code']:
+            #         StackVolNo=[int(s) for s in StackVolNo.str.replace(r'[^0-9]','').tolist()]
+            #         NotStackVolNo=[int(s) for s in NotStackVolNo.str.replace(r'[^0-9]','').tolist()]
+            #         for i in StackVolNo:
+            #             VolStarkCount[i-1]=VolStarkCount[i-1]+1
+            #         for i in NotStackVolNo:
+            #             VolStarkCount[i-1]=0
+            #     if [s for s in VolStarkCount]>10:
+            #         StacVolNo=
+
+        return df_Diag_Ram,VolStarkCount,VolCount
+
+    def TempSamplingDiag(sn,bms_infoN,bms_infoP,param,df_Diag_Ram):
+        InVMaxBatNo=[]
+        InVMinBatNo=[]
+        StackVolNo=[]
+        OutlierVolNo=[]
+        ErrorFlg=0
+        #——————————————————————Cell取最高最低温度————————————————————————————————
+        TempNum=['单体温度'+str(i) for i in range(1,param.CellTempNums+1)]
+        CellTemp=bms_infoN[TempNum]
+        CellTempP=bms_infoP[TempNum]
+        maxCellTemp=CellTemp.max()
+        minCellTemp=CellTemp.min()
+        MaxVoltNum=CellTemp[maxCellTemp==CellTemp].index
+        MinVoltNum=CellTemp[minCellTemp==CellTemp].index
+        InVMaxTempBatNo=CellTemp[CellTemp>=param.PackOTlmt].index
+        InVMinTempBatNo=CellTemp[CellTemp<=param.PackUTlmt].index
+        if param.CellTempNums>2:
+            AvgCellTemp=(CellTemp.sum()-maxCellTemp-minCellTemp)/(param.CellTempNums-2)
+        else:
+            AvgCellTemp=CellTemp.mean()        
+        #——————————————————————温度无效,离群和断线判断———————————————————————
+        if len(InVMaxTempBatNo):
+            if len(InVMinTempBatNo):
+                QuitErrCount[53]=0
+                if not 53 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                    df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,53,2,'电池温度采样断线,最高温度为{}℃,电池编号为{},最低温度为{}℃,电池编号为{}'.format(maxCellTemp,InVMaxTempBatNo.values,minCellTemp,InVMinTempBatNo.values),'返厂维修']
+                    ErrorFlg=1 
+                else:#如果故障发生当前故障中有该故障,则不进行操作
+                    pass                 
+            else:#如果没有故障,并且当前故障表中有该故障,则判断故障是否结束
+                QuitErrCount[2]=0
+                if 53 in df_Diag_Ram['code'].values.tolist():
+                    QuitErrCount[53]=QuitErrCount[53]+1
+                    if QuitErrCount[53]>3:
+                        QuitErrCount[53]=4
+                        end_time=datetime.datetime.now()
+                        end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                        df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==53].index,['end_time']]=end_time
+                    else:
+                        pass
+                else:
+                    pass
+                if not 2 in df_Diag_Ram['code'].values.tolist():
+                    df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,2,2,str(InVMaxTempBatNo.values)+'号温度大于{}℃,采样无效'.format(param.PackOTlmt),'联系用户核实电池温度情况,并返厂维修']
+                    ErrorFlg=1
+                else:
+                    pass
+        elif len(InVMinTempBatNo):
+            QuitErrCount[2]=0
+            if not 2 in df_Diag_Ram['code'].values.tolist():
+                df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,2,2,str(InVMinTempBatNo.values)+'号温度小于{}℃,采样无效'.format(param.PackUTlmt),'返厂维修']
+                ErrorFlg=1
+            else:
+                pass
+        else:
+            if 2 in df_Diag_Ram['code'].values.tolist():
+                QuitErrCount[2]=QuitErrCount[2]+1
+                if QuitErrCount[2]>3:
+                    QuitErrCount[2]=4
+                    end_time=datetime.datetime.now()
+                    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                    df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==2].index,['end_time']]=end_time                   
+                else:
+                    pass
+            else:
+                pass             
+        if ErrorFlg==0:
+            AvgCellTempGap=abs(CellTemp-AvgCellTemp)
+            OutlierTempNo=AvgCellTempGap[AvgCellTempGap>=param.AvgCellTempGap].index
+            if len(OutlierTempNo):
+                QuitErrCount[8]=0
+                if not 8 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                    df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,8,2,str(OutlierTempNo.values)+'号电池异常温度离群','技术介入诊断']
+                    ErrorFlg=1            
+                else:#如果故障发生当前故障中有该故障,则不进行操作
+                    pass
+            else:
+                if 8 in df_Diag_Ram['code'].values.tolist():
+                    QuitErrCount[8]=QuitErrCount[8]+1
+                    if QuitErrCount[8]>3:
+                        QuitErrCount[8]=4
+                        end_time=datetime.datetime.now()
+                        end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                        df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==8].index,['end_time']]=end_time
+                    else:
+                        pass
+                else:
+                    pass
+        #——————————————————————————————————OtherTemp————————————————————————————————————
+        if param.OtherTempNums>0:
+            OtherTempNum=['其他温度'+str(i) for i in range(1,param.OtherTempNums+1)]
+            OtherTemp=bms_infoN[OtherTempNum]
+            OtherTemppP=bms_infoP[OtherTempNum]
+            maxOtherTemp=OtherTemp.max()
+            minOtherTemp=OtherTemp.min()
+            MaxVoltNum=OtherTemp[maxOtherTemp==OtherTemp].index
+            MinVoltNum=OtherTemp[minOtherTemp==OtherTemp].index
+            InVMaxOtherTempBatNo=OtherTemp[OtherTemp>=param.OtherOTlmt].index
+            InVMinOtherTempBatNo=OtherTemp[OtherTemp<=param.OtherUTlmt].index
+            if param.OtherTempNums>2:
+                AvgOtherTemp=(OtherTemp.sum()-maxOtherTemp-minOtherTemp)/(param.OtherTempNums-2)
+            else:
+                AvgOtherTemp=OtherTemp.mean()        
+            #——————————————————————温度无效,离群和断线判断———————————————————————
+            if len(InVMaxOtherTempBatNo):
+                if len(InVMinOtherTempBatNo):
+                    QuitErrCount[54]=0
+                    if not 54 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                        df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,54,2,'其他温度采样断线,最高温度为{}℃,传感器编号为{},最低温度为{}℃,传感器编号为{}'.format(maxOtherTemp,InVMaxOtherTempBatNo.values,minOtherTemp,InVMinOtherTempBatNo.values),'返厂维修']
+                        ErrorFlg=1 
+                    else:#如果故障发生当前故障中有该故障,则不进行操作
+                        pass                 
+                else:#如果没有故障,并且当前故障表中有该故障,则判断故障是否结束
+                    QuitErrCount[55]=0
+                    if 54 in df_Diag_Ram['code'].values.tolist():
+                        QuitErrCount[54]=QuitErrCount[54]+1
+                        if QuitErrCount[54]>3:
+                            QuitErrCount[54]=4
+                            end_time=datetime.datetime.now()
+                            end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                            df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==54].index,['end_time']]=end_time
+                        else:
+                            pass
+                    else:
+                        pass
+                    if not 55 in df_Diag_Ram['code'].values.tolist():
+                        df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,55,2,'传感器温度大于{}℃,采样无效'.format(param.OtherOTlmt),'联系用户核实电池温度情况,并返厂维修']
+                        ErrorFlg=1
+                    else:
+                        pass
+            elif len(InVMinTempBatNo):
+                QuitErrCount[55]=0
+                if not 55 in df_Diag_Ram['code'].values.tolist():
+                    df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,55,2,'传感器温度小于{}℃,采样无效'.format(param.OtherUTlmt),'返厂维修']
+                    ErrorFlg=1
+                else:
+                    pass
+            else:
+                if 55 in df_Diag_Ram['code'].values.tolist():
+                    QuitErrCount[55]=QuitErrCount[55]+1
+                    if QuitErrCount[55]>3:
+                        QuitErrCount[55]=4
+                        end_time=datetime.datetime.now()
+                        end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                        df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==55].index,['end_time']]=end_time                   
+                    else:
+                        pass
+                else:
+                    pass             
+            if ErrorFlg==0:
+                AvgOtherTempGap=abs(OtherTemp-AvgOtherTemp)
+                OutlierOtherTempNo=AvgOtherTempGap[AvgOtherTempGap>=param.AvgOtherTempGap].index
+                if len(OutlierOtherTempNo):
+                    QuitErrCount[56]=0
+                    if not 56 in df_Diag_Ram['code'].values.tolist():#如果故障发生当前故障中没有该故障,则压入该故障
+                        df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,56,2,'传感器温度异常离群','技术介入诊断']
+                        ErrorFlg=1            
+                    else:#如果故障发生当前故障中有该故障,则不进行操作
+                        pass
+                else:
+                    if 56 in df_Diag_Ram['code'].values.tolist():
+                        QuitErrCount[56]=QuitErrCount[56]+1
+                        if QuitErrCount[56]>3:
+                            QuitErrCount[56]=4
+                            end_time=datetime.datetime.now()
+                            end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                            df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==56].index,['end_time']]=end_time
+                        else:
+                            pass
+                    else:
+                        pass
+
+                if (maxOtherTemp-maxCellTemp)>param.AvgOtherTempGap and  maxOtherTemp<param.OtherOTlmt and maxCellTemp<param.PackOTlmt:
+                    QuitErrCount[56]=0
+                    if not 56 in df_Diag_Ram['code'].values.tolist():
+                        df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,56,2,'传感器温度异常离群','技术立即介入诊断']
+                        ErrorFlg=1
+                else:
+                    if 56 in df_Diag_Ram['code'].values.tolist():
+                            QuitErrCount[56]=QuitErrCount[56]+1
+                            if QuitErrCount[56]>3:
+                                QuitErrCount[56]=4
+                                end_time=datetime.datetime.now()
+                                end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                                df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==56].index,['end_time']]=end_time
+                                
+                if (maxCellTemp-maxOtherTemp)>param.AvgOtherTempGap and  maxOtherTemp<param.OtherOTlmt and maxCellTemp<param.PackOTlmt and not 8 in df_Diag_Ram['code']:
+                    QuitErrCount[8]=0
+                    if not 8 in df_Diag_Ram['code'].values.tolist():
+                        df_Diag_Ram.loc[len(df_Diag_Ram)]=[bms_infoN['时间戳'],'0000-00-00 00:00:00',sn,8,2,str(OutlierTempNo.values)+'号电芯温度异常离群','技术立即介入诊断']
+                        
+                        ErrorFlg=1
+                else:
+                    if 8 in df_Diag_Ram['code'].values.tolist():
+                            QuitErrCount[8]=QuitErrCount[8]+1
+                            if QuitErrCount[8]>3:
+                                QuitErrCount[8]=4
+                                end_time=datetime.datetime.now()
+                                end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+                                df_Diag_Ram.loc[df_Diag_Ram[df_Diag_Ram['code']==8].index,['end_time']]=end_time              
+
+        return df_Diag_Ram

+ 308 - 0
LIB/MIDDLE/SaftyCenter/DataDiag_Static/main.py

@@ -0,0 +1,308 @@
+import CBMSBatDiag
+from SC_SamplingSafty import SamplingSafty
+from DataStatistics import DataSta
+from DiagDataMerge import DiagDataMerge
+from SC_CtrlSafty import CtrlSafty
+import datetime
+import pandas as pd
+from LIB.BACKEND import DBManager, Log
+from sqlalchemy import create_engine
+import time, datetime
+from apscheduler.schedulers.blocking import BlockingScheduler
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload as DBDownload
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
+from pandas.core.frame import DataFrame
+import datacompy
+from LIB.MIDDLE.SaftyCenter.Common import QX_BatteryParam
+from LIB.MIDDLE.SaftyCenter.Common import DBDownload as DBDw
+
+#...................................电池包电芯安全诊断函数......................................................................................................................
+def diag_cal():
+    task_on=1
+    global SNnums
+    global start
+    #..................................设置时间..........................................................  
+    start=time.time()
+    end_time=datetime.datetime.now()
+    start_time=end_time-datetime.timedelta(seconds=900)#10分钟跑一次,一次取10分钟数据
+    start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
+    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+
+
+    
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    db='safety_platform'
+    user='qx_algo_readonly'
+    password='qx@123456'
+    mode=2
+    tablename2='all_fault_info'
+    DBRead = DBDw.DBDownload(host, port, db, user, password,mode)
+    with DBRead as DBRead:
+        df_Diag_Ram = DBRead.getdata('start_time','end_time','product_id','code','level','info','advice','Batpos',tablename=tablename2,factory='',sn='',timename='',st='',sp='')
+    df_Diag_Ram=df_Diag_Ram.dropna(how='any')
+    df_Diag_Ram=df_Diag_Ram.reset_index(drop=True)
+    
+    for sn in SNnums:#SN遍历
+        print(sn)
+        if 'PK500' in sn:
+            celltype=1 #6040三元电芯
+        elif 'PK502' in sn:
+            celltype=2 #4840三元电芯
+        elif 'K504B' in sn:
+            celltype=99    #60ah林磷酸铁锂电芯
+        elif 'MGMLXN750' in sn:
+            celltype=3 #力信50ah三元电芯
+        elif 'MGMCLN750' or 'UD' in sn: 
+            celltype=4 #CATL 50ah三元电芯
+        elif 'TJMCL'in sn:
+            celltype=100 #CATL 50ah三元电芯
+        else:
+            print('SN:{},未找到对应电池类型!!!'.format(sn))
+            continue
+            # sys.exit()
+        param=QX_BatteryParam.BatteryInfo(celltype)   
+        #读取原始数据库数据........................................................................................................................................................
+        dbManager = DBManager.DBManager()
+        df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
+        df_bms = df_data['bms']
+        df_bms=df_bms.dropna(how='any')
+        #读取结果数据库数据........................................................................................................................................................
+        host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+        port=3306
+        db='qx_cas'
+        user='qx_algo_readonly'
+        password='qx@123456'
+        mode=1
+        tablename1='cellstateestimation_soh'
+        tablename2='cellstateestimation_uniform_socvoltdiff'       
+        DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
+        with DBRead as DBRead:
+            df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename=tablename1, sn=sn, timename='time_sp', st=start_time, sp=end_time)
+            df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellmin_num,cellmax_num', tablename=tablename2, sn=sn, timename='time', st=start_time, sp=end_time)
+
+        #读取电池当前运营状态.....................................................................................................................................................
+        host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
+        port=3306
+        db='qixiang_manage'
+        user='qx_query'
+        password='@Qx_query'
+        mode=4
+        tablename1='py_battery'     
+        DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
+        with DBRead as DBRead:
+            df_OprtnSta=DBRead.getdata('qrcode','status', tablename=tablename1, sn=sn, timename='', st='', sp='',factory='')#取最后一条运营状态
+
+
+
+
+
+
+        #电池诊断.....................................................................................................................................................................
+        CellFltInfo=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
+        df_Diag_Ram_sn = df_Diag_Ram.loc[df_Diag_Ram['product_id']==sn]#历史故障
+        df_Diag_Ram_sn_else = df_Diag_Ram.loc[df_Diag_Ram['product_id']!=sn]#sn之外的故障
+        CellFltInfo = df_Diag_Ram_sn.drop('Batpos',axis=1)
+        #获取当前故障电池的历史故障信息↑↑↑↑↑↑↑↑↑↑↑.......................................................................................................................................
+        if not df_bms.empty:
+            df_Diag_Batdiag_update_xq=SamplingSafty.main(sn,param,df_bms,CellFltInfo)#采样安全   
+            df_Diag_Batdiag_update_xq2=CtrlSafty.main(sn,param,df_bms,df_Diag_Batdiag_update_xq)#控制安全
+            batDiag=CBMSBatDiag.BatDiag(sn,celltype,df_bms, df_soh, df_uniform, df_Diag_Batdiag_update_xq2)#鹏飞计算
+            df_Diag_Batdiag_update=batDiag.diag()
+            # df_Diag_Batdiag_update=BatDiag.diag() 
+        else:
+            df_Diag_Batdiag_update_xq=DataFrame(columns=['start_time','end_time','product_id','code','level','info','advice','Batpos'])
+            df_Diag_Batdiag_update_xq2=DataFrame(columns=['start_time','end_time','product_id','code','level','info','advice','Batpos'])
+            df_Diag_Batdiag_update=DataFrame(columns=['start_time','end_time','product_id','code','level','info','advice','Batpos'])
+        df_Diag_Ram_add,df_Diag_Ram_Update=DiagDataMerge.DetaMerge(df_Diag_Ram_sn,df_Diag_Batdiag_update,df_OprtnSta,df_Diag_Ram_sn_else)
+    task_on=0
+#.................................统计程序...............................
+def DaTa_Sta_Week_Task():
+    task_on=1
+    factory_info=['骑享','金茂换电']
+    all_period_fault_info=DataFrame(columns=['factory','week','level1_count','level2_count','level3_count','level4_count','level5_count','solve_rate'])
+    toweek='Week'+time.strftime('%W')
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    db='safety_platform'
+    user='qx_algo_readonly'
+    password='qx@123456'
+    mode=2
+    tablename1='all_fault_info'
+    DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
+    with DBRead as DBRead:
+        df_fltinfo=DBRead.getdata('product_id','level','code','start_time','end_time','batpos','factory',tablename=tablename1,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
+#............................获取数据................................
+    for j in range(0,len(factory_info)):
+        df_fltinfo=df_fltinfo[df_fltinfo['factory']==factory_info[j]]
+        #............................获取时间................................      
+        end_time=datetime.datetime.now()
+        # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
+        start_time_week=end_time-datetime.timedelta(days=7)
+        start_time_week=start_time_week.strftime('%Y-%m-%d')
+        end_time=end_time.strftime('%Y-%m-%d')
+        FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(df_fltinfo,start_time_week,end_time)
+        FaultLvlCount=DataSta.WeekInfoSta(df_fltinfo,start_time_week,end_time)
+        for i in range(1,6):
+            if not FaultLvlCount[FaultLvlCount['level']==i]['product_id'].empty:
+                all_period_fault_info.loc[j,'level'+str(i)+'_count']=int(FaultLvlCount[FaultLvlCount['level']==i]['product_id'].values)
+            else:
+                all_period_fault_info.loc[j,'level'+str(i)+'_count']=int(0)
+        all_period_fault_info.loc[j,'factory']=factory_info[j]
+        all_period_fault_info.loc[j,'week']=toweek
+        all_period_fault_info.loc[j,'solve_rate']=FltAlarmInfo.loc[0,'OprationManageRate']
+        all_period_fault_info.fillna(0,inplace=False)
+
+        task_on=0
+def DaTa_Sta_Minutes_Task():
+    task_on=1
+    factory_info=['骑享','金茂换电']
+    #............................获取数据................................
+    host='172.16.121.236'
+    port=3306
+    db='fastfun'
+    user='readonly'
+    password='Fast1234'
+    mode=3
+    tablename1='ff_battery_accum'
+    tablename2='ff_location'
+    DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
+    with DBRead as DBRead:
+        df_last_accum=DBRead.getdata('devcode','dsg_phaccum','dsg_ahaccum',tablename=tablename1,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
+        df_last_pos=DBRead.getdata('devcode','latitude','longitude',tablename=tablename2,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
+        
+        
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    db='qx_cas'
+    user='qx_algo_readonly'
+    password='qx@123456'
+    mode=3
+    tablename2='bat_first_data_time'
+    DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
+    with DBRead as DBRead:
+        df_FirstDataTime=DBRead.getdata('sn','first_data_time',tablename=tablename2,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
+        
+        
+
+    #............................获取时间................................
+    end_time=datetime.datetime.now()
+    # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
+    start_time=end_time-datetime.timedelta(days=1)
+    start_time=start_time.strftime('%Y-%m-%d')
+    end_time=end_time.strftime('%Y-%m-%d')
+    #............................执行程序................................
+    all_statistic_info=DataFrame(columns=['factory','total_alarm','alarm_total_today','alarm_not_close_today','alarm_close_today','alarm_uregent_total_today','alarm_uregent_close_today','alarm_uregent_not_close_today','alarm_close_total','run_time_total','dischrg_total','odo_total','max_dischrg_one','max_runtime_one','max_cycle_one','max_odo_one','alarm_close_total','alarm_total','cell_type','cell_type_count','cell_safety_risk_count','data_safety_risk_count','status_safety_risk_count','hv_safety_risk_count','system_safety_risk_count','sample_safety_risk_count','controller_safety_risk_count','design_safety_risk_count'])
+    for j in range(0,len(factory_info)):
+        host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+        port=3306
+        db='safety_platform'
+        user='qx_algo_readonly'
+        password='qx@123456'
+        mode=2
+        tablename1='all_fault_info'
+        DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
+        with DBRead as DBRead:
+            df_fltinfo=DBRead.getdata('product_id','level','code','start_time','batpos',tablename=tablename1,factory=factory_info[j],sn='',timename='',st='',sp='')#dbdownload经过了改编
+        FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(df_fltinfo,start_time,end_time)
+        SatftyCount=DataSta.SftyWrngClsfy(df_fltinfo)
+        MaxAccumAh,TotalAccumAh,MaxCycle,MaxRunningHour,TotalRunHour=DataSta.AccumInfo(df_last_accum,df_FirstDataTime,end_time)
+        all_location_info=DataSta.FltBatPosition(df_last_pos,df_fltinfo)
+
+       
+        all_statistic_info.loc[j,'factory']=factory_info[j]
+        all_statistic_info.loc[j,'total_alarm']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
+        all_statistic_info.loc[j,'alarm_total_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']
+        all_statistic_info.loc[j,'alarm_close_today']=FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
+        all_statistic_info.loc[j,'alarm_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']-FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
+        all_statistic_info.loc[j,'alarm_uregent_total_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']
+        all_statistic_info.loc[j,'alarm_uregent_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
+        all_statistic_info.loc[j,'alarm_uregent_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']-FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
+        all_statistic_info.loc[j,'run_time_total']=TotalRunHour
+        all_statistic_info.loc[j,'dischrg_total']=TotalAccumAh
+        all_statistic_info.loc[j,'odo_total']=0
+        all_statistic_info.loc[j,'max_dischrg_one']=MaxAccumAh
+        all_statistic_info.loc[j,'max_runtime_one']=MaxRunningHour
+        all_statistic_info.loc[j,'max_cycle_one']=MaxCycle
+        all_statistic_info.loc[j,'max_odo_one']=0
+        all_statistic_info.loc[j,'alarm_close_total']=FltAlarmInfo.loc[0,'CS_Warning_Total_Finish_Count']
+        all_statistic_info.loc[j,'alarm_total']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
+        CellType=Celltype.columns.tolist()
+        CellType=','.join(CellType) 
+        all_statistic_info.loc[0,'cell_type']=str(CellType)
+        CellTypeCount=Celltype.loc[0].tolist()
+        CellTypeCount=[str(x) for x in CellTypeCount]
+        CellTypeCount=','.join(CellTypeCount) 
+        all_statistic_info.loc[j,'cell_type_count']=str(CellTypeCount)
+        all_statistic_info.loc[j,'cell_safety_risk_count']=SatftyCount.loc[0,'CellSaftyCount']
+        all_statistic_info.loc[j,'data_safety_risk_count']=SatftyCount.loc[0,'DataSaftyCodeCount']
+        all_statistic_info.loc[j,'status_safety_risk_count']=SatftyCount.loc[0,'StateSaftyCodeCount']
+        all_statistic_info.loc[j,'hv_safety_risk_count']=SatftyCount.loc[0,'HvSaftyCodeCount']
+        all_statistic_info.loc[j,'system_safety_risk_count']=SatftyCount.loc[0,'SysSaftyCodeCount']
+        all_statistic_info.loc[j,'sample_safety_risk_count']=SatftyCount.loc[0,'SamplingSatyCount']
+        all_statistic_info.loc[j,'controller_safety_risk_count']=SatftyCount.loc[0,'CtrlSaftyCodeCount']
+        all_statistic_info.loc[j,'design_safety_risk_count']=SatftyCount.loc[0,'DsnSaftyCodeCount']
+        end=time.time()
+        #print(end-start)
+        task_on=0
+    print(all_statistic_info)
+
+
+#...............................................主函数.......................................................................................................................
+if __name__ == "__main__":
+    global SNnums
+    global task_on
+    
+    task_on=0
+    excelpath=r'D:\ZLWORK\code\data_analyze_platform\USER\eric\SaftyCenter_CODE_V1\sn-20210903.xlsx'
+    SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
+    SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
+    SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
+    SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
+    SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
+    SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
+    SNnums_6060=SNdata_6060['SN号'].tolist()
+    SNnums_6040=SNdata_6040['SN号'].tolist()
+    SNnums_4840=SNdata_4840['SN号'].tolist()
+    SNnums_L7255=SNdata_L7255['SN号'].tolist()
+    SNnums_C7255=SNdata_C7255['SN号'].tolist()
+    SNnums_U7255=SNdata_U7255['SN号'].tolist()
+    SNnums=SNnums_L7255 + SNnums_C7255 + SNnums_6040 + SNnums_4840 + SNnums_U7255+ SNnums_6060
+    SNnums=['TJMCL120502305038','TJMCL120502305032','TJMCL120502305022','TJMCL120502305026','TJMCL120502305032','TJMCL120502305044','TJMCL120502305048','TJMCL120502305012','TJMCL120502305010']
+    #SNnums = ['MGMLXN750N218N004'] #SNnums_6040
+    
+    mylog=log.Mylog('log.txt','error')
+    mylog.logcfg()
+    #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    db='safety_platform'
+    user='qx_algo_readonly'
+    password='qx@123456'
+    mode=2
+    tablename2='all_fault_info'
+    DBRead = DBDw.DBDownload(host, port, db, user, password,mode)
+    with DBRead as DBRead:
+        df_Diag_Ram = DBRead.getdata('start_time','end_time','product_id','code','level','info','advice','Batpos','factory',tablename=tablename2,factory='',sn='',timename='',st='',sp='')
+    df_Diag_Ram=df_Diag_Ram.dropna(how='any')
+    df_Diag_Ram=df_Diag_Ram.reset_index(drop=True)
+    # result=pd.read_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\result.csv',encoding='gbk')
+
+    #定时任务.......................................................................................................................................................................
+    scheduler = BlockingScheduler()
+    diag_cal()
+    DaTa_Sta_Minutes_Task()
+    DaTa_Sta_Week_Task()  
+
+    if task_on==0:
+        scheduler.add_job(DaTa_Sta_Week_Task, 'interval', days=7, id='Week_Task')
+        scheduler.add_job(diag_cal, 'interval', seconds=900, id='diag_job')
+        scheduler.add_job(DaTa_Sta_Minutes_Task, 'interval', seconds=180, id='Hour_Task')
+
+    try:
+
+        scheduler.start()
+    except Exception as e:
+        scheduler.shutdown()
+        print(repr(e))
+        mylog.logopt(e)

+ 0 - 0
LIB/MIDDLE/SaftyCenter/diagfault/各项目sn号.xlsx → LIB/MIDDLE/SaftyCenter/DataDiag_Static/各项目sn号.xlsx


+ 0 - 0
LIB/MIDDLE/SaftyCenter/diagfault/故障表头及数据类型.xlsx → LIB/MIDDLE/SaftyCenter/DataDiag_Static/故障表头及数据类型.xlsx


+ 0 - 141
LIB/MIDDLE/SaftyCenter/DataSta/main.py

@@ -1,141 +0,0 @@
-import numpy as np
-import pandas as pd
-from LIB.MIDDLE.SaftyCenter.Common import FeiShuData
-from LIB.MIDDLE.SaftyCenter.Common import DBDownload
-import time, datetime
-from pandas.core.frame import DataFrame
-from apscheduler.schedulers.blocking import BlockingScheduler
-from DataStatistics import DataSta
-
-#............................主程序................................... 
-   
-
-
-def Week_Task():
-    all_period_fault_info=DataFrame(columns=['factory','week','level1_count','level2_count','level3_count','level4_count','level5_count','solve_rate'])
-
-    #............................获取数据................................
-    toweek='Week'+time.strftime('%W')
-    CS_Data=FeiShuData.getFeiShuDATA()
-    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port=3306
-    db='safety_platform'
-    user='qx_read'
-    password='Qx@123456'
-    mode=2
-    tablename1='all_fault_info'
-    DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
-    with DBRead as DBRead:
-        df_fltinfo=DBRead.getdata('product_id','level','code','start_time',tablename=tablename1,factory='骑享',sn='',timename='',st='',sp='')#dbdownload经过了改编
-    #............................获取时间................................      
-    end_time=datetime.datetime.now()
-    # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
-    start_time=end_time-datetime.timedelta(days=7)
-    start_time=start_time.strftime('%Y-%m-%d')
-    end_time=end_time.strftime('%Y-%m-%d')
-    FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(CS_Data,df_fltinfo,start_time,end_time)
-    FaultLvlCount=DataSta.WeekInfoSta(df_fltinfo,start_time,end_time)
-    lvl1=FaultLvlCount[FaultLvlCount['level']==1]['product_id'].values
-    lvl2=FaultLvlCount[FaultLvlCount['level']==2]['product_id'].values
-    lvl3=FaultLvlCount[FaultLvlCount['level']==3]['product_id'].values
-    lvl4=FaultLvlCount[FaultLvlCount['level']==4]['product_id'].values
-    lvl5=FaultLvlCount[FaultLvlCount['level']==5]['product_id'].values
-    all_period_fault_info.loc[0,'factory']='骑享'
-    all_period_fault_info.loc[0,'week']=toweek
-    all_period_fault_info.loc[0,'level1_count']=lvl1
-    all_period_fault_info.loc[0,'level2_count']=lvl2
-    all_period_fault_info.loc[0,'level3_count']=lvl3
-    all_period_fault_info.loc[0,'level4_count']=lvl4
-    all_period_fault_info.loc[0,'level5_count']=lvl5
-    all_period_fault_info.loc[0,'solve_rate']=FltAlarmInfo.loc[0,'OprationManageRate']
-    
-def Minutes_Task():
-    
-    #............................获取数据................................
-    host='172.16.121.236'
-    port=3306
-    db='fastfun'
-    user='readonly'
-    password='Fast1234'
-    mode=3
-    tablename1='ff_battery_accum'
-    DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
-    with DBRead as DBRead:
-        df_last_accum=DBRead.getdata('devcode','dsg_phaccum','dsg_ahaccum',tablename=tablename1,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
-
-    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port=3306
-    db='qx_cas'
-    user='qx_read'
-    password='Qx@123456'
-    mode=3
-    tablename2='bat_first_data_time'
-    DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
-    with DBRead as DBRead:
-        df_FirstDataTime=DBRead.getdata('sn','first_data_time',tablename=tablename2,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
-    CS_Data=FeiShuData.getFeiShuDATA()
-    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
-    port=3306
-    db='safety_platform'
-    user='qx_read'
-    password='Qx@123456'
-    mode=2
-    tablename1='all_fault_info'
-    DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
-    with DBRead as DBRead:
-        df_fltinfo=DBRead.getdata('product_id','level','code','start_time',tablename=tablename1,factory='骑享',sn='',timename='',st='',sp='')#dbdownload经过了改编
-    #............................获取时间................................
-    end_time=datetime.datetime.now()
-    # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
-    start_time=end_time-datetime.timedelta(days=1)
-    start_time=start_time.strftime('%Y-%m-%d')
-    end_time=end_time.strftime('%Y-%m-%d')
-    #............................执行程序................................
-    FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(CS_Data,df_fltinfo,start_time,end_time)
-    SatftyCount=DataSta.SftyWrngClsfy(df_fltinfo)
-    MaxAccumAh,TotalAccumAh,MaxCycle,MaxRunningHour,TotalRunHour=DataSta.AccumInfo(df_last_accum,df_FirstDataTime,end_time)
-
-    all_statistic_info=DataFrame(columns=['factory','total_alarm','alarm_total_today','alarm_not_close_today','alarm_close_today','alarm_uregent_total_today','alarm_uregent_close_today','alarm_uregent_not_close_today','alarm_close_total','run_time_total','dischrg_total','odo_total','max_dischrg_one','max_runtime_one','max_cycle_one','max_odo_one','alarm_close_total','alarm_total','cell_type','cell_type_count','cell_safety_risk_count','data_safety_risk_count','status_safety_risk_count','hv_safety_risk_count','system_safety_risk_count','sample_safety_risk_count','controller_safety_risk_count','design_safety_risk_count'])
-    all_statistic_info.loc[0,'factory']='骑享'
-    all_statistic_info.loc[0,'total_alarm']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
-    all_statistic_info.loc[0,'alarm_total_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']
-    all_statistic_info.loc[0,'alarm_close_today']=FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
-    all_statistic_info.loc[0,'alarm_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']-FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
-    all_statistic_info.loc[0,'alarm_uregent_total_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']
-    all_statistic_info.loc[0,'alarm_uregent_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
-    all_statistic_info.loc[0,'alarm_uregent_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']-FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
-    all_statistic_info.loc[0,'run_time_total']=TotalRunHour
-    all_statistic_info.loc[0,'dischrg_total']=TotalAccumAh
-    all_statistic_info.loc[0,'odo_total']=0
-    all_statistic_info.loc[0,'max_dischrg_one']=MaxAccumAh
-    all_statistic_info.loc[0,'max_runtime_one']=MaxRunningHour
-    all_statistic_info.loc[0,'max_cycle_one']=MaxCycle
-    all_statistic_info.loc[0,'max_odo_one']=0
-    all_statistic_info.loc[0,'alarm_close_total']=FltAlarmInfo.loc[0,'CS_Warning_Total_Finish_Count']
-    all_statistic_info.loc[0,'alarm_total']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
-    CellType=Celltype.columns.tolist()
-    CellType=','.join(CellType) 
-    all_statistic_info.loc[0,'cell_type']=str(CellType)
-    CellTypeCount=Celltype.loc[0].tolist()
-    CellTypeCount=[str(x) for x in CellTypeCount]
-    CellTypeCount=','.join(CellTypeCount) 
-    all_statistic_info.loc[0,'cell_type_count']=str(CellTypeCount)
-    all_statistic_info.loc[0,'cell_safety_risk_count']=SatftyCount.loc[0,'CellSaftyCount']
-    all_statistic_info.loc[0,'data_safety_risk_count']=SatftyCount.loc[0,'DataSaftyCodeCount']
-    all_statistic_info.loc[0,'status_safety_risk_count']=SatftyCount.loc[0,'StateSaftyCodeCount']
-    all_statistic_info.loc[0,'hv_safety_risk_count']=SatftyCount.loc[0,'HvSaftyCodeCount']
-    all_statistic_info.loc[0,'system_safety_risk_count']=SatftyCount.loc[0,'SysSaftyCodeCount']
-    all_statistic_info.loc[0,'sample_safety_risk_count']=SatftyCount.loc[0,'SamplingSatyCount']
-    all_statistic_info.loc[0,'controller_safety_risk_count']=SatftyCount.loc[0,'CtrlSaftyCodeCount']
-    all_statistic_info.loc[0,'design_safety_risk_count']=SatftyCount.loc[0,'DsnSaftyCodeCount']
-#定时任务....................................................................................................................................................................... 
-#Week_Task()
-Minutes_Task()
-scheduler = BlockingScheduler()
-scheduler.add_job(Week_Task, 'interval', days=7, id='Week_Task')
-scheduler.add_job(Minutes_Task, 'interval', seconds=300, id='Hour_Task')
-try:  
-    scheduler.start()
-except Exception as e:
-    scheduler.shutdown()
-    print(repr(e))

+ 221 - 0
LIB/MIDDLE/SaftyCenter/Liplated/BatParam.py

@@ -0,0 +1,221 @@
+
+#定义电池参数
+class BatParam:
+    def __init__(self,celltype):
+
+        #公用参数................................................................................................................................................
+        self.CellTempUpLmt=119
+        self.CellTempLwLmt=-39
+        self.CellTempHighLv1=45
+        self.CellTempHighLv2=50
+        self.CellTempLowLv1=-20
+        self.CellTempLowLv2=-25
+        self.CellTempDiffLv1=10
+        self.CellTempDiffLv2=15
+        self.CellTempRate=5
+
+       #热失控参数
+        self.TrwTempHigh=60
+        self.TrwTempRate=20
+        self.TrwTempDiff=15
+        self.TrwCellVoltDiff=2.5
+        self.TrwCellVoltFall=1
+        self.TrwCellVoltLow=1.5
+        self.TrwPackVoltFall=1.5
+
+        self.SocJump=3
+        self.SocClamp=0.1
+        self.SocLow=3
+        self.SocDiff=20
+
+        self.SohLow=65
+        self.SohDiff=20
+
+        self.OcvWeight_Temp=[-30,-20,-10,0,10,20,30,40,50]
+        self.OcvWeight_StandingTime=[0,500,600,1200,1800,3600,7200,10800]
+        self.OcvWeight            =[[0,0,  0,  0,    0,   0.1,0.3, 1],
+                                    [0,0,  0,  0,    0,   0.1,0.3, 1],
+                                    [0,0,  0,  0,    0,   0.2,0.5, 1],
+                                    [0,0,  0,  0,    0.2, 0.4,0.8, 1],
+                                    [0,0,  0,  0.1,  0.3, 0.6,1,   1],
+                                    [0,0,  0.1,0.2,  0.5, 0.8,1,   1],
+                                    [0,0,  0.1,0.3,  0.6, 1,  1,   1],
+                                    [0,0,  0.1,0.3,  0.7, 1,  1,   1],
+                                    [0,0,  0.2,0.3,  0.8, 1,  1,   1]]
+
+
+        if celltype==1: #6040
+            self.Capacity = 41
+            self.PackFullChrgVolt=69.99
+            self.CellFullChrgVolt=4.2
+            self.CellFullChrgCrnt=-15
+            self.CellVoltNums=17
+            self.CellTempNums=3
+            self.OtherTempNums=5
+            self.FullChrgSoc=98
+            self.PackCrntDec=1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0,	    3.5348,	8.3581,	13.181,	18.004,	22.827,	27.651,	32.474,	37.297,	42.120,	46.944,	51.767,	56.590,	61.413,	66.237,	71.060,	75.883,	80.707,	85.530,	90.353,	95.176,	100,   105]
+            self.LookTab_OCV = [3.3159,	3.4384,	3.4774,	3.5156,	3.5478,	3.5748,	3.6058,	3.6238,	3.638,	3.6535,	3.6715,	3.6951,	3.7279,	3.7757,	3.8126,	3.8529,	3.8969,	3.9446,	3.9946,	4.0491,	4.109,	4.183, 4.263]
+
+            self.CellOvLv1=4.3
+            self.CellOvLv2=4.35
+            self.CellUvLv1=2.8
+            self.CellUvLv2=2.5
+            self.CellVoltDiffLv1=0.3
+            self.CellVoltDiffLv2=0.5
+            self.PackVoltOvLv1=self.CellOvLv1*self.CellVoltNums
+            self.PackVoltOvLv2=self.CellOvLv2*self.CellVoltNums
+            self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
+            self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
+
+            self.PackChgOc=-40
+            self.PackDisOc=200
+
+            self.LeakCurrentLv1=10
+            self.LeakCurrentLv2=20
+            self.LeakCurrentLv3=50
+
+        elif celltype==2: #4840
+            self.Capacity = 41
+            self.PackFullChrgVolt=69.99
+            self.CellFullChrgVolt=4.2
+            self.CellFullChrgCrnt=-15
+            self.CellVoltNums=14
+            self.CellTempNums=3
+            self.OtherTempNums=4
+            self.FullChrgSoc=98
+            self.PackCrntDec=1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0,	    3.5348,	8.3581,	13.181,	18.004,	22.827,	27.651,	32.474,	37.297,	42.120,	46.944,	51.767,	56.590,	61.413,	66.237,	71.060,	75.883,	80.707,	85.530,	90.353,	95.176,	100,   105]
+            self.LookTab_OCV = [3.3159,	3.4384,	3.4774,	3.5156,	3.5478,	3.5748,	3.6058,	3.6238,	3.638,	3.6535,	3.6715,	3.6951,	3.7279,	3.7757,	3.8126,	3.8529,	3.8969,	3.9446,	3.9946,	4.0491,	4.109,	4.183, 4.263]
+
+            self.CellOvLv1=4.3
+            self.CellOvLv2=4.35
+            self.CellUvLv1=2.8
+            self.CellUvLv2=2.5
+            self.CellVoltDiffLv1=0.3
+            self.CellVoltDiffLv2=0.5
+            self.PackVoltOvLv1=self.CellOvLv1*self.CellVoltNums
+            self.PackVoltOvLv2=self.CellOvLv2*self.CellVoltNums
+            self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
+            self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
+
+            self.PackChgOc=-40
+            self.PackDisOc=200
+
+            self.LeakCurrentLv1=10
+            self.LeakCurrentLv2=20
+            self.LeakCurrentLv3=50
+
+        elif celltype==3:   #力信50ah三元电芯
+            self.Capacity = 51
+            self.PackFullChrgVolt=80
+            self.CellFullChrgVolt=4.2
+            self.CellFullChrgCrnt=-15
+            self.CellVoltNums=20
+            self.CellTempNums=3
+            self.OtherTempNums=4
+            self.FullChrgSoc=98
+            self.PackCrntDec=1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0,	    5,	    10,	    15,	    20,	    25,	    30,	    35,	    40,	    45,	    50,	    55,	    60,	    65,	    70,	    75,	    80,	    85,	    90,	    95,	    100,   105]
+            self.LookTab_OCV = [3.357, 	3.455, 	3.493, 	3.540, 	3.577, 	3.605, 	3.622, 	3.638, 	3.655, 	3.677, 	3.707, 	3.757, 	3.815, 	3.866, 	3.920, 	3.976, 	4.036, 	4.099, 	4.166, 	4.237, 	4.325, 4.415]
+
+            self.CellOvLv1=4.3
+            self.CellOvLv2=4.35
+            self.CellUvLv1=2.8
+            self.CellUvLv2=2.5
+            self.CellVoltDiffLv1=0.3
+            self.CellVoltDiffLv2=0.5
+            self.PackVoltOvLv1=self.CellOvLv1*self.CellVoltNums
+            self.PackVoltOvLv2=self.CellOvLv2*self.CellVoltNums
+            self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
+            self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
+
+            self.PackChgOc=-40
+            self.PackDisOc=200
+
+            self.LeakCurrentLv1=10
+            self.LeakCurrentLv2=20
+            self.LeakCurrentLv3=50
+
+        elif celltype==4:   #CATL 50ah三元电芯
+            self.Capacity = 50
+            self.PackFullChrgVolt=80
+            self.CellFullChrgVolt=4.2
+            self.CellFullChrgCrnt=-15
+            self.CellVoltNums=20
+            self.CellTempNums=2
+            self.OtherTempNums=0
+            self.FullChrgSoc=98
+            self.PeakSoc=57
+            self.PackCrntDec=-1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0,	    5,	    10,	    15,	    20,	    25,	    30,	    35,	    40,	    45,	    50,	    55,	    60,	    65,	    70,	    75,	    80,	    85,	    90,	    95,	    100,   105]
+            self.LookTab_OCV = [3.152, 	3.397, 	3.438, 	3.481, 	3.523, 	3.560, 	3.586, 	3.604, 	3.620, 	3.638, 	3.661, 	3.693, 	3.748, 	3.803, 	3.853, 	3.903, 	3.953, 	4.006, 	4.063, 	4.121, 	4.183, 4.253]
+
+            self.CellOvLv1=4.3
+            self.CellOvLv2=4.35
+            self.CellUvLv1=2.8
+            self.CellUvLv2=2.5
+            self.CellVoltDiffLv1=0.3
+            self.CellVoltDiffLv2=0.5
+            self.PackVoltOvLv1=self.CellOvLv1*self.CellVoltNums
+            self.PackVoltOvLv2=self.CellOvLv2*self.CellVoltNums
+            self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
+            self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
+
+            self.PackChgOc=-40
+            self.PackDisOc=200
+
+            self.LeakCurrentLv1=10
+            self.LeakCurrentLv2=20
+            self.LeakCurrentLv3=50
+
+        elif celltype==99:   #60ah磷酸铁锂电芯
+            self.Capacity = 54
+            self.PackFullChrgVolt=69.99
+            self.CellFullChrgVolt=3.5
+            self.CellFullChrgCrnt=-20
+            self.OcvInflexionBelow=3.281
+            self.OcvInflexion2=3.296
+            self.OcvInflexion3=3.328
+            self.OcvInflexionAbove=3.4
+            self.SocInflexion1=30
+            self.SocInflexion2=60
+            self.SocInflexion3=70
+            self.CellVoltNums=20
+            self.CellTempNums=4
+            self.OtherTempNums=5
+            self.FullChrgSoc=98
+            self.PeakSoc=59
+            self.PeakVoltLowLmt=3.35
+            self.PeakVoltUpLmt=3.4
+            self.PeakCellVolt=[3.362,3.363,3.365,3.366,3.367]
+            self.PackCrntDec=1
+            self.BalCurrent=0.015
+            self.LookTab_SOC = [0.00, 	2.40, 	6.38, 	10.37, 	14.35, 	18.33, 	22.32, 	26.30, 	30.28, 	35.26, 	40.24, 	45.22, 	50.20, 	54.19, 	58.17, 	60.16, 	65.14, 	70.12, 	75.10, 	80.08, 	84.06, 	88.05, 	92.03, 	96.02, 	100.00]
+            self.LookTab_OCV = [2.7151,	3.0298,	3.1935,	3.2009,	3.2167,	3.2393,	3.2561,	3.2703,	3.2843,	3.2871,	3.2874,	3.2868,	3.2896,	3.2917,	3.2967,	3.3128,	3.3283,	3.3286,	3.3287,	3.3288,	3.3289,	3.3296,	3.3302,	3.3314,	3.3429]
+
+            self.CellOvLv1=3.68
+            self.CellOvLv2=3.7
+            self.CellUvLv1=2.1
+            self.CellUvLv2=2
+            self.CellVoltDiffLv1=0.6
+            self.CellVoltDiffLv2=1
+            self.PackVoltOvLv1=self.CellOvLv1*self.CellVoltNums
+            self.PackVoltOvLv2=self.CellOvLv2*self.CellVoltNums
+            self.PackVoltUvLv1=self.CellUvLv1*self.CellVoltNums
+            self.PackVoltUvLv2=self.CellUvLv2*self.CellVoltNums
+
+            self.PackChgOc=-40
+            self.PackDisOc=200
+
+            self.LeakCurrentLv1=20
+            self.LeakCurrentLv2=50
+            self.LeakCurrentLv3=100
+        else:
+            print('未找到对应电池编号!!!')
+            # sys.exit()
+

+ 164 - 0
LIB/MIDDLE/SaftyCenter/Liplated/Li_plated.py

@@ -0,0 +1,164 @@
+import pandas as pd
+import numpy as np
+import datetime
+import matplotlib as plt
+from scipy.signal import savgol_filter
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import BatParam
+
+class Liplated_test:
+    def __init__(self,sn,celltype,df_bms):  #参数初始化
+
+        self.sn=sn
+        self.celltype=celltype
+        self.param=BatParam.BatParam(celltype)
+        self.df_bms=pd.DataFrame(df_bms)
+        self.packcrnt=df_bms['总电流[A]']*self.param.PackCrntDec
+        self.packvolt=df_bms['总电压[V]']
+        self.bms_soc=df_bms['SOC[%]']
+        self.bmstime= pd.to_datetime(df_bms['时间戳'], format='%Y-%m-%d %H:%M:%S')
+
+        self.cellvolt_name=['单体电压'+str(x) for x in range(1,self.param.CellVoltNums+1)]
+        self.celltemp_name=['单体温度'+str(x) for x in range(1,self.param.CellTempNums+1)]
+        self.bmssta = df_bms['充电状态']
+    #定义加权滤波函数..................................................................................................
+    def moving_average(interval, windowsize):
+        window = np.ones(int(windowsize)) / float(windowsize)
+        re = np.convolve(interval, window, 'same')
+        return re
+#.............................................析锂检测............................................................................
+    def liplated_detect(self):
+        #----------------------------------------筛选充电后静置数据------------------------------------------------------------
+        chrgr_rest_data_temp = self.df_bms.loc[((self.df_bms['充电状态'] == 0) & (self.df_bms['SOC[%]'] > 98) & (self.df_bms['总电流[A]'] == 0)) | 
+                                               ((self.df_bms['充电状态'] == 2) & (self.df_bms['SOC[%]'] > 98) & (self.df_bms['总电流[A]'] == 0))]#接近慢充后静置数据
+        df_lipltd_result = pd.DataFrame(columns=['sn','time','liplated','liplated_amount'])
+        if not chrgr_rest_data_temp.empty:
+            chrgr_rest_data = chrgr_rest_data_temp.reset_index(drop=True)
+            temp_rest_time = chrgr_rest_data['时间戳']
+            rest_time = pd.to_datetime(temp_rest_time)
+            delta_time = (np.diff(rest_time)/pd.Timedelta(1, 'min'))#计算时间差的分钟数
+            pos = np.where(delta_time > 30)#静置数据分段,大于30min时,认为是两个静置过程
+            splice_num = []
+            if len(pos[0]) >= 1:
+                pos_ful_tem = np.insert(pos, 0, 0)
+                pos_len = len(pos_ful_tem)
+                data_len = len(rest_time)
+                pos_ful = np.insert(pos_ful_tem, pos_len, data_len-1)
+                for item in range(0,len(pos_ful)-1):
+                    splice_num.extend(item*np.ones(pos_ful[item +1]-pos_ful[item]))
+                splice_num = np.insert(splice_num, 0, 0)
+            else:
+                splice_num = np.zeros(len(temp_rest_time))
+                pos_ful = np.array([0])
+            chrgr_rest_data['chrgr_rest'] = splice_num
+            #---------------------------判断数据点数大于30的数据段,对电压微分并画图--------------------------------------------
+            cellvolt_list = self.cellvolt_name
+            chrgr_rest_check_data = chrgr_rest_data.drop(['GSM信号','故障等级','故障代码','绝缘电阻','总电流[A]','总电压[V]','充电状态','单体压差','SOC[%]'],axis=1,inplace=False)
+            chrgr_rest_check_data.fillna(value=0)
+            df_rest_volt_diffdt = pd.DataFrame()
+            df_rest_volt_smooth = pd.DataFrame()
+            k = 0
+            for j in range(0,len(pos_ful)-1):#len(pos_ful)-1#有几段充电后静置数据
+                df_test_rest_data = chrgr_rest_check_data.loc[chrgr_rest_check_data['chrgr_rest'] == j]
+                df_rest_volt_smooth = pd.DataFrame()
+                df_test_rest_time = pd.to_datetime(df_test_rest_data['时间戳'],format='%Y-%m-%d %H:%M:%S')
+                df_test_rest_time = df_test_rest_time.reset_index(drop=True)
+                df_data_length = len(df_test_rest_time)
+                if (df_data_length > 30) & ((df_test_rest_time[df_data_length - 1] - df_test_rest_time[0])/pd.Timedelta(1, 'min') > 40):#静置时间大于40min
+                    df_test_rest_time_dif_temp = np.diff(df_test_rest_time)/pd.Timedelta(1, 'min')
+                    num_list = []
+                    data_jump_pos = np.where(df_test_rest_time_dif_temp > 3)
+                    if len(data_jump_pos[0]) > 0:
+                        if data_jump_pos[0][0] > 100:
+                            for i in range(0,data_jump_pos[0][0],15):##采样密集时每隔10行取数据
+                                num_list.append(i)
+                            df_rest_data_temp = df_test_rest_data.iloc[num_list]
+                            df_test_rest_data_choose = pd.DataFrame(df_rest_data_temp)
+                            df_test_rest_data_choose_else = df_test_rest_data.iloc[data_jump_pos[0][0]+1:len(df_test_rest_data)-1]
+                            df_rest_data_recon_temp = df_test_rest_data_choose.append(df_test_rest_data_choose_else)
+                            df_rest_data_recon =df_rest_data_recon_temp.reset_index(drop=True)
+                        else:
+                            df_rest_data_recon = df_test_rest_data
+                    else:
+                        df_rest_data_recon = df_test_rest_data
+                    df_rest_time = pd.to_datetime(df_rest_data_recon['时间戳'],format='%Y-%m-%d %H:%M:%S')
+                    df_rest_time = df_rest_time.reset_index(drop=True)
+                    df_rest_time_dif_temp = np.diff(df_rest_time)/pd.Timedelta(1, 'min')
+                    df_rest_volt = df_rest_data_recon[cellvolt_list]
+                    for item in cellvolt_list:
+                        window_temp = int(len(df_rest_volt[item])/3)
+                        if window_temp%2:#滤波函数的窗口长度需为奇数
+                            window = window_temp
+                        else:
+                            window = window_temp - 1
+                        step = min(int(window/3),5)
+                        df_volt_smooth = savgol_filter(df_rest_volt[item],window,step)
+                        df_rest_volt_smooth[item] = df_volt_smooth
+                    df_test_rest_volt_diff_temp = np.diff(df_rest_volt_smooth,axis=0)
+                    df_test_rest_time_dif = pd.DataFrame(df_rest_time_dif_temp)
+                    df_test_rest_volt_diff = pd.DataFrame(df_test_rest_volt_diff_temp)
+                    df_test_rest_volt_diffdt_temp = np.divide(df_test_rest_volt_diff,df_test_rest_time_dif)
+                    df_test_rest_volt_diffdt = pd.DataFrame(df_test_rest_volt_diffdt_temp)
+                    df_test_rest_volt_diffdt = df_test_rest_volt_diffdt.append(df_test_rest_volt_diffdt.iloc[len(df_test_rest_volt_diffdt)-1])
+                    df_test_rest_volt_diffdt.columns = cellvolt_list
+                    if len(df_test_rest_volt_diffdt) > 25:
+                        for item in cellvolt_list:
+                            df_volt_diffdt_smooth = savgol_filter(df_test_rest_volt_diffdt[item],13,3)
+                            df_test_rest_volt_diffdt[item] = df_volt_diffdt_smooth
+                        df_test_rest_volt_diffdt['chrgr_rest'] = k
+                        df_test_rest_volt_diffdt['时间戳'] = list(df_rest_time)
+                        k = k+1
+                        df_rest_volt_diffdt = df_rest_volt_diffdt.append(df_test_rest_volt_diffdt)
+                        df_rest_volt_diffdt.reset_index()
+            #--------------------------------------------------------确认是否析锂----------------------------------------------------------------------------
+            # df_lipltd_data = pd.DataFrame(columns=['sn','date','liplated'])
+            for item in range(0,k):
+                lipltd_confirm = []
+                lipltd_amount = []
+                df_check_liplated_temp = df_rest_volt_diffdt.loc[df_rest_volt_diffdt['chrgr_rest'] == item].reset_index(drop = True)
+                df_lipltd_volt_temp = df_check_liplated_temp[cellvolt_list]
+                df_lipltd_volt_len = len(df_lipltd_volt_temp)
+                df_data_temp_add = df_lipltd_volt_temp.iloc[df_lipltd_volt_len-4:df_lipltd_volt_len-1]
+                df_lipltd_volt_temp_add = df_lipltd_volt_temp.append(df_data_temp_add)
+                df_lipltd_volt_temp_dif = np.diff(df_lipltd_volt_temp_add,axis=0)#电压一次微分,计算dv/dt
+                df_lipltd_volt_temp_dif = pd.DataFrame(df_lipltd_volt_temp_dif)
+                df_lipltd_volt_temp_dif.columns = cellvolt_list
+                df_lipltd_volt_temp_difdif = np.diff(df_lipltd_volt_temp_dif,axis=0)#电压二次微分,判断升降
+                df_lipltd_volt_temp_difdif = pd.DataFrame(df_lipltd_volt_temp_difdif)
+                df_lipltd_volt_temp_difdif.columns = cellvolt_list
+                df_lipltd_volt_temp_difdif_temp = df_lipltd_volt_temp_difdif
+                df_lipltd_volt_temp_difdif_temp[df_lipltd_volt_temp_difdif_temp >= 0] = 1
+                df_lipltd_volt_temp_difdif_temp[df_lipltd_volt_temp_difdif_temp < 0] = -1
+                df_lipltd_volt_temp_difdifdif = np.diff(df_lipltd_volt_temp_difdif_temp,axis=0)#三次微分,利用-2,2判断波分和波谷
+                df_lipltd_volt_difdifdif = pd.DataFrame(df_lipltd_volt_temp_difdifdif)
+                df_lipltd_volt_difdifdif.columns = cellvolt_list
+                df_lipltd_volt_difdifdif['chrgr_rest'] = k
+                df_lipltd_volt_difdifdif['时间戳'] = list(df_check_liplated_temp['时间戳'])
+                df_lipltd_volt_difdifdif = df_lipltd_volt_difdifdif.reset_index(drop = True)
+                df_lipltd_data_temp = df_lipltd_volt_difdifdif.loc[df_lipltd_volt_difdifdif['时间戳'] < (df_check_liplated_temp['时间戳'][0] + datetime.timedelta(minutes=90))]
+                for cell_name in cellvolt_list:#对每个电芯判断
+                    df_check_plated_data = df_lipltd_data_temp[cell_name]
+                    peak_pos = np.where(df_check_plated_data == -2)
+                    bot_pos = np.where(df_check_plated_data == 2)
+                    if len(peak_pos[0]) & len(bot_pos[0]):
+                        if (peak_pos[0][0] > bot_pos[0][0]) & (df_lipltd_volt_temp_dif[cell_name][peak_pos[0][0] + 1] < 0):
+                            lipltd_confirm.append(1)#1为析锂,0为非析锂
+                            lipltd_amount.append((df_check_liplated_temp['时间戳'][bot_pos[0][0] + 2] - df_check_liplated_temp['时间戳'][0])/pd.Timedelta(1, 'min'))
+                        else:
+                            lipltd_confirm.append(0)
+                            lipltd_amount.append(0)
+                    else:
+                        lipltd_confirm.append(0)
+                        lipltd_amount.append(0)
+                if any(lipltd_confirm) & (max(lipltd_amount) > 5):
+                    df_lipltd_confir_temp = pd.DataFrame({"sn":[self.sn], "time":[df_check_liplated_temp['时间戳'][0]], "liplated":[str(lipltd_confirm)], "liplated_amount":[str(lipltd_amount)]})
+                    df_lipltd_result = df_lipltd_result.append(df_lipltd_confir_temp)
+                    df_lipltd_result = df_lipltd_result.reset_index(drop = True)
+                    df_lipltd_result.sort_values(by = ['time'], axis = 0, ascending=True,inplace=True)#对故障信息按照时间进行排序
+        # df_lipltd_data.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\02析锂检测\liplated\算法开发_检测\滤波后图片\析锂.csv',index=False,encoding='GB18030')
+        #返回诊断结果...........................................................................................................
+        if not df_lipltd_result.empty:
+            return df_lipltd_result
+        else:
+            return pd.DataFrame()
+
+

+ 94 - 0
LIB/MIDDLE/SaftyCenter/Liplated/main.py

@@ -0,0 +1,94 @@
+import datetime
+import pandas as pd
+from LIB.BACKEND import DBManager, Log
+import time, datetime
+from apscheduler.schedulers.blocking import BlockingScheduler
+import log
+from pandas.core.frame import DataFrame
+import Li_plated
+
+#...................................电池包电芯安全诊断函数......................................................................................................................
+def cell_platd_test():
+    global SNnums
+    global df_Diag_lipltd
+    start=time.time()
+    now_time=datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
+    now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')
+    start_time=now_time-datetime.timedelta(days=3)
+    end_time=str(now_time)
+    start_time=str(start_time)
+    for sn in SNnums:
+        if 'PK500' in sn:
+            celltype=1 #6040三元电芯
+        elif 'PK502' in sn:
+            celltype=2 #4840三元电芯
+        elif 'K504B' in sn:
+            celltype=99    #60ah林磷酸铁锂电芯
+        elif 'MGMLXN750' in sn:
+            celltype=3 #力信50ah三元电芯
+        elif 'MGMCLN750' or 'UD' in sn: 
+            celltype=4 #CATL 50ah三元电芯
+        else:
+            print('SN:{},未找到对应电池类型!!!'.format(sn))
+            continue
+            # sys.exit()
+        #读取原始数据库数据........................................................................................................................................................
+        start_time = '2021-11-15 12:00:00'
+        end_time = '2021-11-18 12:00:00'
+        dbManager = DBManager.DBManager()
+        df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
+        df_bms = df_data['bms']
+        df_Diag_lipltd_add = pd.DataFrame(columns = ['sn','time','liplated', 'liplated_amount'])
+
+        #析锂诊断................................................................................................................................................................
+        if not df_bms.empty:
+            Diag_lipltd_temp = Li_plated.Liplated_test(sn,celltype,df_bms)#析锂检测
+            df_Diag_lipltd_add = Diag_lipltd_temp.liplated_detect()        
+        if not df_Diag_lipltd_add.empty:
+            df_Diag_lipltd_temp = df_Diag_lipltd.append(df_Diag_lipltd_add)
+            df_Diag_lipltd = df_Diag_lipltd_temp.drop_duplicates(subset = ['sn','time'], keep = 'first', inplace = False)
+            df_Diag_lipltd.sort_values(by = ['sn'], axis = 0, ascending=True,inplace=True)#对故障信息按照时间进行排序
+            df_Diag_lipltd.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\02析锂检测\01下载数据\格林美-力信7255\SNnums_6040_liplated_sn.csv',index=False,encoding='GB18030')
+        end=time.time()
+        print(end-start)
+
+#...............................................主函数.......................................................................................................................
+if __name__ == "__main__":
+    global SNnums
+    global df_Diag_lipltd
+    
+    excelpath=r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\04故障诊断\01Screen_Problem\sn-20210903.xlsx'
+    SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
+    SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
+    SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
+    SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
+    SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
+    SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
+    SNnums_6060=SNdata_6060['SN号'].tolist()
+    SNnums_6040=SNdata_6040['SN号'].tolist()
+    SNnums_4840=SNdata_4840['SN号'].tolist()
+    SNnums_L7255=SNdata_L7255['SN号'].tolist()
+    SNnums_C7255=SNdata_C7255['SN号'].tolist()
+    SNnums_U7255=SNdata_U7255['SN号'].tolist()
+    #SNnums=SNnums_L7255 + SNnums_C7255 + SNnums_6040 + SNnums_4840 + SNnums_U7255+ SNnums_6060
+    # SNnums=['MGMCLN750N215I005','PK504B10100004341','PK504B00100004172','MGMLXN750N2189014']
+    SNnums = SNnums_6040 #SNnums_C7255 #SNnums_6040['MGMCLN750N215N049'] 
+    # SNnums = pd.read_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\02析锂检测\liplated\疑似析锂电池sn.csv',encoding='GB18030')
+    
+    mylog=log.Mylog('log_diag.txt','error')
+    mylog.logcfg()
+    #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................
+    df_Diag_lipltd=pd.read_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\02析锂检测\01下载数据\格林美-力信7255\析锂.csv',encoding='GB18030')
+
+    print('----------------输入--------')
+    print('-------计算中-----------')
+    #定时任务.......................................................................................................................................................................
+    scheduler = BlockingScheduler()
+    scheduler.add_job(cell_platd_test, 'interval', seconds=10, id='diag_job')
+
+    try:  
+        scheduler.start()
+    except Exception as e:
+        scheduler.shutdown()
+        print(repr(e))
+        mylog.logopt(e)

BIN
LIB/MIDDLE/SaftyCenter/Liplated/析锂.xlsx


+ 35 - 0
LIB/MIDDLE/SaftyCenter/Low_Soc_Alarm/low_soc_alarm.py

@@ -0,0 +1,35 @@
+import numpy as np
+import pandas as pd
+from pandas.core.frame import DataFrame
+from LIB.MIDDLE.SaftyCenter.Common import QX_BatteryParam
+from LIB.BACKEND import DBManager
+import datetime,time
+
+class Low_soc_alarm():
+    def low_soc_alarm(param,df_bms,low_soc_bat_list,sn,df_OprtnSta):
+        if len(df_bms) and df_OprtnSta.loc[0,'status'] !=3:#0禁用 1正常 2故障 3返修 4 损毁 5丢失已赔偿,6丢失未赔偿:
+            VoltageNum=['单体电压'+str(i) for i in range(1,param.CellVoltNums+1)]
+            df_bms[VoltageNum]=df_bms[VoltageNum]/1000
+            CellVol=df_bms[VoltageNum]
+            PackCrnt=df_bms['总电流[A]']
+            ZeroCrntCount=len(df_bms[abs(df_bms['总电流[A]'])<=1])
+            CrntCount=len(PackCrnt)-ZeroCrntCount
+            if CrntCount>0:
+                ZeroCrntRate=(ZeroCrntCount/len(PackCrnt))*100
+            else:
+                ZeroCrntRate=100
+            if ZeroCrntRate>99.85:#静置比大于99.85%
+                ZeroSoc_Volt=np.interp(0,param.LookTab_SOC,param.LookTab_OCV)
+                FiveSoc_Volt=np.interp(10,param.LookTab_SOC,param.LookTab_OCV)
+                CellVolMean=DataFrame()
+                CellVolMean=CellVol.mean()
+                CellVolMin_Index=CellVolMean.idxmin()
+                print(ZeroSoc_Volt)
+                CellLowVolZERO=df_bms[df_bms[CellVolMin_Index] < ZeroSoc_Volt]
+                CellLowVolFive=df_bms[df_bms[CellVolMin_Index] > FiveSoc_Volt]
+                CellLowVolZeroCrnt=CellLowVolZERO[abs(CellLowVolZERO['总电流[A]'])<1]
+                CellLowVolFiveCrnt=CellLowVolFive[abs(CellLowVolFive['总电流[A]'])<1]
+                if len(CellLowVolZeroCrnt)>3 and len(CellLowVolFiveCrnt)<3:
+                    CellLowVolZeroCrnt=CellLowVolZeroCrnt.reset_index(drop=True)
+                    low_soc_bat_list.loc[len(low_soc_bat_list)]=[sn,CellLowVolZeroCrnt.loc[len(CellLowVolZeroCrnt)-1,'时间戳'],3]
+        return low_soc_bat_list

+ 86 - 0
LIB/MIDDLE/SaftyCenter/Low_Soc_Alarm/main.py

@@ -0,0 +1,86 @@
+import datetime
+import pandas as pd
+from LIB.BACKEND import DBManager, Log
+from sqlalchemy import create_engine
+import time, datetime
+from apscheduler.schedulers.blocking import BlockingScheduler
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload as DBDownload
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
+from pandas.core.frame import DataFrame
+import datacompy
+from LIB.MIDDLE.SaftyCenter.Common import QX_BatteryParam
+from LIB.MIDDLE.SaftyCenter.Common import DBDownload as DBDw
+from low_soc_alarm import Low_soc_alarm
+def Low_Soc_Alarm():
+    end_time=datetime.datetime.now()
+    start_time=end_time-datetime.timedelta(days=1)
+    start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
+    end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
+    #-------------------------读取数据-------------------------------------------------------------------
+    excelpath=r'D:\ZLWORK\code\data_analyze_platform\USER\eric\SaftyCenter_CODE_V1\sn-20210903.xlsx'
+    SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
+    SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
+    SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
+    SNdata_L7255 = pd.read_excel(excelpath, sheet_name='格林美-力信7255')
+    SNdata_C7255 = pd.read_excel(excelpath, sheet_name='格林美-CATL7255')
+    SNdata_U7255 = pd.read_excel(excelpath, sheet_name='优旦7255')
+    SNnums_6060=SNdata_6060['SN号'].tolist()
+    SNnums_6040=SNdata_6040['SN号'].tolist()
+    SNnums_4840=SNdata_4840['SN号'].tolist()
+    SNnums_L7255=SNdata_L7255['SN号'].tolist()
+    SNnums_C7255=SNdata_C7255['SN号'].tolist()
+    SNnums_U7255=SNdata_U7255['SN号'].tolist()
+    SNnums=SNnums_L7255 + SNnums_C7255 + SNnums_6040 + SNnums_4840 + SNnums_U7255+ SNnums_6060
+    #SNnums=['MGMCLN750N215I009']
+    #-------------------------执行循环----------------------------------------------------------------------
+    low_soc_bat_list=DataFrame(columns=['sn','time','level'])
+    for sn in SNnums:#SN遍历
+        print(sn)
+        if 'PK500' in sn:
+            celltype=1 #6040三元电芯
+        elif 'PK502' in sn:
+            celltype=2 #4840三元电芯
+        elif 'K504B' in sn:
+            celltype=99    #60ah林磷酸铁锂电芯
+        elif 'MGMLXN750' in sn:
+            celltype=3 #力信50ah三元电芯
+        elif 'MGMCLN750' or 'UD' in sn: 
+            celltype=4 #CATL 50ah三元电芯
+        else:
+            print('SN:{},未找到对应电池类型!!!'.format(sn))
+            continue
+            # sys.exit()
+        param=QX_BatteryParam.BatteryInfo(celltype)   
+        #读取原始数据库数据.....................................................................................
+        dbManager = DBManager.DBManager()
+        df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
+        df_bms = df_data['bms']
+        #读取电池当前运营状态.....................................................................................................................................................
+        host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
+        port=3306
+        db='qixiang_manage'
+        user='qx_query'
+        password='@Qx_query'
+        mode=4
+        tablename1='py_battery'     
+        DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
+        with DBRead as DBRead:
+            df_OprtnSta=DBRead.getdata('qrcode','status', tablename=tablename1, sn=sn, timename='', st='', sp='',factory='')#取最后一条运营状态
+        
+        
+        
+        #执行主程序-------------------------------------------------------------------------------------------
+        low_soc_bat_list=Low_soc_alarm.low_soc_alarm(param,df_bms,low_soc_bat_list,sn,df_OprtnSta)
+
+
+    return low_soc_bat_list
+mylog=log.Mylog('log_diag.txt','error')
+mylog.logcfg()
+
+
+try:  
+    low_soc_bat_list=Low_Soc_Alarm()
+    low_soc_bat_list.to_excel('low_soc_bat_list.xlsx')
+except Exception as e:
+    print(repr(e))
+    mylog.logopt(e)

+ 1 - 1
LIB/MIDDLE/SaftyCenter/diagfault/SC_SamplingSafty.py

@@ -31,7 +31,7 @@ class SamplingSafty:
         #--------------该电池的所有当前故障-------------
 
         VoltageNum=['单体电压'+str(i) for i in range(1,param.CellVoltNums+1)]#单体电压替换cellvolt_
-        CellVoltage=bms_info[VoltageNum]
+        CellVoltage=bms_info[VoltageNum]/1000
         CellMaxVoltage=CellVoltage.max(axis=1)
         CellMinVoltage=CellVoltage.min(axis=1)
         InVMaxBatNo=CellVoltage[CellVoltage>=param.CellOVlmt].dropna(axis=0,how='all',inplace=False)

+ 38 - 44
LIB/MIDDLE/SaftyCenter/diagfault/main.py

@@ -6,12 +6,13 @@ from LIB.BACKEND import DBManager, Log
 from sqlalchemy import create_engine
 import time, datetime
 from apscheduler.schedulers.blocking import BlockingScheduler
-from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload
+from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload as DBDownload
 from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import log
 from pandas.core.frame import DataFrame
 import datacompy
 from LIB.MIDDLE.SaftyCenter.Common import FeiShuData
-from LIB.MIDDLE.SaftyCenter.SaftyCenter.Common import QX_BatteryParam
+from LIB.MIDDLE.SaftyCenter.Common import QX_BatteryParam
+from LIB.MIDDLE.SaftyCenter.Common import DBDownload as DBDw
 
 #...................................电池包电芯安全诊断函数......................................................................................................................
 def diag_cal():
@@ -44,8 +45,7 @@ def diag_cal():
             print('SN:{},未找到对应电池类型!!!'.format(sn))
             continue
             # sys.exit()
-        param=QX_BatteryParam.BatteryInfo(celltype) 
-        print(sn)    
+        param=QX_BatteryParam.BatteryInfo(celltype)   
         #读取原始数据库数据........................................................................................................................................................
         dbManager = DBManager.DBManager()
         df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
@@ -68,19 +68,19 @@ def diag_cal():
 
         #电池诊断................................................................................................................................................................
         CellFltInfo=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
+        df_Diag_Ram = df_Diag_Ram.drop_duplicates(subset=['product_id','code','start_time','Batpos','info'],keep='first')#sn之外的故障
         df_Diag_Ram_sn = df_Diag_Ram.loc[df_Diag_Ram['product_id']==sn]#历史故障
         df_Diag_Ram_sn_else = pd.concat([df_Diag_Ram,df_Diag_Ram_sn,df_Diag_Ram_sn]).drop_duplicates(subset=['product_id','code','start_time','Batpos','info'],keep=False)#sn之外的故障
         CellFltInfo = df_Diag_Ram_sn.drop('Batpos',axis=1)
-        df_Diag_Ram_fix = df_Diag_Ram.loc[df_Diag_Ram['Batpos'] == 1]
-        df_Diag_Ram_unfix = df_Diag_Ram.loc[df_Diag_Ram['Batpos'] == 0]
+        df_Diag_Ram_add = pd.DataFrame()
+        df_Diag_Ram_Update_change = pd.DataFrame()
         if not df_bms.empty:
             df_Diag_Batdiag_update_xq=SamplingSafty.main(sn,param,df_bms,CellFltInfo)#学琦计算故障   
             BatDiag=CBMSBatDiag.BatDiag(sn,celltype,df_bms, df_soh, df_uniform, CellFltInfo)#鹏飞计算
             df_Diag_Batdiag_update=BatDiag.diag() 
-            df_Diag_Cal_Update_add = pd.concat([CellFltInfo,df_Diag_Batdiag_update_xq,df_Diag_Batdiag_update])#重新计算的该SN下的故障
+            df_Diag_Cal_Update_add = pd.concat([df_Diag_Batdiag_update_xq,df_Diag_Batdiag_update])#重新计算的该SN下的故障
             df_Diag_Cal_Update_temp = df_Diag_Cal_Update_add.drop_duplicates(subset=['product_id','start_time','end_time','code','info'], keep='first', inplace=False, ignore_index=False)#去除相同故障
             df_Diag_cal_early_unfix = pd.DataFrame()
-            df_sn_car_fix = pd.DataFrame()
             df_Diag_Cal_finish = pd.DataFrame()
             df_Diag_cal_early_fix = pd.DataFrame()
             if not df_Diag_Cal_Update_temp.empty:
@@ -91,14 +91,13 @@ def diag_cal():
                 df_Diag_Cal_finish['Batpos'] = 1
                 df_Diag_Cal_new['Batpos'] = 0
                 df_feishu_sta = df_read_Yunw.loc[(df_read_Yunw['product_id'] == sn)]#飞书中该sn车辆状态
-                if df_feishu_sta.empty:
+                if df_feishu_sta.empty:#飞书中没有该sn记录故障的新增
                     df_Diag_cal_early_unfix = df_Diag_Cal_new#如果为新出故障,则直接记录在df_diag_frame中
                 else:
-                    df_Diag_cal_later = df_Diag_Cal_new.loc[df_Diag_Cal_new['start_time'] > max(df_feishu_sta['start_time'])]#故障表中故障时间晚于飞书记录时间
+                    df_Diag_cal_later = df_Diag_Cal_new.loc[pd.to_datetime(df_Diag_Cal_new['start_time']) > max(pd.to_datetime(df_feishu_sta['start_time']))]#故障表中故障时间晚于飞书记录时间的新增
                     df_Diag_cal_early = pd.concat([df_Diag_Cal_new,df_Diag_cal_later,df_Diag_cal_later]).drop_duplicates(subset=['product_id','code','start_time'],keep=False)#故障表中故障时间早于飞书记录时间
-                    df_feishu_sta_latest = df_feishu_sta.loc[df_feishu_sta['start_time'] == max(df_feishu_sta['start_time'])]#飞书中该SN下的最新故障
+                    df_feishu_sta_latest = df_feishu_sta.loc[pd.to_datetime(df_feishu_sta['start_time']) == max(pd.to_datetime(df_feishu_sta['start_time']))]#飞书中该SN下的最新故障
                     df_feishu_diag_unfix = (df_feishu_sta_latest['advice'] == '需正常返仓') | (df_feishu_sta_latest['advice'] == '需紧急返仓')
-                    df_sn_car_unfix = pd.DataFrame()
                     if any(df_feishu_diag_unfix):
                         df_Diag_cal_early_unfix = df_Diag_Cal_new
                     else:
@@ -107,30 +106,20 @@ def diag_cal():
                 if not df_Diag_cal_early_fix.empty:
                     df_Diag_cal_early_fix['Batpos'] = 1
             df_Diag_Ram_Update = pd.concat([df_Diag_cal_early_unfix,df_Diag_cal_early_fix,df_Diag_Cal_finish])
-            df_Diag_Ram_Update.sort_values(by = ['start_time'], axis = 0, ascending=True,inplace=True)#对故障信息按照时间进行排序
-            df_temp5 = pd.concat([df_Diag_Ram_Update,df_Diag_Ram_sn_else])
-            df_Diag_Ram_sum = df_temp5.drop_duplicates(subset=['product_id','start_time','end_time','code','info'], keep='first', inplace=False, ignore_index=False)#去除相同故障
-            df_tempnum = df_Diag_Ram_sum.groupby(['product_id']).size()#获取每个sn的故障总数
-            col1 = df_tempnum[df_tempnum>1].reset_index()[['product_id']]#多故障sn号
-            col2 = df_tempnum[df_tempnum==1].reset_index()[['product_id']]#单故障sn号
-            df_temp1 = pd.DataFrame()
-            if not col1.empty:
-                for item in col1['product_id']:
-                    temp_data = df_Diag_Ram_sum.loc[df_Diag_Ram_sum['product_id'] == item]
-                    temp_data.sort_values(by = ['start_time'], axis = 0, ascending=True,inplace=True)#对故障信息按照时间进行排序
-                    df_temp1 = df_temp1.append(temp_data)
-            df_temp2 = pd.merge(col2,df_Diag_Ram_sum,on=["product_id"])#单故障码数据筛选
-            df_temp3 = pd.concat([df_temp1,df_temp2])#多故障及单故障合并
-            df_temp4 = df_temp3.reset_index(drop=True)
-            df_Diag_Ram = df_temp4
-            df_Diag_Ram_fix = df_Diag_Ram.loc[df_Diag_Ram['Batpos'] == 1]
-            df_Diag_Ram_unfix = df_Diag_Ram.loc[df_Diag_Ram['Batpos'] == 0]
-        if len(df_Diag_Ram) > 0:#历史及现有故障
-            df_Diag_Ram.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\result.csv',index=False,encoding='GB18030')
-        if len(df_Diag_Ram_fix) > 0:#故障车辆已返仓
-            df_Diag_Ram_fix.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\result_fix.csv',index=False,encoding='GB18030')
-        if len(df_Diag_Ram_unfix) > 0:#故障车辆未返仓
-            df_Diag_Ram_unfix.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problemm\result_unfix.csv',index=False,encoding='GB18030')
+            df_Diag_Ram_Update['start_time'] = pd.to_dateime(df_Diag_Ram_Update['start_time'])
+            df_Diag_Ram_Update.sort_values(by = ['start_time'], axis = 0, ascending=True,inplace=True)#该sn下当次诊断的故障状态
+            df_Diag_Ram_add = pd.concat([df_Diag_Ram_Update,df_Diag_Ram_sn,df_Diag_Ram_sn]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
+            df_Diag_Ram_Update_old = pd.concat([df_Diag_Ram_Update,df_Diag_Ram_add,df_Diag_Ram_add]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
+            df_Diag_Ram_Update_change = pd.concat([df_Diag_Ram_Update_old,df_Diag_Ram_sn,df_Diag_Ram_sn]).drop_duplicates(subset=['start_time','code','Batpos'],keep=False)#此次判断中新增故障
+            df_Diag_Ram_sav = df_Diag_Ram_Update.loc[df_Diag_Ram_Update['Batpos'] == 0]
+            df_Diag_Ram = pd.concat([df_Diag_Ram_sn_else,df_Diag_Ram_sav])
+
+        if len(df_Diag_Ram_sav) > 0:#历史及现有故障
+            df_Diag_Ram.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\04故障诊断\01Screen_Problem\result.csv',index=False,encoding='GB18030')
+        if len(df_Diag_Ram_add) > 0:#新增故障
+            df_Diag_Ram_add.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\04故障诊断\01Screen_Problem\result_add.csv',index=False,encoding='GB18030')
+        if len(df_Diag_Ram_Update_change) > 0:#更改故障
+            df_Diag_Ram_Update_change.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\04故障诊断\01Screen_Problem\result_change.csv',index=False,encoding='GB18030')
         end=time.time()
         print(end-start)
 
@@ -138,7 +127,7 @@ def diag_cal():
 if __name__ == "__main__":
     global SNnums
     
-    excelpath=r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\sn-20210903.xlsx'
+    excelpath=r'D:\Work\Code_write\data_analyze_platform\USER\lzx\01算法开发\04故障诊断\01Screen_Problem\sn-20210903.xlsx'
     SNdata_6060 = pd.read_excel(excelpath, sheet_name='科易6060')
     SNdata_6040 = pd.read_excel(excelpath, sheet_name='科易6040')
     SNdata_4840 = pd.read_excel(excelpath, sheet_name='科易4840')
@@ -158,13 +147,18 @@ if __name__ == "__main__":
     mylog=log.Mylog('log_diag.txt','error')
     mylog.logcfg()
     #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................
-    result=pd.read_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\result.csv',encoding='gbk')
-    
-    # df_Diag_Ram=result[result['end_time']=='0000-00-00 00:00:00']
-    df_Diag_Ram=result#[result['Batpos'] == 0]#将故障依然存在的赋值
-    print('----------------输入--------')
-    print(df_Diag_Ram)
-    print('-------计算中-----------')
+    host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
+    port=3306
+    db='safety_platform'
+    user='qx_read'
+    password='Qx@123456'
+    mode=2
+    tablename2='all_fault_info'
+    DBRead = DBDw.DBDownload(host, port, db, user, password,mode)
+    with DBRead as DBRead:
+        df_Diag_Ram = DBRead.getdata('start_time','end_time','product_id','code','level','info','advice','Batpos',tablename=tablename2,factory='骑享',sn='',timename='',st='',sp='')
+    # result=pd.read_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\result.csv',encoding='gbk')
+
     #定时任务.......................................................................................................................................................................
     scheduler = BlockingScheduler()
     scheduler.add_job(diag_cal, 'interval', seconds=300, id='diag_job')

+ 24 - 0
LIB/MIDDLE/SaftyCenter/log.py

@@ -0,0 +1,24 @@
+import logging
+import traceback
+
+class Mylog:
+
+    def __init__(self,log_name,log_level):
+        self.name=log_name
+        self.level=log_level
+    
+    def logcfg(self):
+        if len(self.level) > 0:
+            if self.level == 'debug':
+                Level=logging.DEBUG
+            elif self.level == 'info':
+                Level=logging.INFO
+            elif self.level == 'warning':
+                Level=logging.WARNING
+            else:
+                Level=logging.ERROR
+        logging.basicConfig(filename=self.name, level=Level,format='%(asctime)s - %(levelname)s - %(message)s')
+
+    def logopt(self,*info):
+        logging.error(info)
+        logging.error(traceback.format_exc())

BIN
Low_Soc_Alarm.xlsx


BIN
df_file.xlsx