commit a42c074c16efa80fa3f62c9fb0b788bd243eed46 Author: leon Date: Sun Jun 21 17:13:18 2026 +0800 提交现有代码 diff --git a/.gitignore b/.gitignore new file mode 100755 index 0000000..6e478d8 --- /dev/null +++ b/.gitignore @@ -0,0 +1,15 @@ +# Ignore files +**/.DS_Store +**/__pycache__ +/.idea +/logFile +/logFile/* +/dataFile +/dataFile/* +/build +/dist +/env +/myenv +/datas +*.db +.vscode \ No newline at end of file diff --git a/Manager/history_manager.py b/Manager/history_manager.py new file mode 100644 index 0000000..eef8f67 --- /dev/null +++ b/Manager/history_manager.py @@ -0,0 +1,78 @@ +from models import History, Session +import json +import uuid +from datetime import datetime +class HistoryManager: + def __init__(self, parent=None): + super().__init__() + + def create(self, info): + data = { + "id": str(uuid.uuid4()), + "info": json.dumps(info), + "datetime": datetime.now() + } + print("create history:", data) + ok, res = Session.addByClass(History, data) + if ok: + return str(res["id"]) + else: + print("create history failed:", res) + return "" + + def update(self, id, info): + + data = {"info": info} + ok,res = Session.updateById(History, id, data) + return ok + + def delete(self, id): + if isinstance(id, str): + ok,res = Session.deleteById(History, id) + return ok + else: + ok,res = Session.deleteByIds(History, id) + return ok + + def getInfoByDatetime(self, date_time_str): + ok,res = Session.queryByDatetime(History, date_time_str) + if ok: + return res + else: + return [] + + def getTrend(self, duration): + ok,res = Session.queryByTimestampRange(History, duration) + if ok: + return res + else: + return [] + + def getDateTimes(self,date_str, hour_str): + ok,res = Session.queryByDateHour(History, date_str, hour_str) + if ok: + return res + else: + return [] + + def getInfos(self, ids): + ok,res = Session.queryByIds(History, ids) + if ok: + return res + else: + return [] + + def getInfo(self, id = "all"): + if id == "all": + ok,res = Session.queryByAll(History) + if ok: + return res + else: + return [] + else: + ok,res = Session.queryById(History, id) + if ok: + return res + else: + return None +historyManager = HistoryManager() \ No newline at end of file diff --git a/Manager/product_manager.py b/Manager/product_manager.py new file mode 100644 index 0000000..142b69c --- /dev/null +++ b/Manager/product_manager.py @@ -0,0 +1,51 @@ +from models import Product, Session +import uuid +class ProductManager: + def __init__(self, parent=None): + super().__init__() + + def create(self, info): + data = { + "id": str(uuid.uuid4()), + "info": info + } + ok, res = Session.addByClass(Product, data) + if ok: + return str(res["id"]) + return "" + + def update(self, id, info): + + data = {"info": info} + ok,res = Session.updateById(Product, id, data) + return ok + + def delete(self, id): + if isinstance(id, str): + ok,res = Session.deleteById(Product, id) + return ok + else: + ok,res = Session.deleteByIds(Product, id) + return ok + + def getInfos(self, ids): + ok,res = Session.queryByIds(Product, ids) + if ok: + return res + else: + return [] + + def getInfo(self, id = "all"): + if id == "all": + ok,res = Session.queryByAll(Product) + if ok: + return res + else: + return [] + else: + ok,res = Session.queryById(Product, id) + if ok: + return res + else: + return None +productManager = ProductManager() diff --git a/Psyunew3.py b/Psyunew3.py new file mode 100644 index 0000000..29fae5a --- /dev/null +++ b/Psyunew3.py @@ -0,0 +1,637 @@ +# -- coding: utf-8 -- +import platform +from datetime import datetime +import random +from ctypes import * + +if 'Windows' in platform.system(): + if "32bit" in platform.architecture(): + Psyuunew=windll.LoadLibrary('Syunew3D.dll') + else: + Psyuunew=windll.LoadLibrary('Syunew3D_x64.dll') +else: + if "32bit" in platform.architecture(): + Psyuunew=windll.LoadLibrary('libPsyunew3.so') + else: + Psyuunew=cdll.LoadLibrary('libPsyunew3_arm8.so') + +##�����İ汾 +NT_GetIDVersion=Psyuunew.NT_GetIDVersion +NT_GetIDVersion.argtypes=(c_void_p,c_char_p) +NT_GetIDVersion.restypes=(c_int) + + +##��ȡ������չ�汾 +NT_GetVersionEx=Psyuunew.NT_GetVersionEx +NT_GetVersionEx.argtypes=(c_void_p,c_char_p) +NT_GetVersionEx.restypes=(c_int) + + +##�㷨���� +sWrite_2Ex=Psyuunew.sWrite_2Ex +sWrite_2Ex.argtypes=(c_ulong ,c_void_p,c_char_p) +sWrite_2Ex.restypes=(c_int) + +sWriteEx=Psyuunew.sWriteEx +sWriteEx.argtypes=(c_ulong ,c_void_p,c_char_p) +sWriteEx.restypes=(c_int) + +sRead=Psyuunew.sRead +sRead.argtypes=(c_void_p,c_char_p) +sRead.restypes=(c_int) + +sWrite_2=Psyuunew.sWrite +sWrite_2.argtypes=(c_ulong ,c_char_p) +sWrite_2.restypes=(c_int) + +sWrite_2=Psyuunew.sWrite_2 +Psyuunew.argtypes=(c_ulong ,c_char_p) +sWrite_2.restypes=(c_int) +##�㷨���� + +##дһ���ֽڵ��������� +YWrite=Psyuunew.YWrite +YWrite.argtypes=(c_byte ,c_short,c_char_p ,c_char_p,c_char_p ) +YWrite.restypes=(c_int) + +##�Ӽ������ж�ȡһ����?? +YRead=Psyuunew.YRead +YRead.argtypes=(c_void_p,c_short,c_char_p ,c_char_p,c_char_p ) +YRead.restypes=(c_int) + +##дһ���ֽڵ��������� +YWriteEx=Psyuunew.YWriteEx +YWriteEx.argtypes=(c_void_p,c_short,c_short,c_char_p,c_char_p,c_char_p ) +YWriteEx.restypes=(c_int) + +##�Ӽ������ж�ȡһ����?? +YReadEx=Psyuunew.YReadEx +YReadEx.argtypes=(c_void_p,c_short,c_short,c_char_p,c_char_p,c_char_p ) +YReadEx.restypes=(c_int) + +##����ָ���ļ�������ʹ����ͨ�㷨һ?? +FindPort_2=Psyuunew.FindPort_2 +FindPort_2.argtypes=(c_int ,c_ulong ,c_ulong ,c_char_p) +FindPort_2.restypes=(c_int) + +##���Ҽ���?? +FindPort=Psyuunew.FindPort +FindPort.argtypes=(c_int ,c_char_p) +FindPort.restypes=(c_int) + +##��ȡ����ID +GetID=Psyuunew.GetID +GetID.argtypes=(c_void_p,c_void_p,c_char_p) +GetID.restypes=(c_int) + +##�Ӽ������ж��ַ�?? +YReadString=Psyuunew.YReadString +YReadString.argtypes=(c_char_p ,c_short,c_int ,c_char_p ,c_char_p,c_char_p) +YReadString.restypes=(c_int) + +##д�ַ�����������?? +YWriteString=Psyuunew.YWriteString +YWriteString.argtypes=(c_char_p,c_short,c_char_p ,c_char_p,c_char_p ) +YWriteString.restypes=(c_int) + +##����д��?? +SetWritePassword=Psyuunew.SetWritePassword +SetWritePassword.argtypes=(c_char_p ,c_char_p,c_char_p ,c_char_p,c_char_p) +SetWritePassword.restypes=(c_int) + +##���ö���?? +SetReadPassword=Psyuunew.SetReadPassword +SetReadPassword.argtypes=(c_char_p ,c_char_p,c_char_p ,c_char_p,c_char_p) +SetReadPassword.restypes=(c_int) + +##������ǿ�㷨��Կһ +SetCal_2=Psyuunew.SetCal_2 +SetCal_2.argtypes=(c_char_p,c_char_p) +SetCal_2.restypes=(c_int) + +##ʹ����ǿ�㷨һ���ַ������м��� +EncString=Psyuunew.EncString +EncString.argtypes=(c_char_p,c_char_p,c_char_p) +EncString.restypes=(c_int) + +##ʹ����ǿ�㷨һ�Զ��������ݽ��м��� +Cal=Psyuunew.Cal +Cal.argtypes=(c_void_p,c_void_p,c_char_p) +Cal.restypes=(c_int) + +##������ǿ�㷨��Կ?? +SetCal_New=Psyuunew.SetCal_New +SetCal_New.argtypes=(c_char_p,c_char_p) +SetCal_New.restypes=(c_int) + +##ʹ����ǿ�㷨�����ַ������м�?? +Cal_New=Psyuunew.Cal_New +Cal_New.argtypes=(c_void_p,c_void_p,c_char_p) +Cal_New.restypes=(c_int) + +##ʹ����ǿ�㷨�����ַ������м�?? +EncString_New=Psyuunew.EncString_New +EncString_New.argtypes=(c_char_p,c_char_p,c_char_p) +EncString_New.restypes=(c_int) + +##�������ij������� +GetProduceDate=Psyuunew.GetProduceDate +GetProduceDate.argtypes=(c_char_p,c_char_p) +GetProduceDate.restypes=(c_int) + +##����ID���� +SetID=Psyuunew.SetID +SetID.argtypes=(c_char_p ,c_char_p) +SetID.restypes=(c_int) + +##������ͨ��?? +SetCal=Psyuunew.SetCal +SetCal.argtypes=(c_char_p ,c_char_p,c_char_p ,c_char_p,c_char_p) +SetCal.restypes=(c_int) + +##��������ת������ +##SnToProduceDate=Psyuunew.SnToProduceDate +##SnToProduceDate.argtypes=(c_char_p ,c_char_p ) +##SnToProduceDate.restypes=(c_void) + +##ʹ����ǿ�㷨���ַ������н���ʹ������ +##StrDec=Psyuunew.StrDec +##StrDec.argtypes=(c_char_p,c_char_p,c_char_p) +##StrDec.restypes=(c_void ) +## +##StrEnc=Psyuunew.StrEnc +##StrEnc.argtypes=(c_char_p,c_char_p,c_char_p) +##StrEnc.restypes=(c_void) +## +##EnCode=Psyuunew.EnCode +##EnCode.argtypes=(c_void_p ,c_void_p , c_char_p ) +##EnCode.restypes=(c_void) +## +##DeCode=Psyuunew.DeCode +##DeCode.argtypes=(c_void_p , c_void_p , c_char_p ) +##DeCode.restypes=(c_void) +##ʹ����ǿ�㷨���ַ������н���ʹ������) + + +##ʹ����ǿ�㷨�Զ��������ݽ��м���ʹ������) +##DecBySoft=Psyuunew.DecBySoft +##DecBySoft.argtypes=(c_void_p, c_void_p ) + +##EncBySoft=Psyuunew.EncBySoft +##EncBySoft.argtypes=(c_void_p , c_void_p ) +##ʹ����ǿ�㷨�Զ��������ݽ��м���ʹ������) + +##�ַ��������������ݵ�ת�� +##HexStringToc_byteArray=Psyuunew.HexStringToc_byteArray +##HexStringToc_byteArray.argtypes=(c_char_p ,c_void_p) +##HexStringToc_byteArray.restypes=(c_void) +## +##ByteArrayToHexString=Psyuunew.ByteArrayToHexString +##ByteArrayToHexString.argtypes=(c_void_p,c_char_p ,c_int ) +##ByteArrayToHexString.restypes=(c_void) +##�ַ��������������ݵ�ת�� + + ##��ʼ��������,ע�⣬��ʼ���������е�����??����д����Ҳ??0000000-00000000����ǿ�㷨���ᱻ��ʼ?? +ReSet=Psyuunew.ReSet +ReSet.argtypes=[c_char_p] +ReSet.restypes=(c_int) + +##���º���ֻ���ڴ�U�̵�?? +##�����Ƿ���ʾU�̲����̷�����Ϊ��ʾ����Ϊ����ʾ +SetHidOnly=Psyuunew.SetHidOnly +SetHidOnly.argtypes=( c_bool,c_char_p) +SetHidOnly.restypes=(c_int) + +##����U�̲���Ϊֻ��״̬�� +SetUReadOnly=Psyuunew.SetUReadOnly +SetUReadOnly.argtypes=[c_char_p] +SetUReadOnly.restypes=(c_int) +##���Ϻ���ֻ���ڴ�U�̵�?? + +##���º���ֻ֧������оƬ��?? +##����SM2��Կ?? +YT_GenKeyPair=Psyuunew.YT_GenKeyPair +YT_GenKeyPair.argtypes=(c_char_p ,c_char_p,c_char_p,c_char_p) +YT_GenKeyPair.restypes=(c_int) + +##����Pin?? +YtSetPin=Psyuunew.YtSetPin +YtSetPin.argtypes=(c_char_p,c_char_p,c_char_p ) +YtSetPin.restypes=(c_int) + +##����SM2��Կ�Լ����� +Set_SM2_KeyPair=Psyuunew.Set_SM2_KeyPair +Set_SM2_KeyPair.argtypes=(c_char_p,c_char_p,c_char_p,c_char_p,c_char_p ) +Set_SM2_KeyPair.restypes=(c_int) + +##���ؼ������Ĺ�Կ +Get_SM2_PubKey=Psyuunew.Get_SM2_PubKey +Get_SM2_PubKey.argtypes=(c_char_p,c_char_p,c_char_p,c_char_p) +Get_SM2_PubKey.restypes=(c_int) + +##�Զ��������ݽ���SM2���� +SM2_EncBuf=Psyuunew.SM2_EncBuf +SM2_EncBuf.argtypes=(c_void_p,c_void_p,c_int ,c_char_p) +SM2_EncBuf.restypes=(c_int) + +##�Զ��������ݽ���SM2���� +SM2_DecBuf=Psyuunew.SM2_DecBuf +SM2_DecBuf.argtypes=(c_void_p,c_void_p,c_int ,c_char_p ,c_char_p) +SM2_DecBuf.restypes=(c_int) + +##���ַ�������SM2���� +SM2_EncString=Psyuunew. SM2_EncString +SM2_EncString.argtypes=(c_char_p,c_char_p,c_char_p) +SM2_EncString.restypes=(c_int) + +##���ַ�������SM2���� +SM2_DecString=Psyuunew.SM2_DecString +SM2_DecString.argtypes=(c_char_p,c_char_p,c_char_p ,c_char_p) +SM2_DecString.restypes=(c_int) + +##����Ϣ����SM2ǩ�� +YtSign=Psyuunew.YtSign +YtSign.argtypes=(c_char_p , c_char_p ,c_char_p ,c_char_p) +YtSign.restypes=(c_int) + +##��SM2ǩ��������ǩ +YtVerfiy=Psyuunew.YtVerfiy +YtVerfiy.argtypes=(c_char_p,c_char_p,c_char_p,c_char_p,c_char_p,c_void_p,c_char_p) +YtVerfiy.restypes=(c_int) + +##SM2�㷨��ʼ��(ʹ������) +IniSM2=Psyuunew.IniSM2 +IniSM2.restypes=(c_int) + +##���ַ�������SM2����(ʹ������) +SM2EncString=Psyuunew.SM2EncString +SM2EncString.argtypes=(c_char_p,c_char_p,c_char_p ,c_char_p) +SM2EncString.restypes=(c_int) + + +##���ַ�������SM2���ܣ�ʹ�������� +SM2DecString=Psyuunew.SM2DecString +SM2DecString.argtypes=(c_char_p,c_char_p,c_char_p) +SM2DecString.restypes=(c_int) + +##����Ϣ����SM2ǩ����ʹ�������� +SM2Sign=Psyuunew.SM2Sign +SM2Sign.argtypes=(c_char_p , c_char_p ,c_int ,c_char_p ,c_char_p) +SM2Sign.restypes=(c_int) + +##��SM2ǩ��������ǩ��ʹ�������� +SM2Verfiy=Psyuunew.SM2Verfiy +SM2Verfiy.argtypes=(c_char_p,c_char_p,c_char_p,c_char_p,c_char_p) +SM2Verfiy.restypes=(c_int) + +##�ͷ�SM2�㷨(ʹ������) +ReleaseSM2=Psyuunew.ReleaseSM2 + +##��������Ӳ��оƬΨһID +GetChipID=Psyuunew.GetChipID +GetChipID.argtypes=(c_char_p,c_char_p) +GetChipID.restypes=(c_int) +##���Ϻ���ֻ֧������оƬ���� + +##���º���ֻ֧��D8 +CheckDate=Psyuunew.CheckDate +CheckDate.argtypes=(c_char_p,c_char_p) +CheckDate.restypes=(c_int) +##���Ϻ���ֻ֧��D8 + + +if 'Linux' in platform.system(): + CloseUsbHandle=Psyuunew.CloseUsbHandle + CloseUsbHandle.argtype=c_char_p + CloseUsbHandle.restypes=(c_void_p) + +def CheckDateEx(Path): + dt=datetime.now() + nowDate=dt.strftime( '%Y/%m/%d/%H/%M/%S' ) + ret=CheckDate(nowDate.encode('utf-8'),Path) + return ret + +def HexStringToByteArrayEx(InString): + + mylen=len(InString) + array_data={} + in_data=c_byte + temp='' + for n in range(0,mylen,2): + temp=InString[n:2+n] + temp='0x'.encode()+temp + in_data=int(temp,16) + array_data[n/2]=(in_data) + return array_data + +def StringToByteArray(InString): + + mylen=len(InString) + array_data={} + in_data=c_int + temp='' + for n in range(0,mylen): + temp=InString[n:1+n] + in_data=ord(temp) + array_data[n]=(in_data) + array_data[n+1]=0 + return array_data + +def ByteArrayToString(InBuf): + arrBytes = bytearray() + for n in range(0,len(InBuf)): + arrBytes.append(InBuf[n]) + return arrBytes.decode() + + +def ByteArrayToHexString(in_data,inlen): + OutString='' + temp='' + for n in range(0,inlen): + temp='%02X' % in_data[n] + OutString=OutString+temp + return OutString + +def EnCode(InData,Key,pos): + KeyBuf=HexStringToByteArrayEx(Key) + OutData=EncBySoft(InData,KeyBuf,pos) + return OutData + +def DeCode(InData,Key,pos): + KeyBuf=HexStringToByteArrayEx(Key) + OutData=DecBySoft(InData,KeyBuf,pos) + return OutData + + +def EncBySoft(inb, KeyBuf,pos): + bufArray=c_uint32*16 + buf=bufArray + + temp_string='' + cnDelta = 2654435769 + _sum = 0 + a = 0 + b = 0 + c = 0 + d = 0 + + for n in range(0,4): + a = (KeyBuf[n] << (n * 8)) | a + b = (KeyBuf[n + 4] << (n * 8)) | b + c = (KeyBuf[n + 4 + 4] << (n * 8)) | c + d = (KeyBuf[n + 4 + 4 + 4] << (n * 8)) | d + y = 0 + z = 0 + + for n in range(0,4): + temp = (inb[pos +n]) + y = (temp << (n * 8)) | y + temp = (inb[pos +n + 4]) + z = (temp << (n * 8)) | z + + n = 32 + while n > 0: + _sum = (cnDelta + _sum) & 0xffffffff + temp=(z << 4) & 0xffffffff + temp=(temp+a)& 0xffffffff + temp_1= (z + _sum) & 0xffffffff + temp_2=((z >> 5) + b)& 0xffffffff + temp=temp ^ temp_1 ^ temp_2 + y = (y+ temp)& 0xffffffff + temp=(y << 4)& 0xffffffff + temp=(temp + c)& 0xffffffff + temp_1=(y + _sum)& 0xffffffff + temp_2=((y >> 5) + d)& 0xffffffff + temp=temp ^ temp_1 ^ temp_2 + z=(z+temp)& 0xffffffff + n = n - 1 + + outb={} + for n in range(0,4): + outb [n]= (y >> (n) * 8) & 255 + outb[n + 4] = (z >> (n) * 8) & 255 + + return outb + +def DecBySoft(inb, KeyBuf,pos): + bufArray=c_uint32*16 + buf=bufArray + temp_string='' + cnDelta = 2654435769 + _sum = 0xC6EF3720 + a = 0 + b = 0 + c = 0 + d = 0 + for n in range(0,4): + a = (KeyBuf[n] << (n * 8)) | a + b = (KeyBuf[n + 4] << (n * 8)) | b + c = (KeyBuf[n + 4 + 4] << (n * 8)) | c + d = (KeyBuf[n + 4 + 4 + 4] << (n * 8)) | d + y = 0 + z = 0 + for n in range(0,4): + temp = (inb[pos +n]) + y = (temp << (n * 8)) | y + temp = inb[pos +n + 4] + z = (temp << (n * 8)) | z + + n = 32 + while n > 0: + temp=(y << 4) + temp= ( temp+ c) & 0xffffffff + temp_1=(y + _sum)& 0xffffffff + temp_2=((y >> 5) + d)& 0xffffffff + temp= temp ^ temp_1 ^ temp_2 + z=(z-temp) & 0xffffffff + #z -= ((y << 4) + c) ^ (y + _sum) ^ ((y >> 5) + d) + temp=(z << 4)& 0xffffffff + temp=(temp+a)& 0xffffffff + temp_1=(z + _sum)& 0xffffffff + temp_2=((z >> 5) + b)& 0xffffffff + temp= temp ^ temp_1 ^ temp_2 + y = (y -temp)& 0xffffffff + _sum = (_sum -cnDelta)& 0xffffffff + n = n - 1 + + outb={} + for n in range(0,4): + outb[n] = (y >> (n) * 8) & 255 + outb[n + 4] = (z >> (n) * 8) & 255 + + return outb + +def StrDec(InString,Key): + OutBuf={} + mylen=len(InString)/2 + KeyBuf=HexStringToByteArrayEx(Key) + InBuf=HexStringToByteArrayEx(InString) + for n in range(0,(mylen-8)+1,8): + tempBuf=DecBySoft(InBuf,KeyBuf,n) + for i in range(0,8): + OutBuf[i+ n] = tempBuf[i] + if mylen>8: + n=len(OutBuf)-1 + for n in range(len(OutBuf),mylen): + OutBuf[n]=(InBuf[n]) + return ByteArrayToString(OutBuf) + + +def StrEnc(InString,Key): + OutBuf={} + InBuf={} + temp_Buf=InString.encode('utf-8') + mylen=len(InString)+1 + for n in range(0,mylen-1): + InBuf[n]=temp_Buf[n] + InBuf[n+1]=(0) + if mylen<8: + for n in range(mylen,8): + InBuf[n]=(0) + mylen=8 + + KeyBuf=HexStringToByteArrayEx(Key) + for n in range(0,(mylen-8)+1,8): + tempBuf=EncBySoft(InBuf,KeyBuf,n) + + for i in range(0,8): + OutBuf[i+ n] = tempBuf[i] + if mylen>8: + n=len(OutBuf)-1 + for n in range(len(OutBuf),mylen-1): + OutBuf[n]=(InBuf[n]) + OutBuf[n+1]=0 + OutString=ByteArrayToHexString(OutBuf,mylen) + return OutString + +#ʹ����ǿ�㷨������Ƿ���ڶ�Ӧ�ļ����� +def CheckKeyByEncstring_New(): + DevicePath=create_string_buffer(260) + EncInString=["22128","29496","13134","26562","17476","14629","21328","21094","17506","6324","13549","19640","6132","30309","12958","12107","32068","16221","3328","8272","18876","7005","21705","21913","9191","16070","29910","30362","23917","23706", \ +"23584","7780","27929","14460","18370","32167","2263","22702","11509","7352","24493","22545","17170","15750","29640","22569","11669","23974","5234","4886","17943","22600","30738","3482","1619","10303","30261","26903","4641","18941", \ +"24965","21905","24955","15763","459","9129","2686","10420","11761","30367","11106","6321","1537","5720","29824","25725","19748","24916","21076","11946","25510","24245","14199","1897","24817","28734","1699","11917","19853","9298", \ +"7346","30087","32037","10225","31390","16746","2181","22716","3970","11496","26515","30456","8855","19026","11100","30597","23862","1436","22537","30182","29914","9813","24292","17982","29982","29105","14423","10060","10684","27778", \ +"7661","5236","10380","15674","25678","14263","31625","11754","30021","31672","27341","20037","27069","15801","26259","13724","17343","8092","4404","25826","18549","31201","26921","18601","31273","28077","4879","23330","12870","5825", \ +"17308","26144","23380","23934","18862","25876","19198","26854","14396","1810","15375","12445","12385","20681","26735","12003","19288","24205","17194","12954","9338","18001","21097","20805","833","6565","10615","30981","9542","1979", \ +"700","8862","10310","8038","31171","9072","5144","12567","25910","8062","1207","20705","20704","7017","29757","30837","6058","11892","9445","18727","7582","21632","11016","28135","10726","24592","5920","7496","24780","3142", \ +"16326","15227","23994","12003","11190","7251","27962","2634","7114","25921","26359","16253","13562","3929","10170","24605","19041","2379","11116","8301","18233","31080","18201","10574","14557","8102","747","2628","30918","22419", \ +"5162","19310","30349","14948","30528","8080","8687","24808","10682","13836","29891","17812","1088","11492","7429","18040","13467","8889","18125","18247","22454","26829","1623","29522","13213","21764","25083","8077","4471","13278", \ +"31796","19591","14223","23166","23965","18548","847","22693","24304","28966","9025","19126","13061","5647","28943","19379","4312","31295","27524","1853","32128","30315","20617","27542","13883","15076","22312","31650","14945","12699", \ +"2443","16609","30059","35","16124","23926","2294","10669","13797","15906","14009","20748","19920","27720","27278","6833","24936","32745","25714","11951","16501","12713","637","23224","18915","3272","10984","21533","9659","16680", \ +"22030","6610","7975","5453","14442","30310","7793","30806","3222","8718","17155","13319","32073","1178","7528","16066","12129","6012","2377","11657","27604","26567","10095","17917","27072","14381","30661","12385","14429","17151", \ +"4951","18838","18692","7216","1612","5408","6450","13138","18926","20254","31869","30101","24233","7765","1699","4047","1543","26148","5499","20590","7345","14480","31487","10631","5232","26681","18252","21193","3632","14946", \ +"12954","2953","5114","14572","10050","31926","29431","9307","27584","15077","13684","1487","27821","26694","15576","24841","9923","30380","31662","1647","12508","2441","20385","1279","26098","30702","31609","15453","12064","28301", \ +"16674","3787","28062","12730","7077","13099","1225","32613","6444","9982","1047","4385","21761","16486","28964","15903","4495","24614","12716","15666","29277","17312","5510","1740","22041","30422","174","22269","20619","26217", \ +"13628","20346","17564","4508","15723","14740","7769","23632","30101","26683","11496","265","13878","14852","7319","8934","7653","15136","4301","32683","31580","26463","24085","16827","22392","3126","25625","29205","7984","19125", \ +"1956","2654","28063","14735","19615","9941","30208","10005","4116","22622","3500","31546","25132","5756","22044","14736","52","20814","1773","9032"] + EncOutString=["CFA5FE777DC2BC7B","44CC739E5A0AD0FD","F899C13ED9551C22","88C9F8A3851867D3","4A8582E27FD9DC67","3B0C85F79C0477BC","0D9F86729D31401A","FF5F672C74542BE6","A52B65507CDA6FB8","904B249FB4829280","F0E7DDF11001ABC9","D484E5FFC963D8BF","EF6A770444EAF909","57F04E9FE1BA3FD8","E44C761A27CEAA6D","214011B85BC93CD5","ECC2BE37F0A7CC70","5F67939A60A91731","158C60D62860EB3E","F9AF015E39140554","C541B957DA510B57","09141D471E3DA317","80A9C10B7A936931","86D48EB13DE8FAFD","F6E091745A514880","AD9C6FBE675DDE34","90624792C9C13206","7D2FA019033BB15A","E607F1BEBB969730","EF883C1C09EBDFB6", \ +"FC5DA492706FFD97","DC157A70336D5485","C5791500EED7D0C0","1419486CB24F7B84","A85B373EB338BEF0","3BFDC24552DC6869","83292730338867C4","F959B81CEB38B033","D32A108599F419CF","25703A615B3D233B","48F59647DC4DAD4A","1CBE22F872F94D59","E66481AF23455FFE","A2CF111CCF0F90F6","9E060B68D27F6471","7AA7F68A20781E04","D42B9534E35545FF","690BB1D3A234DE47","47537F5307511545","DF1A23A328DFD8EE","2BB952E497AFCB23","6248AB81BD46DB9C","87C45B0FAA3D56DD","5D520D1F1F3E3E0F","4DADC23C11C3185A","EE76D9CFB5E08DBC","43479B4306255A11","AB7EDF7F7ED985D5","1F9FF1783CAD8D7C","B33177574A51197F", \ +"C45DFD5FACF18277","D121ED1B1AC249F0","12BE5DA679D438C8","079CEAF5B39D1D95","302F2CB2A81D910A","BFC705D80BA6C0FE","E6CD51636DBE8B43","DF73BEA5B3E6F6B4","29E061BE84B23983","8D0AD2EC2B4C3E45","D2B2E7171157C05A","42B17459DCA82D2A","4DB04A2BC1611CF0","8D8711A7F88A70E0","66EF0ABDEB85D042","A5E94512F4312EBF","43CFDEA0A91C56E5","1072ACFB9083C31B","92D165AAA37BA96A","6C4465C69014DDA2","E036BAFB250DE30F","57D033AED1D43A4F","E5CF1891A692551E","2E0355E70EFFEAD2","AAB895BF3AA49F77","900501A8C0E13A26","E5C5D718EC6EC3F6","4BD7B10B427396FF","F15CF42D89326540","78B02DA8170C8443", \ +"99A3B6F619246817","E60AD2D10D1BFB9F","0AA6472EB1ED0398","0FBA22CE10EF7D82","452AAD535259F35A","FFA23D9FB431A7C0","C70024F4209BAE45","85D989DB6CF42AD7","8424212FA20F79D3","A4B2F0295C9E2C14","F4C6D62B04DFE42E","2805A5076B02A255","E03DEA5FFC819E4D","59CA29FFE5D74BBC","283DE843AC609309","66336BABC6D1AF46","32E4165BECA69384","AEC1E80263D8AE17","4E4ABDF72E70E74D","0BBCB346796A6CA2","AF0A7400F81B830A","62D5BDE717D7B0A3","8C4CC1648999341C","2CB2F8F5222C69D9","56AE1FC179F4691B","59289EE6B5C3B83C","45A05BF94122DB41","6906AC9FDD7A86E6","538A090961E32024","9ED08BF21EDAE659", \ +"23FA7CB4DCD962E3","AE4B851DD388F3F3","31DFAFB538203227","D4873E475DCB2680","F15E3D7A5D0D8661","FEF3F1068A1A3F59","D6CE5E515A548187","24C1833FDDF0ED0E","FC11B0427132349C","613125596918DC71","951E0EA36138FAD0","DC6381115DD5756D","CB91A0DF6779B8EC","10A918DF8F64D2F1","A674613187569D01","91325980C90DD689","CAF4B366DF8CE0B6","6889904712A8E2C6","0D0590FB59A81048","3B22E50E4EB48221","B3EDDC7EE7193FDE","05D3476144AF62D9","9BF24495C71E6E41","1D3A890B7189998F","F84C9EE56F21B876","5C0E670EE62E2FBD","2A4CA6B86053A516","D23BBCA50E6D5D09","80A13D68D3B70F4F","203D4A48B7C70202", \ +"77E0987A7B28B412","34F36FC1E9B0606D","1B0BE2DB2539A0DE","895F297219E37293","A8D7A559994175D6","59641FC84612978A","700909835367DF77","F608040DC74A9FF6","5C0E5E35C94CBF5F","4C0043522D604D16","7A86FC128C76A915","C87D2F5265A94CDE","34040B31C730EB23","E7FB69C6278BB0DC","B09704DDF15382DA","02BBE2A95107D57C","D39B53C38768A568","6D53FB813B47A275","A751CE9C9764BB2A","B9AD286B56B458A8","2A73038247ADC81F","8A060D49361023E6","229BB5537061FA9A","BF85B927F833C03F","AB659C6F90DB3298","54986E55FFFCF30D","2FCBCA07195CBDAF","6C23E5D9C833CEC7","87960A6AE63E40F9","1625BFDCA435AF13", \ +"A55D176ECD240C8B","BD767A4AFF96AEE8","A77EE39253159DBC","128B3B9F4302E146","8E16856B0DDDB26B","6E9BF08A6D4445E2","2BF2F072D52EBE27","27766687DAF0BF45","3433B8B274F09F0C","8C5C3F62D6E11590","3E46EE812B4970C7","632C333541734408","0012F0B2CCE761ED","1FAB4F6EDE9A78DB","409B816B06FBEA35","EEF3573529E71273","56142C951DE0413D","638C8067BC04F392","3889C5C7A265B4DA","E559D3BBEC7A2B63","23194DBA569246DF","6DE909486E941630","1B7D29EAD296DADB","AFB2AF61178DE9B8","C61F36E21227BB42","B31449DA15C80F04","10972FFA7E67B455","5330EA69E7D3A155","AD27CD3E46823C6E","5772DC6624F32F23", \ +"BF082996855F63F5","D2551216B1C603C6","EFF32D646ABA5146","02BBE2A95107D57C","CBA8FA2488C533B5","E0A537B87CAD31CD","AADD1E5FF433636E","9C98BD75A894FC0D","175380D96D8D8CD5","BEAAECCCB107E1F8","5E321A336C1FCBED","0188B4178DF24EB3","D25EA4DF43DD6764","9963912DFFAE722C","88B95C5E4CDE4FF4","2ACFE1F463AB51A2","009EC39124093800","0933A8B8BDCA2E8E","0D55116B8F16D439","081FC397E397F8AC","3644824A83E55D15","C31F059D831DAAC8","0E6C5C7EECE235AE","50C728DFB4F61EED","6DEAF0A51E012A4D","4B596B1202024EB5","4E1B622D806AA501","72B029C7E8ED56D0","75AE04BDCD0C2725","DAFB1CEFAA153E63", \ +"EDB5323B0FA5DB31","139571B5C7882C92","FC0DDE34CCCA3F0C","7D1AA46CF45C447A","403F9923D38D226F","A156C02D6F6F4207","8F79738E1BCC23C0","451A1BFACF5BB149","3821949F5313B79B","B9CB8EBF2F926126","2F810B7DF2633641","F78F2CB7A1AC9523","A58218472A04FF35","5704AFC3B93FF453","EFF880522BC6BD9E","B685BD4C6C89628F","3D8D0F53B4ECD8AB","F7CE1DDCC28EBED9","E43EA06D350B30F8","2B88F3071183876E","0B95364DF5C511FE","094F20C85FC24442","8A082748B960F95F","FDE800482BCA74F8","F5CC40ECBDDCE36F","8B0DBE932255D388","6AC85BD4ECC8098A","7B43801212B2B86A","6272E527CC554AE2","95E2E29E08606D25", \ +"87E2E7DA0E6F9AE3","CDDE9D43DBA1BF42","BCB875714C5AFAD9","BF7F37D2645FEDCC","7B37BA7CF4F093F0","7745EA1B14895D8B","C4B053E766EC59BB","076BB5368EE833B7","B58B097A27FBA13D","A6818FCE74444637","234F6DE36D6135AA","F93AE4F64BBA85E1","D21FE040FC1888E6","B50B725265A4A7CB","EDA8DF048844C858","1458CCE4024A052B","65007F73EF0A1718","A57EC3B1E334594B","9113F9BFAEFA6E7D","AA0EA6C445E52B3C","F3FBA318A7297B9C","E8490F72F3D8AC76","CD0FA677E9CE6A35","ECC1F6C9B146817C","39242405BB9B2700","C022AFDADE92011E","13615B49BA3D42BD","FAC07B329F92E015","840C5ED65E1C2943","9FEDFD3A5B1DA38A", \ +"103F3C4346D712A9","FEC3B993D813ED7C","AF34A0BB7D8311D9","E567003B7736CBE5","CC24FDC91CC3B171","9867302B77C34B5B","10C5D3C6C4C719CD","242F1C616B952B15","CA7AC8234847771D","9205F2924CD88B5C","A38D8D146AE535E8","1FD2391909782870","BA6FD84CDC102987","1AFD6B63AE15B67E","0D3BC910BBFC9B52","9083C6C34958520D","9E886BFC12811906","D4C84BE2F7D46074","C48FE01EFA774C39","FB1A47C32E096C29","FDACFE5CB437B623","0CC41514F23ED235","F4461F7DD038257E","A4388F569A7C1B1C","697958B6A44F851D","FE68C4AD30C86E0E","A7186EC6934FB1D7","7C6670A45BC56F0D","FDA13B04E135BF4E","5F221638ACCF5DAC", \ +"9C8F1363482C94B5","87258236D81D9249","CA5D09A2C27FC74D","2362836E7C1211B9","F4A336888C9BC45E","99D81FF4843943B7","6FB827A91EC49978","9F0412ADD1D92A13","5E724AF5814995E0","22DE60F466548005","77667222093A59A2","798B13392C4C24E2","C358A9B283EF0DF7","0DE4B91F77C7D618","522444A42E59B8AB","8EF221BE3B2F8E3E","7181256EA8F75A2F","150EA219B59D70EA","D4C3A80C677176A2","52E08DB0CF299389","02013194C02DBA9A","BA5429F47E799D31","7CDCF3E536C66440","D0BAA8794B309154","BAB890923277A1EA","13A6B82D3FA71D09","2BD153E8A526F676","34040B31C730EB23","6B22CBEA4A410FE5","A8458516ABC45DBA", \ +"E81EE8C134B968B2","BC2CC4A150DE04C2","7812FF04B85A0C02","6762F05A5FEAC0DE","A4C3123B5670AC75","5B57DF03D5CE335E","95DDCDD2AD0C5F24","E1CDF0F64B66CB76","6708D59CE2FF1209","4AF87F93678AB8D9","E7AD2A33F3BD4F81","BE6EBD332452F958","4BBD10FFB4B4113C","DC003D51289DFF49","E5C5D718EC6EC3F6","BE18BE0D1828CCF5","E44A223E0A6380A3","668A96491651C53D","0F3727D20C2346C4","2AA5CD407E87181C","40A117959B085BCC","F31198993FB89E8A","132929E135F89166","F9C11ACA479F5068","7CED6A15DD8D9529","7CB7C3365121F74E","41FAEE8E4A53AE08","A8963556D144B270","9B19366829DBDB22","BA35A66DC4BDB244", \ +"B9AD286B56B458A8","2AC45F24B58BFFC7","FAAFE7EE4E6CC01E","364F41D6770DCF02","4819615DF2E9CC29","15BB09D7F88B49A9","DA53CF9F484A3570","54B773DA9F015D4A","8AB3EE7B6619B6C2","A8DA3E47A4BA4CA8","BAB49DDAC3A69156","BC191C2CA8BF5975","E376A2D85CE00C21","3E2BC5930D1C0D4F","9A09FE24EFC4582C","D106091F6EF52490","778DBF924BA90F86","C2EC35025452FD24","440D3D9B7F0E0C20","C0CC9D99D7730C1C","44776AB346C92FA3","E843CBED39E97F16","BB619EC199FC7CAA","56BFF900DBAC2155","EB8CE67FAF6A5367","D22D153C81F1C09A","BA4B3B4D13BA5338","F0BCC8CEF2AFF2EB","679643306314041D","2D292F09220E42EE", \ +"6B4384ADFFDB004D","15AB139CA5E53C27","584A5913FF4956C8","839D03B45D600DD1","F862DFA5B7036CBB","B7CBD3C01149B2D2","F17A6C580BF2A657","57A40D5C82B1F7E6","86FF1931FA492C04","9F68C19F5C24D378","96BFDC80FC149357","44CF3E2E354543DB","67D8037745144962","DA697D967D554EC1","B800E40A74BEBD76","D76341895B0A7C1D","17F78023F95ABE7D","32BB976FEBAA679A","E0480BC8E1F2BB91","62F91E5FEF7D0E19","A3F9F804055F6857","C440629BE0B15A14","67BF4891DEE7B076","D85FD3A5362F835B","93F7A3E37304D8E3","C3E20946707AFEA3","4FD0A7DDDEEDEB3E","53D76C52982AABFE","91E267D10D9081FA","279BDF8AD992269C", \ +"36961542D35B63BF","A7B4543875346904","639EF19414884E2E","3667B72DDAB06025","D7E34290727FFFE6","D0468C8FA6A0A6A8","92703AEDB72A596F","5E4ACD3930EF4B3A","BE6EBD332452F958","A11B3A058D1FB0B4","A4B2F0295C9E2C14","CE670A8014BEF5BE","2E2E226E4D88C306","36B132A93312B5DF","F3692EA7F5083300","1B6B1D413E4DDA71","91F6AEAC50C2831B","9D160A344B2B606D","8404818915AAD0F0","2E7E821DE5047DDC","FE01D0F6DBEC604B","12BCFD63FA5B4F9B","3ADB05AE89D39FE4","889CD8B4C4D808FB","3CB70121DCEAB136","F7790077AC6E13B8","7E68B4C8A6F3DB3C","92D851C715FAF55A","4EA7A87A5033E61B","83F287E4B4D9DFB0", \ +"0194ACCAE701866E","49744AA812C00A2E","A4D1BA14748B8B61","8C79C0FCBB553842","544BD977BC00748D","058934FB3BDC293E","E03D223F33E7B2C3","7A1356B6D0757D30","91DC5D7AD773DFD5","206A0E0C7FEA3F59","870DBCBA19884B29","99430CC28ACD7323","06C04ACD41D93448","1A6DB4C18117FCAF","1B1A6BA91F147E7A","DD662B39B87B1740","346723FEAD39B143","65D43D985876041E","3799A75F167F0004","04D2588FC395289E"] +#@NoUseNewKeyEx return 1 #���û��ʹ��������ܣ�ֱ�ӷ���1 +#@NoSupNewKeyEx return 2 #��������֧��������ܣ�ֱ�ӷ���2 + myrnd=random.randint(1, (500 -1 )) + mylen = len(EncInString[myrnd])+1 + if mylen < 8 : + mylen = 8 + outstring = create_string_buffer((mylen* 2+1))#//ע�⣬����Ҫ??һ�����ȣ����ڴ������ѧ���� + for n in range(0,255): + ret=FindPort(n,DevicePath) + if ret!=0: + CloseDongle(DevicePath) + return ret + ret=EncString_New(EncInString[myrnd].encode('utf-8'), outstring,DevicePath) + if outstring.value.decode('utf-8').lower()==EncOutString[myrnd].lower(): + CloseDongle(DevicePath) + return 0 + CloseDongle(DevicePath) + return -92 + + +#ʹ����ǿ�㷨һ�����������������������Ч�ط�ֹ���� +def CheckKeyByEncstring(): +#�Ƽ����ܷ�����������������������������㣬ͬʱ�ڳ����ж�ʹ�ô�����ͬ���ļ������㣬Ȼ����бȽ��жϡ� + DevicePath=create_string_buffer(260) +#@NoUseKeyEx return 1 #���û��ʹ��������ܣ�ֱ�ӷ���1 + InString=('%X%X' % ((int)(random.uniform(0, 24174836)),(int)(random.uniform(0, 24174836)))) + for n in range(0,255): + ret=FindPort(n,DevicePath) + if ret!=0 : + CloseDongle(DevicePath) + return ret + if Sub_CheckKeyByEncstring(InString,DevicePath)==0: + CloseDongle(DevicePath) + return 0 + return -92 + +def Sub_CheckKeyByEncstring(InString,DevicePath): +#//'ʹ����ǿ�㷨���ַ������м��� + nlen = len(InString) + 1 + if nlen < 8 : + nlen = 8 + outstring = create_string_buffer((nlen * 2+1))#//ע�⣬����Ҫ��1һ�����ȣ����ڴ������ѧ��?? + outstring = StrEnc(InString, 'D31B2D928A62607E3E6ACD1165843D8E'.encode('utf-8')) + outstring_2 = create_string_buffer((nlen * 2+1))#//ע�⣬����Ҫ��1һ�����ȣ����ڴ������ѧ��?? + EncString(InString.encode('utf-8'),outstring_2,DevicePath) + if outstring.lower()==outstring_2.value.decode('utf-8').lower():#//�ȽϽ���Ƿ���� + ret=0 + else: + ret=-92 + return ret + +#//ʹ�ô����ȵķ�����ָ���ĵ�ַ��ȡ�ַ��� +def ReadStringEx(addr,DevicePath): + InArray=c_ubyte*1 + blen = InArray(0) +#//�ȴӵ�ַ0������ǰд����ַ����ij�?? + ret = YReadEx(blen, addr, 1, 'BD1B62F3'.encode('utf-8'), '7621A856'.encode('utf-8'), DevicePath) + if ret != 0 : + return '' + outstring=create_string_buffer(blen[0]) +#�ٴӵ�ַ1��ȡָ�����ȵ��ַ��� + ret = YReadString(outstring, addr+1, blen[0], 'BD1B62F3'.encode('utf-8'), '7621A856'.encode('utf-8'), DevicePath) + if ret!=0: + return '' + return outstring.value + + +#//ʹ�ôӴ�������ȡ��Ӧ���ݵķ�ʽ����Ƿ����ָ���ļ����� +def CheckKeyByReadEprom(): + DevicePath=create_string_buffer(260) +#@NoUseCode_data return 1 #���û��ʹ��������ܣ�ֱ�ӷ���1 + for n in range(0,255): + ret=FindPort(n,DevicePath) + if ret!=0 : + CloseDongle(DevicePath) + return ret + outstring=ReadStringEx(0,DevicePath) + if(outstring=='TGX-08-0003#B1084CF7-A763-49DA-A7B5-6E88F7D131B8#241324F9-8563-424D-9E98-8DDAFE105EA5'.encode('utf-8')): + CloseDongle(DevicePath) + return 0 + CloseDongle(DevicePath) + return -92 + +#ʹ����ͨ�㷨һ����ָ���ļ����� +def CheckKeyByFindort_2(): + DevicePath=create_string_buffer(260) + ret=FindPort_2(0, 1, -500811555, DevicePath) + CloseDongle(DevicePath) + return ret + +def CloseDongle(DevicePath): + if 'Linux' in platform.system(): + CloseUsbHandle(DevicePath)#�ر�USB�豸 + diff --git a/Psyunew3.pyc b/Psyunew3.pyc new file mode 100644 index 0000000..f89d47a Binary files /dev/null and b/Psyunew3.pyc differ diff --git a/README.md b/README.md new file mode 100644 index 0000000..264a84f --- /dev/null +++ b/README.md @@ -0,0 +1,2 @@ +# TGX_PYSERVER + diff --git a/config.json b/config.json new file mode 100644 index 0000000..043c6c5 --- /dev/null +++ b/config.json @@ -0,0 +1,8 @@ +{ + "sn" : "", + "calc_server": { + "ip": "101.200.29.204", + "port": 5000, + "protocol": "mqtt" + } +} diff --git a/config.py b/config.py new file mode 100644 index 0000000..ffc7dc1 --- /dev/null +++ b/config.py @@ -0,0 +1,13 @@ +LOCALBORKER = "127.0.0.1" +LOCALPORT = 1883 +DEVICEBORKER = "127.0.0.1" +DEVICEPORT = 1883 +BORKER = "123.57.81.127" +PORT = 1888 +USER = "test" +PWD = "test" +DEVICENAME = 'TGX-08' +YSMODE = False +COREECTMODE = True + + diff --git a/cpy_http_client.py b/cpy_http_client.py new file mode 100755 index 0000000..3060316 --- /dev/null +++ b/cpy_http_client.py @@ -0,0 +1,396 @@ +# The `HttpClient` class is a Python class that handles HTTP requests, sends commands to a server, +# processes server responses, and calculates various results based on received data. +from PySide6.QtCore import QObject, Signal, Slot, QTimer +from datetime import datetime +import random +import gzip +from io import BytesIO +from Manager.history_manager import historyManager +import json +from config import * +import requests +import logging + +# 配置日志记录 +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger('HttpClient') +class HttpClient(QObject): + reciveData = Signal(dict) + + def __init__(self, address, port, connection_name, psk=None): + super().__init__() + self.name = connection_name + self.init = 1 + self.file_name = "" + self.device_name = "" + self.address = address + self.port = port + self.tempIndex = 0 + self.base_url = f"http://{address}:{port}/api" + logger.info(f"HttpClient initialized with base URL: {self.base_url}") + + # 定时器 + self.debug_timer = QTimer(self) + self.debug_timer.setInterval(5000) + self.debug_timer.timeout.connect(self.debug_info) + if YSMODE: + self.debug_timer.start() + logger.info("Debug mode enabled") + + def debug_info(self): + if self.tempIndex == 0: + self.device_name = "scanner1" + self.tempIndex = 1 + elif self.tempIndex == 1: + self.device_name = "scanner2" + self.tempIndex = 0 + self.reciveData.emit({ + "device": self.device_name, + "WtOSC": [random.uniform(0.80,0.82), 0.799, 0.819, 0.837, 0.83, 0.815, 0.812, 0.81], + "WtINS": [random.uniform(10.498,10.520), 10.525, 10.512, 10.488, 10.485, 10.486, 10.471, 10.468], + "WtISC": [0.973, 0.965, 0.94, 0.924, 0.935, 0.957, 0.968, 0.97], + "WtALL": [12.271, 12.288, 12.271, 12.249, 12.25, 12.258, 12.25, 12.248], + "AngOSC": [0, 90, 346.656], + "AngINS": [270, 0, 253.233], + "AngISC": [90, 315, 144.457], + "AngALL": [270, 0, 226.029], + "DmCORE": [random.uniform(14,14.3), 14.2, 14.1], + "DmALL": [random.uniform(37,37.2), 37.1, 37.2], + "EccentricityINS": random.uniform(0.30, 0.60), + "EccentricityOSC": 4.540023894862595, + "EccentricityISC": 5.035971223021576, + "Volatility": [0.021, 0.021, 0.028], + "EllipticityDmALL": -0.0, + "EllipticityDmCORE": -0.0, + "AvgALL": 12.260625000000001, + "AvgISC": 0.954, "AvgOSC": 0.81525, "AvgINS": 10.491625, "MinALL": 12.248, "MinISC": 0.924, "MinOSC": 0.799, "MinINS": 10.468, + "ConcentricityALL": 99.83697424193022, "ConcentricityISC": 97.4169741697417, "ConcentricityOSC": 97.67726161369193, "ConcentricityINS": 99.72848092221216, + "EccentricALL": 0.020000000000000462, "EccentricISC": 0.024499999999999966, "EccentricOSC": 0.01899999999999996, "EccentricINS": 0.028500000000000192, + "EccentricityALL": 0.32552083333334086,"EdgesA": [41.53, 42.66, 54.93, 56.28, 75.88, 76.58, 86.97, 88.19], "EdgesB": [39.36, 40.58, 52.69, 53.92, 73.64, 74.23, 84.77, 86.01]}) + + # self.reciveData.emit({ + # "device": self.device_name, + # "WtOSC": [0.83, 0.86, 0.84, 0.81, 0.88, 0.92, 0.87, 0.79], + # "WtISC": [0.72, 0.76, 1.03, 0.96, 1.05, 0.84, 0.77, 0.89], + # "WtINS": [5.96, 6.57, 11.33, 13.54, 11.27, 6.47, 5.88, 7.62], + # "WtALL": [7.50, 8.20, 13.20, 15.32, 13.21, 8.22, 7.52, 9.30], + # "AngOSC": [303.75, 225.00, 21.88], + # "AngINS": [202.50, 135.00, 274.23], + # "AngISC": [247.50, 78.75, 301.21], + # "AngALL": [247.50, 135.00, 286.10], + # "DmCORE": [16.69, 14.54, 18.85], + # "DmALL": [37.21, 39.16, 35.27], + # "DmCOREDeviation": 1, + # "DmALLDeviation": 2, + # "AvgINS": 8.82, + # "AvgOSC": 0.95, + # "AvgISC": 0.88, + # "AvgALL": 9.63, + # "MinISC": 0.95, + # "MinOSC": 0.81, + # "MinINS": 5.88, + # "MinALL": 7.50, + # "EccentricINS": 0.95, + # "EccentricOSC": 2.03, + # "EccentricISC": 3.22, + # "EccentricALL": 8.82, + # "EccentricityINS": 16.003, + # "EccentricityOSC": 21.126, + # "EccentricityISC": 43.283, + # "EccentricityALL": 43.283, + # "ConcentricityALL" : 21.25, + # "ConcentricityINS" : 21.25, + # "ConcentricityOSC" : 11.63, + # "ConcentricityISC" : 6.53, + # "ConcentricityDeviationALL": 21.25, + # "ConcentricityDeviationINS": 21.25, + # "ConcentricityDeviationOSC": 11.63, + # "ConcentricityDeviationISC": 6.53, + # "EllipticityDmCORE": 6.51, + # "EllipticityDmALL": 9.68, + # "Volatility": [0.290, 0.088, 0.314], + # "EdgesA": [41.53, 42.66, 54.93, 56.28, 75.88, 76.58, 86.97, 88.19], + # "EdgesB": [39.36, 40.58, 52.69, 53.92, 73.64, 74.23, 84.77, 86.01] + # }) + + def start_handshake(self): + # HTTP客户端不需要握手,可以直接发送请求 + logger.info(f"{self.name}: HTTP client ready to send requests to {self.address}:{self.port}") + + def check_server_status(self): + """检查服务器状态""" + try: + url = f"{self.base_url}/status" + response = requests.get(url, timeout=5) + if response.status_code == 200: + return response.json() + else: + logger.error(f"Failed to get server status, status code: {response.status_code}") + return None + except Exception as e: + logger.error(f"Error checking server status: {e}") + return None + + + @Slot() + def handle_timeout(self): + # HTTP客户端不需要重连,重试请求即可 + logger.info(f"{self.name}: HTTP request timeout, ready to retry") + + @Slot() + def udp_socket_connected(self): + # 兼容原有接口,HTTP客户端不需要UDP连接 + pass + + @Slot() + def readyRead(self): + # 兼容原有接口,HTTP客户端不需要监听接收数据 + pass + + def send_command(self, command, params=None): + """发送命令到服务器""" + try: + url = f"{self.base_url}/command" + data = {"command": command} + if params: + data.update(params) + + response = requests.post(url, json=data, timeout=10) + if response.status_code == 200: + logger.info(f"Command '{command}' sent successfully") + return response.json() + else: + logger.error(f"Failed to send command '{command}', status code: {response.status_code}") + return None + except Exception as e: + logger.error(f"Error sending command '{command}': {e}") + return None + + @Slot() + def handshake_timeout(self): + # HTTP客户端不需要处理握手超时 + pass + + @Slot(bytearray) + def write_data(self, data): + """发送二进制数据到服务器""" + try: + url = f"{self.base_url}/data" + files = {'file': ('binary_data', data, 'application/octet-stream')} + response = requests.post(url, files=files, timeout=10) + + if response.status_code == 200: + logger.info('Data sent successfully') + result = response.json() + if result: + self.reciveData.emit(self.calResult(json.dumps(result))) + return True + else: + logger.error(f"Failed to send data, status code: {response.status_code}") + return False + except Exception as e: + logger.error(f"Error sending data: {e}") + return False + + + def compress_file_with_params(self, file_content): + compressed_data = None + try: + # 使用BytesIO来创建一个可写的文件对象 + compressed_file = BytesIO() + with gzip.GzipFile(fileobj=compressed_file, mode='wb') as gzf: + gzf.write(file_content) + + # 读取压缩后的文件内容 + compressed_data = compressed_file.getvalue() + return compressed_data + except Exception as e: + logger.error(f'Error compressing file: {e}') + return None + + @Slot(int, bytearray,str, int) + def start_cal(self, motor_index, file_content, direction, row_count): + """开始计算,通过HTTP发送文件数据""" + logger.info(f"Starting calculation with motor_index: {motor_index}, direction: {direction}") + if direction == "": + return + + direction_value = 0 + if direction == "UP": + direction_value = 1 + elif direction == "DOWN": + direction_value = 2 + + current_time = datetime.now() + compress_file_content = self.compress_file_with_params(file_content) + if not compress_file_content: + logger.error("Failed to compress file content") + return + + self.device_name = f"scanner{motor_index}" + self.file_name = f'{current_time.strftime("%Y-%m-%d_%H_%M_%S_%f")[:-3]}_direction_{direction_value}_device{motor_index}.csv' + + try: + url = f"{self.base_url}/data" + + # 准备表单数据 + form_data = { + "init": str(self.init), + "device_id": str(motor_index), + "device_name": DEVICENAME, + "version": "2", + "offset": "0", + "scale": "1", + "file_type": "raw", + "compress": "gz", + "row_count": str(row_count), + "direction": direction + } + + # 准备文件数据 + files = { + 'file': (f'{self.file_name}.gz', compress_file_content, 'application/gzip') + } + + self.init = 0 + logger.info(f"Sending file: {self.file_name}.gz with size: {len(compress_file_content)} bytes") + + # 发送HTTP POST请求 + response = requests.post(url, data=form_data, files=files, timeout=30) + + if response.status_code == 200: + logger.info("Calculation request sent successfully") + try: + result = response.json() + if result: + # 添加设备名称到结果中 + result['device'] = self.device_name + # 计算额外的结果数据 + processed_result = self.calResult(json.dumps(result)) + self.reciveData.emit(processed_result) + except json.JSONDecodeError: + logger.error("Failed to parse server response as JSON") + else: + logger.error(f"Failed to send calculation request, status code: {response.status_code}") + logger.error(f"Response content: {response.text}") + + except Exception as e: + logger.error(f"Error sending calculation request: {e}") + + @Slot() + def set_init(self): + self.init = 1 + logger.info(f"=====set init==== {self.init}") + + def calResult(self, r_str): + """处理服务器返回的计算结果""" + try: + robj = json.loads(r_str) + + # 安全地获取结果中的数据,如果不存在则使用默认空列表 + DmALL = robj.get("DmALL", []) + DmCORE = robj.get("DmCORE", []) + WtOSC = robj.get("WtOSC", []) + WtINS = robj.get("WtINS", []) + WtISC = robj.get("WtISC", []) + WtALL = robj.get("WtALL", []) + + # 设置设备名称 + robj["device"] = self.device_name + + # 计算椭圆度 + if len(DmALL) >= 3: + robj["EllipticityDmALL"] = 2*abs(DmALL[1]-DmALL[2])/(DmALL[1] + DmALL[2]) if (DmALL[1] + DmALL[2]) != 0 else 0 + else: + robj["EllipticityDmALL"] = 0 + + if len(DmCORE) >= 3: + robj["EllipticityDmCORE"] = 2*abs(DmCORE[1]-DmCORE[2])/(DmCORE[1] + DmCORE[2]) if (DmCORE[1] + DmCORE[2]) != 0 else 0 + else: + robj["EllipticityDmCORE"] = 0 + + # 计算平均值 + robj["AvgALL"] = self.avg(WtALL) + robj["AvgISC"] = self.avg(WtISC) + robj["AvgOSC"] = self.avg(WtOSC) + robj["AvgINS"] = self.avg(WtINS) + + # 计算最小值 + if WtALL: + robj["MinALL"] = min(WtALL) + robj["ConcentricityALL"] = 200*min(WtALL)/(min(WtALL)+max(WtALL)) if (min(WtALL)+max(WtALL)) != 0 else 0 + robj["EccentricALL"] = (max(WtALL) - min(WtALL))/2 + robj["EccentricityALL"] = (max(WtALL) - min(WtALL))*100/max(WtALL) if max(WtALL) != 0 else 0 + else: + robj["MinALL"] = 0 + robj["ConcentricityALL"] = 0 + robj["EccentricALL"] = 0 + robj["EccentricityALL"] = 0 + + if WtISC: + robj["MinISC"] = min(WtISC) + robj["ConcentricityISC"] = 200*min(WtISC)/(min(WtISC)+max(WtISC)) if (min(WtISC)+max(WtISC)) != 0 else 0 + robj["EccentricISC"] = (max(WtISC) - min(WtISC))/2 + robj["EccentricityISC"] = (max(WtISC) - min(WtISC))*100/max(WtISC) if max(WtISC) != 0 else 0 + else: + robj["MinISC"] = 0 + robj["ConcentricityISC"] = 0 + robj["EccentricISC"] = 0 + robj["EccentricityISC"] = 0 + + if WtOSC: + robj["MinOSC"] = min(WtOSC) + robj["ConcentricityOSC"] = 200*min(WtOSC)/(min(WtOSC)+max(WtOSC)) if (min(WtOSC)+max(WtOSC)) != 0 else 0 + robj["EccentricOSC"] = (max(WtOSC) - min(WtOSC))/2 + robj["EccentricityOSC"] = (max(WtOSC) - min(WtOSC))*100/max(WtOSC) if max(WtOSC) != 0 else 0 + else: + robj["MinOSC"] = 0 + robj["ConcentricityOSC"] = 0 + robj["EccentricOSC"] = 0 + robj["EccentricityOSC"] = 0 + + if WtINS: + robj["MinINS"] = min(WtINS) + robj["ConcentricityINS"] = 200*min(WtINS)/(min(WtINS)+max(WtINS)) if (min(WtINS)+max(WtINS)) != 0 else 0 + robj["EccentricINS"] = (max(WtINS) - min(WtINS))/2 + robj["EccentricityINS"] = (max(WtINS) - min(WtINS))*100/max(WtINS) if max(WtINS) != 0 else 0 + else: + robj["MinINS"] = 0 + robj["ConcentricityINS"] = 0 + robj["EccentricINS"] = 0 + robj["EccentricityINS"] = 0 + + # 保存到历史记录 + try: + historyManager.create(robj) + except Exception as hist_error: + logger.error(f"Error saving to history: {hist_error}") + + return robj + except Exception as e: + logger.error(f"Error processing calculation result: {e}") + return {} + + def avg(self, data): + """计算平均值""" + if len(data) == 0: + return 0 + if len(data) == 1: + return data[0] + try: + mean_value = sum(data) / len(data) + return mean_value + except TypeError: + logger.error("Error calculating average: data contains non-numeric values") + return 0 + + @Slot(object) + def psk_required(self, auth): + # HTTP客户端不需要PSK认证 + pass + +# 为了保持向后兼容性,可以继续使用原类名 +CalcHttpClient = HttpClient + + + diff --git a/cpy_mqtt_client.py b/cpy_mqtt_client.py new file mode 100644 index 0000000..1832f4a --- /dev/null +++ b/cpy_mqtt_client.py @@ -0,0 +1,527 @@ +# The `CpyMqttClient` class is a Python class that handles MQTT requests, sends commands to a server, +# processes server responses, and calculates various results based on received data. +from PySide6.QtCore import QObject, Signal, Slot, QTimer, QUrl, QIODevice + +import os +import gzip +from io import BytesIO +from Manager.history_manager import historyManager +import json +from config import * +import logging +import struct +import base64 +import threading +import uuid +import copy +import time +import socket + +import paho.mqtt.client as mqtt +import ssl + +import pandas as pd + +# 配置日志记录 +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger('CpyMqttClient') + +class CpyMqttClient(QObject): + reciveData = Signal(dict) + + def __init__(self, address, port, dev_id, psk=None): + super().__init__() + self.dev_id = dev_id + self.init = 1 + self.file_name = "" + self.scanner_name = "" + self.address = address + self.port = port + self.tempIndex = 0 + + self.last_server_ack_time = 0 + + self.cal_queue = {} + + # 初始化MQTT客户端,通过SSL连接 + # 使用V2.0 API版本 + self.client = mqtt.Client(client_id=dev_id, callback_api_version=mqtt.CallbackAPIVersion.VERSION2) + # 设置连接回调 + self.client.on_connect = self.on_connect + self.client.on_message = self.on_message + self.client.on_disconnect = self.on_disconnect + # 设置用户名密码 + self.client.username_pw_set('cpy_tgx-08_controller', 'tgzz2026.') + # 配置SSL + logger.info("Configuring SSL for MQTT connection...") + # 使用默认系统CA证书 + self.client.tls_set(cert_reqs=ssl.CERT_NONE) + # 禁用证书验证,解决自签名证书问题 + self.client.tls_insecure_set(True) + # 开始循环 + #logger.info("Starting MQTT client loop...") + #self.client.loop_start() + + self.check_timer = QTimer(self) + self.check_timer.timeout.connect(self.check_mqtt_server) + self.check_timer.start(1000) + + thread = threading.Thread(target=self.main_loop) + thread.start() + + + + def cal_queue_lock(self): + if not hasattr(self, "_cal_queue_lock"): + self._cal_queue_lock = threading.Lock() + self._cal_queue_lock.acquire() + + def cal_queue_unlock(self): + try: + self._cal_queue_lock.release() + except: + pass + + def check_cal_queue(self): + """检查计算队列""" + if len(self.cal_queue) == 0: + return + logger.info(f"check cal queue: {len(self.cal_queue)} items in queue") + self.cal_queue_lock() + # 使用列表复制进行遍历,避免字典大小变化导致的错误 + for uid, data in list(self.cal_queue.items()): + if time.time() - data.get("time", 0) > 5: + logger.error(f"calculate response timeout: {uid}") + del self.cal_queue[uid] + self.cal_queue_unlock() + + def check_network_ready(self, host="cpycal.tgoim.com", port=8883): + try: + ip = socket.gethostbyname(host) + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(0.5) + result = sock.connect_ex((ip, port)) + sock.close() + print(result) + if result == 0: + return ip + return False + except Exception as e: + print(e) + return False + + def check_mqtt_server(self): + if self.status == "init": + ip = self.check_network_ready(host='localhost') + if ip: + logger.info("Connecting to MQTT broker at cpycal.tgoim.com:8883...") + self.check_timer.stop() + self.client.connect(ip, 8883, 10) + self.client.loop_start() + + + def main_loop(self): + """主循环""" + self.status = "init" + + while True: + print(self.status) + self.check_cal_queue() + + time.sleep(1) + if self.status == "init__": + if self.check_network_ready(): + # 连接到MQTT服务器 + logger.info("Connecting to MQTT broker at cpycal.tgoim.com:8883...") + self.client.connect('cpycal.tgoim.com', 8883, 10) + time.sleep(2) + else: + logger.info('network not ready...') + if self.status == "connected": + self.status = "checking" + self.check_server_status() + elif self.status == "available": + self.status = "registering" + self.register() + elif self.status == "checking": + if time.time() > self.check_server_status_time + 5: + self.status = "checking" + self.check_server_status() + elif self.status == "unavailable": + self.status = "checking" + self.check_server_status() + elif self.status == "registering": + if time.time() > self.register_time + 5: + self.status = "checking" + self.check_server_status() + elif self.status == "registered": + if time.time() > self.last_server_ack_time + 10: + self.status = "checking" + self.check_server_status() + + def on_disconnect(self, client, userdata, flags, rc, properties=None): + """断开连接回调 (V2.0 风格)""" + self.status = "disconnected" + logger.info(f"Disconnected from MQTT broker, return code: {rc}") + + def on_connect(self, client, userdata, flags, rc, properties=None): + """连接成功回调 (V2.0 风格)""" + if rc == 0: + logger.info("Connected to MQTT broker successfully") + self.status = "connected" + self.client.subscribe(f"v1/cpy/{self.dev_id}", qos=1) + else: + logger.error(f"Failed to connect to MQTT broker, return code: {rc}") + + def handle_calculate_response(self, result, uid): + """处理计算响应""" + if not result: + logger.error(f"Received calculate response with empty result: {result}") + return + try: + if not uid: + logger.error(f"Received calculate response with no 'uuid' field: {uid}") + return + self.cal_queue_lock() + _data = self.cal_queue.get(uid, None) + self.cal_queue_unlock() + if not _data: + logger.error(f"Received calculate response with no 'uuid' field: {uid}") + return + cal_data = copy.deepcopy(_data) #使用深拷贝 + self.cal_queue_lock() + del self.cal_queue[uid] #删除队列中的数据 + self.cal_queue_unlock() + + if cal_data.get("time", None): + logger.info(f"calculation costs time: {time.time() - cal_data.get('time', None)}") + + data_path = cal_data.get("data_path", None) + if not data_path: + logger.error(f"Received calculate response with no 'data_path' field: {data_path}") + return + info = cal_data.get("info", None) + if not info: + logger.error(f"Received calculate response with no 'info' field: {result}") + return + + # 保存设备名称和文件名 + scanner_id = info.get("scanner_id", None) + if not scanner_id: + logger.error(f"Received calculate response with no 'scanner_id' field: {result}") + return + + result['device'] = f"scanner{scanner_id}" + + # 计算额外的结果数据 + processed_result = self.calResult(json.dumps(result)) + # 保存结果到文件 + self.save_result(data_path, processed_result) + + # 发射结果信号 + self.emit_recive_data(processed_result) + except json.JSONDecodeError: + logger.error("Failed to parse server response as JSON") + + def handle_server_response(self, payload): + """处理服务器响应""" + cmd = payload.get("ack", None) + error = payload.get("error", None) + result = payload.get("result", None) + if not cmd or error is None or result is None: + logger.error(f"Received message with no 'ack' field: {payload}") + return + + if cmd == "status": + logger.info(f"Server status: {result}") + if error == 200: + self.status = "available" + else: + self.status = "unavailable" + elif cmd == 'register': + if error == 200: + self.status = "registered" + self.last_server_ack_time = time.time() + else: + self.status = "unavailable" + logger.info(f"Register status: {'success' if self.status == 'registered' else 'failed'}") + elif cmd == 'calculate': + if error == 200: + self.last_server_ack_time = time.time() + self.handle_calculate_response(result, payload.get("uuid", None)) + else: + logger.error(f"Received calculate response with error: {error}") + + def on_message(self, client, userdata, msg): + """接收消息回调 (V2.0 风格)""" + try: + payload = json.loads(msg.payload.decode()) + logger.info(f"Received message on topic {msg.topic}: {payload}") + self.handle_server_response(payload) + except json.JSONDecodeError: + logger.error(f"Failed to decode JSON from message on topic {msg.topic}") + + def send_command(self, payload): + """发送MQTT命令""" + topic = f"v1/cpy/server/1" + self.client.publish(topic, json.dumps(payload), qos=0) + + def register(self): + """注册设备到服务器""" + self.register_time = time.time() + payload = { + "cmd":"register", + "ver":1, + "dev_id": self.dev_id + } + self.send_command(payload) + + def check_server_status(self): + """检查服务器状态""" + self.check_server_status_time = time.time() + try: + payload = { + "cmd":"status", + "ver":1, + "dev_id": self.dev_id + } + self.send_command(payload) + logger.info(f"Sent status check command: {payload}") + except Exception as e: + logger.error(f"Error checking server status: {e}") + return None + + def calculate_data(self, info, data, data_path): + """计算数据""" + try: + info['uuid'] = str(uuid.uuid4()) + info['cmd'] = 'calculate' + info['ver'] = 1 + info['data'] = base64.b64encode(data).decode('utf-8') + self.cal_queue_lock() + self.cal_queue[info['uuid']] = { + "data_path" : data_path, + "info" : info, + "time" : time.time(), + } + self.cal_queue_unlock() + self.send_command(info) + except Exception as e: + logger.error(f"Error in calculate_data: {e}") + + def compress_file_with_name(self, csv_path: str): + compressed_data = None + try: + #使用pandas读取csv文件 + df = pd.read_csv(csv_path) + file_content = bytearray() + + # 遍历DataFrame中的每一行 + for index, row in df.iterrows(): + channel_A = row['CH1'] + channel_B = row['CH2'] + file_content.extend(struct.pack('= 3: + robj["EllipticityDmALL"] = 2*abs(DmALL[1]-DmALL[2])/(DmALL[1] + DmALL[2]) if (DmALL[1] + DmALL[2]) != 0 else 0 + else: + robj["EllipticityDmALL"] = 0 + + if len(DmCORE) >= 3: + robj["EllipticityDmCORE"] = 2*abs(DmCORE[1]-DmCORE[2])/(DmCORE[1] + DmCORE[2]) if (DmCORE[1] + DmCORE[2]) != 0 else 0 + else: + robj["EllipticityDmCORE"] = 0 + + # 计算平均值 + robj["AvgALL"] = self.avg(WtALL) + robj["AvgISC"] = self.avg(WtISC) + robj["AvgOSC"] = self.avg(WtOSC) + robj["AvgINS"] = self.avg(WtINS) + + # 计算最小值 + if WtALL: + robj["MinALL"] = min(WtALL) + robj["ConcentricityALL"] = 200*min(WtALL)/(min(WtALL)+max(WtALL)) if (min(WtALL)+max(WtALL)) != 0 else 0 + robj["EccentricALL"] = (max(WtALL) - min(WtALL))/2 + robj["EccentricityALL"] = (max(WtALL) - min(WtALL))*100/max(WtALL) if max(WtALL) != 0 else 0 + else: + robj["MinALL"] = 0 + robj["ConcentricityALL"] = 0 + robj["EccentricALL"] = 0 + robj["EccentricityALL"] = 0 + + if WtISC: + robj["MinISC"] = min(WtISC) + robj["ConcentricityISC"] = 200*min(WtISC)/(min(WtISC)+max(WtISC)) if (min(WtISC)+max(WtISC)) != 0 else 0 + robj["EccentricISC"] = (max(WtISC) - min(WtISC))/2 + robj["EccentricityISC"] = (max(WtISC) - min(WtISC))*100/max(WtISC) if max(WtISC) != 0 else 0 + else: + robj["MinISC"] = 0 + robj["ConcentricityISC"] = 0 + robj["EccentricISC"] = 0 + robj["EccentricityISC"] = 0 + + if WtOSC: + robj["MinOSC"] = min(WtOSC) + robj["ConcentricityOSC"] = 200*min(WtOSC)/(min(WtOSC)+max(WtOSC)) if (min(WtOSC)+max(WtOSC)) != 0 else 0 + robj["EccentricOSC"] = (max(WtOSC) - min(WtOSC))/2 + robj["EccentricityOSC"] = (max(WtOSC) - min(WtOSC))*100/max(WtOSC) if max(WtOSC) != 0 else 0 + else: + robj["MinOSC"] = 0 + robj["ConcentricityOSC"] = 0 + robj["EccentricOSC"] = 0 + robj["EccentricityOSC"] = 0 + + if WtINS: + robj["MinINS"] = min(WtINS) + robj["ConcentricityINS"] = 200*min(WtINS)/(min(WtINS)+max(WtINS)) if (min(WtINS)+max(WtINS)) != 0 else 0 + robj["EccentricINS"] = (max(WtINS) - min(WtINS))/2 + robj["EccentricityINS"] = (max(WtINS) - min(WtINS))*100/max(WtINS) if max(WtINS) != 0 else 0 + else: + robj["MinINS"] = 0 + robj["ConcentricityINS"] = 0 + robj["EccentricINS"] = 0 + robj["EccentricityINS"] = 0 + + # 保存到历史记录 + try: + historyManager.create(robj) + except Exception as hist_error: + logger.error(f"Error saving to history: {hist_error}") + + return robj + except Exception as e: + logger.error(f"Error processing calculation result: {e}") + return {} + + def avg(self, data): + """计算平均值""" + if len(data) == 0: + return 0 + if len(data) == 1: + return data[0] + try: + mean_value = sum(data) / len(data) + return mean_value + except TypeError: + logger.error("Error calculating average: data contains non-numeric values") + return 0 + + @Slot(object) + def psk_required(self, auth): + # HTTP客户端不需要PSK认证 + pass + + + + diff --git a/cpy_mqtt_client.py.save b/cpy_mqtt_client.py.save new file mode 100644 index 0000000..0f67554 --- /dev/null +++ b/cpy_mqtt_client.py.save @@ -0,0 +1,525 @@ +# The `CpyMqttClient` class is a Python class that handles MQTT requests, sends commands to a server, +# processes server responses, and calculates various results based on received data. +from PySide6.QtCore import QObject, Signal, Slot, QTimer, QUrl, QIODevice + +import os +import gzip +from io import BytesIO +from Manager.history_manager import historyManager +import json +from config import * +import logging +import struct +import base64 +import threading +import uuid +import copy +import time +import socket + +import paho.mqtt.client as mqtt +import ssl + +import pandas as pd + +# 配置日志记录 +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s') +logger = logging.getLogger('CpyMqttClient') + +class CpyMqttClient(QObject): + reciveData = Signal(dict) + + def __init__(self, address, port, dev_id, psk=None): + super().__init__() + self.dev_id = dev_id + self.init = 1 + self.file_name = "" + self.scanner_name = "" + self.address = address + self.port = port + self.tempIndex = 0 + + self.last_server_ack_time = 0 + + self.cal_queue = {} + + # 初始化MQTT客户端,通过SSL连接 + # 使用V2.0 API版本 + self.client = mqtt.Client(client_id=dev_id, callback_api_version=mqtt.CallbackAPIVersion.VERSION2) + # 设置连接回调 + self.client.on_connect = self.on_connect + self.client.on_message = self.on_message + self.client.on_disconnect = self.on_disconnect + # 设置用户名密码 + self.client.username_pw_set('cpy_tgx-08_controller', 'tgzz2026.') + # 配置SSL + logger.info("Configuring SSL for MQTT connection...") + # 使用默认系统CA证书 + self.client.tls_set(cert_reqs=ssl.CERT_NONE) + # 禁用证书验证,解决自签名证书问题 + self.client.tls_insecure_set(True) + # 开始循环 + logger.info("Starting MQTT client loop...") + # self.client.loop_start() + + self.check_timer = QTimer(self) + self.check_timer.timeout.connect(self.check_mqtt_server) + self.check_timer.start(1000) + + thread = threading.Thread(target=self.main_loop) + thread.start() + + + + def cal_queue_lock(self): + if not hasattr(self, "_cal_queue_lock"): + self._cal_queue_lock = threading.Lock() + self._cal_queue_lock.acquire() + + def cal_queue_unlock(self): + try: + self._cal_queue_lock.release() + except: + pass + + def check_cal_queue(self): + """检查计算队列""" + if len(self.cal_queue) == 0: + return + logger.info(f"check cal queue: {len(self.cal_queue)} items in queue") + self.cal_queue_lock() + # 使用列表复制进行遍历,避免字典大小变化导致的错误 + for uid, data in list(self.cal_queue.items()): + if time.time() - data.get("time", 0) > 5: + logger.error(f"calculate response timeout: {uid}") + del self.cal_queue[uid] + self.cal_queue_unlock() + + def check_network_ready(self, host="cpycal.tgoim.com", port=8883): + try: + ip = socket.gethostbyname(host) + + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(0.5) + result = sock.connect_ex((ip, port)) + sock.close() + print(result) + if result == 0: + return ip + return False + except Exception as e: + print(e) + return False + + def check_mqtt_server(self): + if self.status == "init": + ip = self.check_network_ready() + if ip: + logger.info("Connecting to MQTT broker at cpycal.tgoim.com:8883...") + self.client.connect(ip, 8883, 10) + self.check_timer.stop() + + def main_loop(self): + """主循环""" + self.status = "init" + + + + while True: print(self.status) self.check_cal_queue() + + time.sleep(1) + if self.status == "init__": + if self.check_network_ready(): + # 连接到MQTT服务器 + logger.info("Connecting to MQTT broker at cpycal.tgoim.com:8883...") + self.client.connect('cpycal.tgoim.com', 8883, 10) + time.sleep(2) + else: + logger.info('network not ready...') + if self.status == "connected": + self.status = "checking" + self.check_server_status() + elif self.status == "available": + self.status = "registering" + self.register() + elif self.status == "checking": + if time.time() > self.check_server_status_time + 5: + self.status = "checking" + self.check_server_status() + elif self.status == "unavailable": + self.status = "checking" + self.check_server_status() + elif self.status == "registering": + if time.time() > self.register_time + 5: + self.status = "checking" + self.check_server_status() + elif self.status == "registered": + if time.time() > self.last_server_ack_time + 10: + self.status = "checking" + self.check_server_status() + + def on_disconnect(self, client, userdata, flags, rc, properties=None): + """断开连接回调 (V2.0 风格)""" + self.status = "disconnected" + logger.info(f"Disconnected from MQTT broker, return code: {rc}") + + def on_connect(self, client, userdata, flags, rc, properties=None): + """连接成功回调 (V2.0 风格)""" + if rc == 0: + logger.info("Connected to MQTT broker successfully") + self.status = "connected" + self.client.subscribe(f"v1/cpy/{self.dev_id}", qos=1) + else: + logger.error(f"Failed to connect to MQTT broker, return code: {rc}") + + def handle_calculate_response(self, result, uid): + """处理计算响应""" + if not result: + logger.error(f"Received calculate response with empty result: {result}") + return + try: + if not uid: + logger.error(f"Received calculate response with no 'uuid' field: {uid}") + return + self.cal_queue_lock() + _data = self.cal_queue.get(uid, None) + self.cal_queue_unlock() + if not _data: + logger.error(f"Received calculate response with no 'uuid' field: {uid}") + return + cal_data = copy.deepcopy(_data) #使用深拷贝 + self.cal_queue_lock() + del self.cal_queue[uid] #删除队列中的数据 + self.cal_queue_unlock() + + if cal_data.get("time", None): + logger.info(f"calculation costs time: {time.time() - cal_data.get('time', None)}") + + data_path = cal_data.get("data_path", None) + if not data_path: + logger.error(f"Received calculate response with no 'data_path' field: {data_path}") + return + info = cal_data.get("info", None) + if not info: + logger.error(f"Received calculate response with no 'info' field: {result}") + return + + # 保存设备名称和文件名 + scanner_id = info.get("scanner_id", None) + if not scanner_id: + logger.error(f"Received calculate response with no 'scanner_id' field: {result}") + return + + result['device'] = f"scanner{scanner_id}" + + # 计算额外的结果数据 + processed_result = self.calResult(json.dumps(result)) + # 保存结果到文件 + self.save_result(data_path, processed_result) + + # 发射结果信号 + self.emit_recive_data(processed_result) + except json.JSONDecodeError: + logger.error("Failed to parse server response as JSON") + + def handle_server_response(self, payload): + """处理服务器响应""" + cmd = payload.get("ack", None) + error = payload.get("error", None) + result = payload.get("result", None) + if not cmd or error is None or result is None: + logger.error(f"Received message with no 'ack' field: {payload}") + return + + if cmd == "status": + logger.info(f"Server status: {result}") + if error == 200: + self.status = "available" + else: + self.status = "unavailable" + elif cmd == 'register': + if error == 200: + self.status = "registered" + self.last_server_ack_time = time.time() + else: + self.status = "unavailable" + logger.info(f"Register status: {'success' if self.status == 'registered' else 'failed'}") + elif cmd == 'calculate': + if error == 200: + self.last_server_ack_time = time.time() + self.handle_calculate_response(result, payload.get("uuid", None)) + else: + logger.error(f"Received calculate response with error: {error}") + + def on_message(self, client, userdata, msg): + """接收消息回调 (V2.0 风格)""" + try: + payload = json.loads(msg.payload.decode()) + logger.info(f"Received message on topic {msg.topic}: {payload}") + self.handle_server_response(payload) + except json.JSONDecodeError: + logger.error(f"Failed to decode JSON from message on topic {msg.topic}") + + def send_command(self, payload): + """发送MQTT命令""" + topic = f"v1/cpy/server/3" + self.client.publish(topic, json.dumps(payload), qos=0) + + def register(self): + """注册设备到服务器""" + self.register_time = time.time() + payload = { + "cmd":"register", + "ver":1, + "dev_id": self.dev_id + } + self.send_command(payload) + + def check_server_status(self): + """检查服务器状态""" + self.check_server_status_time = time.time() + try: + payload = { + "cmd":"status", + "ver":1, + "dev_id": self.dev_id + } + self.send_command(payload) + logger.info(f"Sent status check command: {payload}") + except Exception as e: + logger.error(f"Error checking server status: {e}") + return None + + def calculate_data(self, info, data, data_path): + """计算数据""" + try: + info['uuid'] = str(uuid.uuid4()) + info['cmd'] = 'calculate' + info['ver'] = 1 + info['data'] = base64.b64encode(data).decode('utf-8') + self.cal_queue_lock() + self.cal_queue[info['uuid']] = { + "data_path" : data_path, + "info" : info, + "time" : time.time(), + } + self.cal_queue_unlock() + self.send_command(info) + except Exception as e: + logger.error(f"Error in calculate_data: {e}") + + def compress_file_with_name(self, csv_path: str): + compressed_data = None + try: + #使用pandas读取csv文件 + df = pd.read_csv(csv_path) + file_content = bytearray() + + # 遍历DataFrame中的每一行 + for index, row in df.iterrows(): + channel_A = row['CH1'] + channel_B = row['CH2'] + file_content.extend(struct.pack('= 3: + robj["EllipticityDmALL"] = 2*abs(DmALL[1]-DmALL[2])/(DmALL[1] + DmALL[2]) if (DmALL[1] + DmALL[2]) != 0 else 0 + else: + robj["EllipticityDmALL"] = 0 + + if len(DmCORE) >= 3: + robj["EllipticityDmCORE"] = 2*abs(DmCORE[1]-DmCORE[2])/(DmCORE[1] + DmCORE[2]) if (DmCORE[1] + DmCORE[2]) != 0 else 0 + else: + robj["EllipticityDmCORE"] = 0 + + # 计算平均值 + robj["AvgALL"] = self.avg(WtALL) + robj["AvgISC"] = self.avg(WtISC) + robj["AvgOSC"] = self.avg(WtOSC) + robj["AvgINS"] = self.avg(WtINS) + + # 计算最小值 + if WtALL: + robj["MinALL"] = min(WtALL) + robj["ConcentricityALL"] = 200*min(WtALL)/(min(WtALL)+max(WtALL)) if (min(WtALL)+max(WtALL)) != 0 else 0 + robj["EccentricALL"] = (max(WtALL) - min(WtALL))/2 + robj["EccentricityALL"] = (max(WtALL) - min(WtALL))*100/max(WtALL) if max(WtALL) != 0 else 0 + else: + robj["MinALL"] = 0 + robj["ConcentricityALL"] = 0 + robj["EccentricALL"] = 0 + robj["EccentricityALL"] = 0 + + if WtISC: + robj["MinISC"] = min(WtISC) + robj["ConcentricityISC"] = 200*min(WtISC)/(min(WtISC)+max(WtISC)) if (min(WtISC)+max(WtISC)) != 0 else 0 + robj["EccentricISC"] = (max(WtISC) - min(WtISC))/2 + robj["EccentricityISC"] = (max(WtISC) - min(WtISC))*100/max(WtISC) if max(WtISC) != 0 else 0 + else: + robj["MinISC"] = 0 + robj["ConcentricityISC"] = 0 + robj["EccentricISC"] = 0 + robj["EccentricityISC"] = 0 + + if WtOSC: + robj["MinOSC"] = min(WtOSC) + robj["ConcentricityOSC"] = 200*min(WtOSC)/(min(WtOSC)+max(WtOSC)) if (min(WtOSC)+max(WtOSC)) != 0 else 0 + robj["EccentricOSC"] = (max(WtOSC) - min(WtOSC))/2 + robj["EccentricityOSC"] = (max(WtOSC) - min(WtOSC))*100/max(WtOSC) if max(WtOSC) != 0 else 0 + else: + robj["MinOSC"] = 0 + robj["ConcentricityOSC"] = 0 + robj["EccentricOSC"] = 0 + robj["EccentricityOSC"] = 0 + + if WtINS: + robj["MinINS"] = min(WtINS) + robj["ConcentricityINS"] = 200*min(WtINS)/(min(WtINS)+max(WtINS)) if (min(WtINS)+max(WtINS)) != 0 else 0 + robj["EccentricINS"] = (max(WtINS) - min(WtINS))/2 + robj["EccentricityINS"] = (max(WtINS) - min(WtINS))*100/max(WtINS) if max(WtINS) != 0 else 0 + else: + robj["MinINS"] = 0 + robj["ConcentricityINS"] = 0 + robj["EccentricINS"] = 0 + robj["EccentricityINS"] = 0 + + # 保存到历史记录 + try: + historyManager.create(robj) + except Exception as hist_error: + logger.error(f"Error saving to history: {hist_error}") + + return robj + except Exception as e: + logger.error(f"Error processing calculation result: {e}") + return {} + + def avg(self, data): + """计算平均值""" + if len(data) == 0: + return 0 + if len(data) == 1: + return data[0] + try: + mean_value = sum(data) / len(data) + return mean_value + except TypeError: + logger.error("Error calculating average: data contains non-numeric values") + return 0 + + @Slot(object) + def psk_required(self, auth): + # HTTP客户端不需要PSK认证 + pass + + + + diff --git a/create.sql b/create.sql new file mode 100644 index 0000000..87d1480 --- /dev/null +++ b/create.sql @@ -0,0 +1,32 @@ +/* + Navicat Premium Data Transfer + + Source Server : data + Source Server Type : SQLite + Source Server Version : 3021000 + Source Schema : main + + Target Server Type : SQLite + Target Server Version : 3021000 + File Encoding : 65001 + + Date: 06/09/2024 11:06:05 +*/ + +PRAGMA foreign_keys = false; + +-- ---------------------------- +-- Table structure for device_model_group +-- ---------------------------- + +CREATE TABLE "history" ( + "id" text NOT NULL, + "name" TEXT, + "info" TEXT, + "datetime" TEXT +); +CREATE TABLE "product" ( + "id" text NOT NULL, + "info" TEXT +); +PRAGMA foreign_keys = true; \ No newline at end of file diff --git a/data_center.py b/data_center.py new file mode 100644 index 0000000..107ca64 --- /dev/null +++ b/data_center.py @@ -0,0 +1,276 @@ +from PySide6.QtCore import * +from datetime import datetime +from config import * +class DataCenter(QObject): + plcAlive = Signal(bool) + dataReady = Signal(dict) + send_temperature_data = Signal(str, dict) + readFinished = Signal() + + def __init__(self, parent=None): + super().__init__(parent) + + self.settings = QSettings("TGZZ", "TGX") # 设置存储位置 + self.temp_timer = QTimer(self) + self.temp_timer.timeout.connect(self.update_temp_timer) + + self.debug_timer = QTimer(self) + self.debug_timer.timeout.connect(self.update_debug_timer) + if YSMODE: + self.debug_timer.start(1000) + self.temp_timer.start(1000) + self.temp_data = {} + self.device_object = { + "scanner1":{ + "acquisition_board":{ + "temperature": 0 , + "temperature_alarm_line": 0, + "communication_status": 0, + "failure_status": 1, + "failure_info": "采集板故障", + "usage_duration": 15, + "useful_life": 365 + }, + "power":{ + "voltage_value": 0, + "voltage_setting_value": 0, + "current_value": 0, + "current_setting_value": 0, + "filament_current_value": 0, + "filament_current_setting_value": 0, + "filament_preheating_current_value": 0, + "filament_preheating_current_setting_value": 0, + "communication_status": 0, + "failure_status": 1, + "failure_info": "电源故障", + "enable_status": 0, + "safety_lock": 0, + "switch": 0, + "temperature": 0, + "temperature_alarm_line": 80, + "usage_duration": 15, + "useful_life": 365 + }, + "xray":{ + "enable_status": 0, + "oil_temperature": 0, + "oil_temperature_alarm_line": 50, + "liquid_level": 0, + "usage_duration": 15, + "useful_life": 365, + "failure_status": 1, + "failure_info": "射线故障" + }, + "motor":{ + "communication_status": 0, + "position": 0, + "direction": 0, + "velocity": 0, + "setting_velocity": 0, + "usage_duration": 15, + "useful_life": 365, + "failure_status": 1, + "failure_info": "电机故障" + } + }, + "scanner2":{ + "acquisition_board":{ + "temperature": 0 , + "temperature_alarm_line": 0, + "communication_status": 0, + "failure_status": 1, + "failure_info": "采集板故障", + "usage_duration": 15, + "useful_life": 365 + }, + "power":{ + "voltage_value": 0, + "voltage_setting_value": 0, + "current_value": 0, + "current_setting_value": 0, + "filament_current_value": 0, + "filament_current_setting_value": 0, + "filament_preheating_current_value": 0, + "filament_preheating_current_setting_value": 0, + "communication_status": 0, + "failure_status": 1, + "failure_info": "电源故障", + "enable_status": 0, + "safety_lock": 0, + "switch": 0, + "temperature": 0, + "temperature_alarm_line": 80, + "usage_duration": 15, + "useful_life": 365 + }, + "xray":{ + "enable_status": 0, + "oil_temperature": 0, + "oil_temperature_alarm_line": 50, + "liquid_level": 0, + "usage_duration": 15, + "useful_life": 365, + "failure_status": 1, + "failure_info": "射线故障" + }, + "motor":{ + "communication_status": 0, + "position": 0, + "direction": 0, + "velocity": 0, + "setting_velocity": 0, + "usage_duration": 15, + "useful_life": 365, + "failure_status": 1, + "failure_info": "电机故障" + } + }, + "global_dev":{ + "device":{ + "cw_flow_rate": 0, + "cw_flow_rate_lower_limit": 0, + "custom_intvl": 0, + "water_temperature": 0, + "water_temperature_alarm_line": 50, + "light": False, + "outlet_air_temperature": 0, + "outlet_air_temperature_alarm_line": 50, + "control_board_temperature": 0, + "control_board_temperature_alarm_line": 30, + "failure_info": "通用设备故障1,2", + "sports_mode": "fast" + } + } + } + + def appendTempData(self, data1, data2, max_count=3600): + dateTimeData = self.temp_data.get("datetime", []) + scanner1data = self.temp_data.get("SCANNER1", []) + scanner2data = self.temp_data.get("SCANNER2", []) + + timestamp = int(datetime.now().timestamp()) + if len(dateTimeData) >= max_count: + dateTimeData.pop(0) + dateTimeData.append(timestamp) + if len(scanner1data) >= max_count: + scanner1data.pop(0) + scanner1data.append(data1) + + if len(scanner2data) >= max_count: + scanner2data.pop(0) + scanner2data.append(data2) + self.temp_data["SCANNER1"] = scanner1data + self.temp_data["SCANNER2"] = scanner2data + self.temp_data["datetime"] = dateTimeData + self.temp_data["method"] = "temperature" + + def update_debug_timer(self): + self.dataReady.emit(self.device_object) + + def update_temp_timer(self): + data1 = self.device_object["scanner1"]["xray"]["oil_temperature"] + data2 = self.device_object["scanner2"]["xray"]["oil_temperature"] + self.appendTempData(data1, data2) + + @Slot(str, int) + def get_temperature(self, cid, duration): + self.send_temperature_data.emit(cid, self.temp_data) + @Slot(int, dict) + def update_voltage_info(self, voltage_index, info): + self.device_object[f"scanner{voltage_index}"]["power"] = info + self.dataReady.emit(self.device_object) + + @Slot(dict) + def update_motor_globaldev_info(self, info): + self.device_object[f"global_dev"]["device"]["sports_mode"] = info["sports_mode"] + self.dataReady.emit(self.device_object) + + @Slot(dict) + def update_globaldev_info(self, info): + self.device_object[f"global_dev"] = info + self.dataReady.emit(self.device_object) + + @Slot(int, dict) + def update_xray_info(self, xray_index, info): + self.device_object[f"scanner{xray_index}"]["xray"] = info + self.dataReady.emit(self.device_object) + + @Slot(int, dict) + def update_acquisition_info(self, acquisition_index, info): + self.device_object[f"scanner{acquisition_index}"]["acquisition_board"]["temperature"] = info["temp"]/10 + self.dataReady.emit(self.device_object) + + @Slot(int, dict) + def update_motor_info(self, motor_index, info): + self.device_object[f"scanner{motor_index}"]["motor"] = info + self.dataReady.emit(self.device_object) + + @Slot(int, int) + def update_motor_position(self, motor_index, position): + self.device_object[f"scanner{motor_index}"]["motor"]["position"] = position + self.dataReady.emit(self.device_object) + + @Slot(int, int) + def update_motor_direction(self, motor_index, direction): + self.device_object[f"scanner{motor_index}"]["motor"]["direction"] = direction + self.dataReady.emit(self.device_object) + + @Slot(int,float) + def update_motor_velocity(self, motor_index, velocity): + self.device_object[f"scanner{motor_index}"]["motor"]["velocity"] = velocity + self.dataReady.emit(self.device_object) + + @Slot(int, dict) + def update_alu_info(self, alu_index, info): + self.device_object["global_dev"]["device"]["light"] = info["light"] + self.dataReady.emit(self.device_object) + + @Slot(int, dict) + def update_wsu_info(self, wsu_index, info): + self.device_object["global_dev"]["device"]["cw_flow_rate"] = info["flow_rate"] + self.device_object["global_dev"]["device"]["water_temperature"] = info["water_temp"] + self.dataReady.emit(self.device_object) + + @Slot(int, dict) + def update_osu_info(self, osu_index, info): + self.device_object[f"scanner{osu_index}"]["xray"]["oil_temperature"] = info["oil_temp"] + self.device_object[f"scanner{osu_index}"]["xray"]["liquid_level"] = info["oil_level"] + self.dataReady.emit(self.device_object) + + + @Slot(int, dict) + def update_hsv_info(self, hsv_index, info): + self.device_object[f"scanner{hsv_index}"]["power"]["voltage_value"] = info["voltage"] + self.device_object[f"scanner{hsv_index}"]["power"]["current_value"] = info["current"] + self.device_object[f"scanner{hsv_index}"]["power"]["filament_current_value"] = info["current_filament"] + self.device_object[f"scanner{hsv_index}"]["power"]["temperature"] = info["internal_temperature"] + self.device_object[f"scanner{hsv_index}"]["power"]["enable_status"] = 1 if info["switch_status"] == True else 0 + + # self.device_object[f"scanner{hsv_index}"]["xray"]["enable_status"] = 1 if info["xray_status"] == True else 0 + # self.device_object[f"scanner{hsv_index}"]["power"]["voltage_setting_value"] = info["param"]["kV"] + # self.device_object[f"scanner{hsv_index}"]["power"]["current_setting_value"] = info["param"]["mA"] + #TODO + # self.device_object[f"scanner{hsv_index}"]["power"]["filament_current_setting_value"] = info["param"]["filament_limit"] + # self.device_object[f"scanner{hsv_index}"]["power"]["filament_preheating_current_setting_value"] = info["param"]["filament_preheat"] + self.dataReady.emit(self.device_object) + + @Slot(int,float) + def update_motor_setting_velocity(self, motor_index, setting_velocity): + self.device_object[f"scanner{motor_index}"]["motor"]["setting_velocity"] = setting_velocity + self.dataReady.emit(self.device_object) + + @Slot(str, int) + def write_data(self, dbname, num): + self.settings.setValue(dbname, num) # 保存到设置中 + return True + + def reapply_write_settings(self): + """ 从 QSettings 加载之前保存的写入日志 """ + dbnames = self.settings.allKeys() # 获取所有键 + for dbname in dbnames: + num = self.settings.value(dbname) # 获取对应的值 + print(f"Reapplying write: {dbname} = {num}") + self.write_data(dbname, num) + + + diff --git a/dog.py b/dog.py new file mode 100644 index 0000000..341484a --- /dev/null +++ b/dog.py @@ -0,0 +1,59 @@ +# -- coding: utf-8 -- +import Psyunew3 +from ctypes import * + +class Dog(): + def isDogAlive(self): + try: + DevicePath=create_string_buffer(260) + ret=c_int() + ##这个用于判断系统中是否存在着加密锁。不需要是指定的加密锁, + ret = Psyunew3.FindPort(0,DevicePath) + if(ret!=0): + return 2 + print('未找到加密锁,请插入加密锁后,再进行操作。') + exit() + print("dog ret:",ret) + ##使用普通算法一来检查是否存在指定的加密锁 + if (Psyunew3.CheckKeyByFindort_2() == 0): + pass + # print('使用普通算法一来检查:找到指定的加密锁') + else: + return 3 + print('使用普通算法一来检查:未能找到指定的加密锁') + + + ##使用增强算法一来检查是否存在指定的加密锁 + ret = Psyunew3.CheckKeyByEncstring() + if (ret == 1): + pass + # print( '你生成加密代码时没有设置该函数') + else: + if (ret == 0): + pass + # print('使用增强算法一来检查:找到指定的加密锁') + else: + return 4 + print('使用增强算法一来检查:未能找到指定的加密锁') + + ##使用增强算法二来检查是否存在指定的加密锁 + ret = Psyunew3.CheckKeyByEncstring_New() + if (ret == 0): + pass + # print('使用增强算法二来检查:找到指定的加密锁') + else: + if (ret < 0): + return 5 + print('使用增强算法二来检查:未能找到指定的加密锁') + elif (ret == 2): + return 6 + print('当前锁不支持这个功能。') + return 1 + except Exception as e: + print(f"dog Error{e}") + return 9 + def read_string(self): + DevicePath=create_string_buffer(260) + return Psyunew3.ReadStringEx(0, DevicePath) +dog = Dog() + diff --git a/http_server.py b/http_server.py new file mode 100644 index 0000000..ce467f0 --- /dev/null +++ b/http_server.py @@ -0,0 +1,467 @@ +import socket +import base64 +import json +import time +import os +from unittest import result +import psutil +import struct +import csv +import threading +from collections import defaultdict +from typing import Dict, List, Tuple, Optional +import logging +from config import * +from x_ray_data_processor import processor +from PySide6.QtCore import QObject, Signal, Slot, QThread, QTimer +from scipy.ndimage import gaussian_filter1d +import numpy as np +import binascii + +def crc16_modbus(data: bytes) -> int: + """CRC-16/MODBUS算法实现,与客户端C代码完全一致""" + crc = 0xFFFF + for byte in data: + crc ^= byte + for _ in range(8): + if crc & 0x0001: + crc >>= 1 + crc ^= 0xA001 + else: + crc >>= 1 + return crc +from http.server import BaseHTTPRequestHandler, HTTPServer + +from scipy.ndimage import gaussian_filter1d + +from fastapi import FastAPI, File, Form, HTTPException, Request +from fastapi.middleware.cors import CORSMiddleware +import uvicorn + +# 配置日志 +logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +__udp_port = 50009 + +http_thread = None + +def udp_send(data): + _socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + _socket.sendto(data, ("127.0.0.1", __udp_port)) + _socket.sendto(data, ("192.168.8.150", 50009)) #调试用 + +# 创建FastAPI应用 +app = FastAPI( + title="CPY Controller API", + description="HTTP and UDP server for CPY Controller", + version="1.0.0" +) + +# 配置CORS +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# HTTP路由 +@app.get("/") +async def root(): + """根路径""" + return { + "message": "Welcome to CPY Controller API!", + "endpoints": { + "post_data": "/api/data", + "multipart_endpoint": "/api/endpoint" + } + } + +@app.post("/api/endpoint") +async def receive_multipart_data( + request: Request, + metadata: str = Form(...), # 接收JSON字符串 + data: bytes = File(...), # 接收二进制数据,使用File但接收bytes +): + """接收multipart/form-data格式数据""" + try: + # 解析metadata JSON + metadata_dict = json.loads(metadata) + logger.info(f"Received metadata: {metadata_dict}") + + binary_data = data + + print('binary_data:', binary_data[:10].hex(' ')) + + # 构造与原系统兼容的数据结构 + data_json = { + 'type': metadata_dict.get('type', 'data_points'), + 'name': metadata_dict.get('name', 'daq'), + 'id': metadata_dict.get('id', ''), + 'version': metadata_dict.get('version', 'V8'), + 'direction': metadata_dict.get('direction', ''), + 'data': base64.b64encode(binary_data).decode('utf-8'), + 'data_len': metadata_dict.get('data_len', len(binary_data)) + } + + # 发送到UDP + udp_send(json.dumps(data_json).encode()) + + return { + "status": "success" + } + except json.JSONDecodeError as e: + logger.error(f"Error parsing metadata: {e}") + raise HTTPException(status_code=400, detail="Invalid metadata JSON format") + except Exception as e: + logger.error(f"Error processing multipart data: {e}") + raise HTTPException(status_code=400, detail=f"Error processing data: {str(e)}") + +class HttpServerEnhanced(QThread): + start_cal = Signal(int, str, str, int) # 信号:接收到消息,包含数据文件路径、发送者地址和端口 + send_collect_data = Signal(dict) # + update_acquisition_info = Signal(int, dict) + + def __init__(self, ip="0.0.0.0", port=50009, parent=None): + super(HttpServerEnhanced, self).__init__(parent) + + global __udp_port + + self.ip = ip + self.port = port + __udp_port = port + + self.running = True + self.motor1_direction = "" + self.motor2_direction = "" + + self.collect_object1 = { + "method" : "scanner1", + "channelA_data" :"base64", + "channelB_data" :"base64", + "intensityA" : 98, + "intensityB" : 98 + } + self.collect_object2 = { + "method" : "scanner2", + "channelA_data" :"base64", + "channelB_data" :"base64", + "intensityA" : 98, + "intensityB" : 98 + } + self.debug_timer = QTimer(self) + self.debug_timer.timeout.connect(self.update_debug_timer) + if YSMODE: + self.debug_timer.start(1000) + + global http_thread + http_thread = threading.Thread(target=self.http_loop, args=(10008,)) + http_thread.start() + + def update_debug_timer(self): + import random + channelA = [random.randint(1, 1000) for _ in range(3000)] + channelB = [random.randint(1, 1000) for _ in range(3000)] + self.collect_object1['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode() + self.collect_object1['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode() + self.collect_object2['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode() + self.collect_object2['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode() + self.send_collect_data.emit(self.collect_object1) + self.send_collect_data.emit(self.collect_object2) + + def parse_V8_packet(self, base64_data, data_len): + binary_data = base64.b64decode(base64_data) + channel_A = [] + channel_B = [] + + offset = 0 + + print("data_len:", data_len, "len(binary_data):", len(binary_data)) + + bytes_len = struct.unpack(' len(binary_data): + print("offset:", offset, "data_len:", len(data_points)) + break + channel_A.append(struct.unpack(' 100: + #gause filter + channelA_filtered = gaussian_filter1d(channelA, 0.1) + channelA = np.array(channelA_filtered).tolist() + channelB_filtered = gaussian_filter1d(channelB, 0.1) + channelB = np.array(channelB_filtered).tolist() + #save data to csv file + + chop_num = 300 + + if ip_address == "192.168.100.236" or msg.get("id","") == "1#SCANNER": + dev_name = "Scanner1" + chop_num = 200 + elif ip_address == "192.168.100.237" or msg.get("id","") == "2#SCANNER": + dev_name = "Scanner2" + chop_num = 200 + + if direction == "UP": + channelA = channelA[chop_num:-200] + channelB = channelB[chop_num:-200] + elif direction == "DOWN": + channelA = channelA[200:-chop_num] + channelB = channelB[200:-chop_num] + + save_filename = f'{time.strftime("%Y%m%d_%H%M%S")}_{dev_name}_{direction}.csv' + data_path = self.save_data_to_csv(save_filename, channelA, channelB) + + channelA_average = np.mean(channelA) + channelB_average = np.mean(channelB) + + #COREECTMODE = False + corrected_name = None + if COREECTMODE and channelA_average > 5000 and channelB_average > 5000: + try: + new_A, new_B = self.correct_data(data_path) + #save corrected data to csv file + if new_A is not None and new_B is not None: + corrected_name = save_filename[0:-4] +"_corrected.csv" + new_path = self.save_data_to_csv(corrected_name, new_A, new_B) + if new_path and os.path.exists(new_path): + os.remove(data_path) #remove old file + data_path = new_path + channelA = new_A + channelB = new_B + except Exception as e: + print(f"Error correcting data: {e}") + channelA_json = json.dumps(channelA) + channelB_json = json.dumps(channelB) + # print("================channelA_json",channelA_json) + # print("================channelB_json",channelB_json) + channelA_bytes = channelA_json.encode('utf-8') + channelB_bytes = channelB_json.encode('utf-8') + + if ip_address == "192.168.100.236" or msg.get("id","") == "1#SCANNER": + self.collect_object1["method"] = "scanner1" + if channelA_average < 5000 or channelB_average < 5000: + print("xray low idensity") + else: + if data_path: + self.start_cal.emit(1, data_path, direction, len(channelA)) + print("====emit direction[1]:", direction) + self.collect_object1['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8') + self.collect_object1['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8') + self.send_collect_data.emit(self.collect_object1) + elif ip_address == "192.168.100.237" or msg.get("id","") == "2#SCANNER": + self.collect_object2["method"] = "scanner2" + if channelA_average < 5000 or channelB_average < 5000: + print("xray low idensity") + else: + self.start_cal.emit(2, data_path, direction, len(channelA)) + print("====emit direction[2]:", direction) + self.collect_object2['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8') + self.collect_object2['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8') + self.send_collect_data.emit(self.collect_object2) + + except OSError as e: + print(f"Error handle_data_point: {e}") # 记录错误信息 + + def stop(self): + """停止 UDP 服务器""" + self.running = False + http_thread.join() + self.wait() # 等待线程结束 + + def __del__(self): + self.stop() # 确保在对象销毁时停止服务器 diff --git a/install_packages.sh b/install_packages.sh new file mode 100644 index 0000000..cf0f630 --- /dev/null +++ b/install_packages.sh @@ -0,0 +1,2 @@ +#!/bin/bash +pip install -r requirements.txt diff --git a/libPsyunew3_arm8.so b/libPsyunew3_arm8.so new file mode 100644 index 0000000..9d2db87 Binary files /dev/null and b/libPsyunew3_arm8.so differ diff --git a/main.py b/main.py new file mode 100644 index 0000000..b6edc9e --- /dev/null +++ b/main.py @@ -0,0 +1,139 @@ +# main.py +from mqtt_client import MQTTClient +from data_center import DataCenter +from cpy_mqtt_client import CpyMqttClient +from http_server import HttpServerEnhanced +from tcp_modbus import TCPModbus +from PySide6.QtCore import * +from config import * +from dog import dog +import subprocess +import os +import time +import sqlite3 +import sys +import json +def import_sql_to_database(db_path, table_bame): + + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + sql_file_path = f"{table_bame}.sql" + try: + with open(sql_file_path, 'r', encoding='utf-8') as file: + sql_script = file.read() + try: + conn.executescript(sql_script) + except sqlite3.Error as e: + print(f"SQLite error: {e}") + return + conn.commit() + print("SQL file imported successfully.") + + except FileNotFoundError: + print(f"The file {sql_file_path} was not found.") + except Exception as e: + print(f"An unexpected error occurred: {e}") + finally: + conn.close() +def get_cpu_serial(): + cmd = "cat /proc/cpuinfo | grep Serial | awk -F' ' '{print $3}'" + serial = subprocess.check_output(cmd, shell=True).decode().strip() + return serial + + +def read_config(): + config = {} + path = "/home/admin/.config/cpy/config.json" + with open(path, "r") as f: + config = json.load(f) + return config + return None + +def save_config(config): + path = "/home/admin/.config/cpy/config.json" + with open(path, "w", encoding='utf-8') as f: + json.dump(config, f, indent=4) + +if __name__ == "__main__": + app = QCoreApplication(sys.argv) + isDog = dog.isDogAlive() + if not isDog: + print("Dog is not running, exit program") + sys.exit(0) + # time.sleep(5) + # dataDB = os.path.join(os.path.dirname(__file__),'data.db') + # import_sql_to_database(dataDB,"create") + dog_str = dog.read_string() + print(dog_str) + str_keys = dog_str.decode() + print(str_keys) + + list_keys = str_keys.split("#") + device_id = list_keys[0] + cpu_id = list_keys[1] + if not cpu_id == get_cpu_serial(): + print("序列号不匹配,退出程序") + sys.exit(0) + psk = list_keys[2] + + + mqtt_client = MQTTClient(device_id)#http://123.57.81.127/ + + data_center = DataCenter() + udp_server = HttpServerEnhanced(port=50009) + udp_server.start() + modbus_client = TCPModbus(host='192.168.8.211', port=502) + modbus_client.start() + + config = read_config() + + if config.get('sn', '') != device_id: + config.update(sn = device_id) + save_config(config) + + ip = "101.200.29.204" + port = 18003 + try: + if config: + if 'calc_server' in config: + ip = config['calc_server'].get('ip', "101.200.29.204") + port = config['calc_server'].get('port', 18003) + + protocol = config['calc_server'].get('protocol', "dtls") + if protocol == "dtls": + calc_client = DtlsAssociation(ip, port, device_id, psk) + calc_client.start_handshake() + elif protocol == "http": + calc_client = CalcHttpClient(ip, port, device_id, psk) + elif protocol == "mqtt": + calc_client = CpyMqttClient(ip, port, device_id, psk) + except Exception as e: + print(f"Error: {e}") + sys.exit(0) + + # mqtt_client.update_direction.connect(udp_server.update_direction) + udp_server.send_collect_data.connect(mqtt_client.send_collect_data) + udp_server.start_cal.connect(calc_client.start_cal) + modbus_client.sig_start.connect(mqtt_client.start_device) + modbus_client.sig_pause.connect(mqtt_client.pause_device) + modbus_client.sig_reset.connect(calc_client.set_init) + modbus_client.sig_stop.connect(mqtt_client.stop_device) + udp_server.update_acquisition_info.connect(data_center.update_acquisition_info) + calc_client.reciveData.connect(mqtt_client.send_kneed) + mqtt_client.update_motor_info.connect(data_center.update_motor_info) + mqtt_client.update_alu_info.connect(data_center.update_alu_info) + mqtt_client.update_wsu_info.connect(data_center.update_wsu_info) + mqtt_client.update_osu_info.connect(data_center.update_osu_info) + mqtt_client.update_hsv_info.connect(data_center.update_hsv_info) + mqtt_client.get_temperature.connect(data_center.get_temperature) + mqtt_client.update_motor_globaldev_info.connect(data_center.update_motor_globaldev_info) + mqtt_client.calc_init.connect(calc_client.set_init) + data_center.dataReady.connect(mqtt_client.send_deviceinfo) + data_center.send_temperature_data.connect(mqtt_client.send_temperature_data) + + try: + app.exec() + except Exception as e: + print(f"Error: {e}") + + sys.exit(0) diff --git a/main_ys_mode.py b/main_ys_mode.py new file mode 100644 index 0000000..9cc9732 --- /dev/null +++ b/main_ys_mode.py @@ -0,0 +1,94 @@ +# main.py +from mqtt_client import MQTTClient +from data_center import DataCenter +from dtls_client import DtlsAssociation +from udp_server import UdpServer +from tcp_modbus import TCPModbus +from PySide6.QtCore import * +from config import * +from dog import dog +import subprocess +import os +import time +import sqlite3 +import sys +def import_sql_to_database(db_path, table_bame): + + conn = sqlite3.connect(db_path) + cursor = conn.cursor() + sql_file_path = f"{table_bame}.sql" + try: + with open(sql_file_path, 'r', encoding='utf-8') as file: + sql_script = file.read() + try: + conn.executescript(sql_script) + except sqlite3.Error as e: + print(f"SQLite error: {e}") + return + conn.commit() + print("SQL file imported successfully.") + + except FileNotFoundError: + print(f"The file {sql_file_path} was not found.") + except Exception as e: + print(f"An unexpected error occurred: {e}") + finally: + conn.close() +def get_cpu_serial(): + cmd = "cat /proc/cpuinfo | grep Serial | awk -F' ' '{print $3}'" + serial = subprocess.check_output(cmd, shell=True).decode().strip() + return serial + + +if __name__ == "__main__": + app = QCoreApplication(sys.argv) + isDog = dog.isDogAlive(); + if not isDog: + print("Dog is not running, exit program") + sys.exit(0) + os.system("sudo ifconfig can0 down") + # time.sleep(0.5) + os.system("sudo ip link set can0 up type can bitrate 500000") + os.system("sudo ifconfig can0 txqueuelen 65536") + os.system("sudo ifconfig can0 up") + dataDB = os.path.join(os.path.dirname(__file__),'data.db') + import_sql_to_database(dataDB,"create") + dog_str = dog.read_string() + # str_keys = dog_str.decode() + str_keys = "1#1#241324F9-8563-424D-9E98-8DDAFE105EA5" + list_keys = str_keys.split("#") + device_id = list_keys[0] + # cpu_id = list_keys[1] + # if not cpu_id == get_cpu_serial(): + # print("序列号不匹配,退出程序") + # sys.exit(0) + psk = list_keys[2] + + mqtt_client = MQTTClient(device_id)#http://123.57.81.127/ + mqtt_client.connectToBroker() + data_center = DataCenter() + udp_server = UdpServer(port=50009) + udp_server.start() + modbus_client = TCPModbus(host='192.168.8.211', port=502) + modbus_client.start() + dtls_client = DtlsAssociation("101.200.29.204", 18003, "TGZZ", psk) + dtls_client.start_handshake() + # mqtt_client.update_direction.connect(udp_server.update_direction) + udp_server.send_collect_data.connect(mqtt_client.send_collect_data) + udp_server.start_cal.connect(dtls_client.start_cal) + modbus_client.sig_start.connect(mqtt_client.start_device) + modbus_client.sig_pause.connect(mqtt_client.pause_device) + modbus_client.sig_reset.connect(dtls_client.set_init) + modbus_client.sig_stop.connect(mqtt_client.stop_device) + udp_server.update_acquisition_info.connect(data_center.update_acquisition_info) + dtls_client.reciveData.connect(mqtt_client.send_kneed) + mqtt_client.update_motor_info.connect(data_center.update_motor_info) + mqtt_client.update_alu_info.connect(data_center.update_alu_info) + mqtt_client.update_wsu_info.connect(data_center.update_wsu_info) + mqtt_client.update_osu_info.connect(data_center.update_osu_info) + mqtt_client.update_hsv_info.connect(data_center.update_hsv_info) + mqtt_client.get_temperature.connect(data_center.get_temperature) + mqtt_client.update_motor_globaldev_info.connect(data_center.update_motor_globaldev_info) + data_center.dataReady.connect(mqtt_client.send_deviceinfo) + data_center.send_temperature_data.connect(mqtt_client.send_temperature_data) + sys.exit(app.exec()) diff --git a/models.py b/models.py new file mode 100644 index 0000000..4fbc726 --- /dev/null +++ b/models.py @@ -0,0 +1,277 @@ +#!/opt/homebrew/bin/python3 +# -*- coding:utf-8 -*- + +from sqlalchemy import Column, Integer, String, DateTime, create_engine +from sqlalchemy.orm import sessionmaker, declarative_base +from concurrent.futures import ThreadPoolExecutor +from datetime import datetime, timedelta +import os +import json +import uuid + +dataDB = os.path.join(os.path.dirname(__file__),'data.db') +engine = create_engine(f'sqlite:///{dataDB}') + +SessionMaker = sessionmaker(bind=engine)() + +Base = declarative_base() + + +class Product(Base): + __tablename__ = 'product' + id = Column(String, primary_key=True, doc='产品ID') + info = Column(String, nullable=False, doc='产品详情') + +class History(Base): + __tablename__ = 'history' + id = Column(String, primary_key=True, doc='历史ID') + name = Column(String, nullable=False, doc='历史名称') + info = Column(String, nullable=False, doc='历史详情') + datetime = Column(DateTime, nullable=False, doc='历史时间') + + +class Session(): + def __init__(self): + super().__init__() + self.executor = ThreadPoolExecutor() + def addByClass(self, cls, _data): + try: + if not _data: + return False, None + data = cls() + for k, v in _data.items(): + if k == '_sa_instance_state': + continue + setattr(data, k, v) + SessionMaker.add(data) + SessionMaker.commit() + data.id + + return True, data.__dict__ + except Exception as e: + print(e) + return False, None + finally: + SessionMaker.close() + def queryByIds(self, cls, ids): + try: + if not cls or not ids: + return False, None + data = SessionMaker.query(cls).filter(cls.id.in_(ids)).all() + if not data: + return False, None + result = [] + for item in data: + if '_sa_instance_state' in item.__dict__: + del item.__dict__['_sa_instance_state'] + result.append(item.__dict__) + return True, result + except Exception as e: + + return False, None + + def queryById(self, cls, _id): + try: + if not cls or not _id: + return False, None + data = SessionMaker.query(cls).get(_id) + if not data: + return False, None + if '_sa_instance_state' in data.__dict__: + del data.__dict__['_sa_instance_state'] + return True, data.__dict__ + except Exception as e: + + return False, None + + def queryByDateHour(self, cls, date_str, hour_str): + try: + print("date_str:",date_str,"hour_str:",hour_str) + if not cls or not date_str or not hour_str: + return False, None + + date = datetime.strptime(date_str, "%Y-%m-%d") + hour = int(hour_str) + + start_datetime = datetime(date.year, date.month, date.day, hour, 0, 0) + end_datetime = start_datetime + timedelta(hours=1) + print("start_datetime:",start_datetime, "end_datetime:",end_datetime) + + data = SessionMaker.query(cls).filter( + cls.datetime >= start_datetime, + cls.datetime < end_datetime + ).all() + + if not data: + return False, None + + time_list = [item.datetime.strftime("%Y-%m-%d %H:%M:%S.%f") for item in data] + + return True, time_list + except Exception as e: + print(f"Error occurred: {e}") + return False, None + + def queryByDatetime(self, cls, datetime_str): + try: + if not cls or not datetime_str: + return False, None + + # 将字符串转换为datetime对象 + try: + # 支持包含毫秒的格式: 2025-03-14 17:48:50.992612 + target_datetime = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S.%f") + except ValueError: + # 尝试不带毫秒的格式 + try: + target_datetime = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S") + except ValueError: + print(f"Invalid datetime format: {datetime_str}. Expected format: %Y-%m-%d %H:%M:%S or %Y-%m-%d %H:%M:%S.%f") + return False, None + + # 精确匹配查询 + data = SessionMaker.query(cls).filter(cls.datetime == target_datetime).first() + + if not data: + return False, None + + # 处理查询结果 + if '_sa_instance_state' in data.__dict__: + del data.__dict__['_sa_instance_state'] + + return True, data.__dict__ + except Exception as e: + print(f"queryByDatetime error: {e}") + return False, None + + def queryByTimestampRange(self, cls, minutes): + try: + if not cls or not minutes: + return False, None + + # 验证分钟数参数 + try: + minutes_int = int(minutes) + if minutes_int <= 0: + print(f"Minutes must be positive: {minutes}") + return False, None + except ValueError: + print(f"Invalid minutes format: {minutes}") + return False, None + + # 获取当前时间 + current_datetime = datetime.now() + + # 计算指定分钟数前的时间 + minutes_ago = current_datetime - timedelta(minutes=minutes_int) + + # 查询时间范围内的数据 + data = SessionMaker.query(cls).filter( + cls.datetime >= minutes_ago, + cls.datetime <= current_datetime + ).all() + + if not data: + return False, None + + # 格式化结果为数据列表 + data_list = [] + for item in data: + # 删除SQLAlchemy实例状态属性 + if '_sa_instance_state' in item.__dict__: + del item.__dict__['_sa_instance_state'] + data_list.append(item.__dict__) + + return True, data_list + except Exception as e: + print(f"queryByTimestampRange error: {e}") + return False, None + + def queryByAll(self, cls): + try: + if not cls: + return False, None + dataAll = SessionMaker.query(cls).all() + if dataAll is None: + return False, None + dataList = list() + for data in dataAll: + if '_sa_instance_state' in data.__dict__: + del data.__dict__['_sa_instance_state'] + dataList.append(data.__dict__) + return True, dataList + except Exception as e: + return False, None + + def updateById(self, cls, _id, _data): + try: + if not cls or not _id or not _data: + return False, None + data = SessionMaker.query(cls).filter_by(id=_id).first() + for k, v in _data.items(): + if k == '_sa_instance_state': + continue + if k not in data.__dict__: + continue + if data.__dict__[k] == v: + continue + setattr(data, k, v) + SessionMaker.commit() + if "id" in _data: + _data = SessionMaker.query(cls).get(_data["id"]) + else: + _data = SessionMaker.query(cls).get(_id) + return True, data.__dict__ + except Exception as e: + return False, None + finally: + SessionMaker.close() + + def deleteById(self, cls, _id): + try: + if not _id: + return False, None + data = SessionMaker.query(cls).filter_by(id=_id).first() + if not data: + return False, None + SessionMaker.delete(data) + SessionMaker.commit() + return True, _id + except Exception as e: + return False, None + finally: + SessionMaker.close() + + def deleteByIds(self, cls, ids): + try: + if not ids: + return False, None + data = SessionMaker.query(cls).filter(cls.id.in_(ids)).all() + if not data: + return False, None + for item in data: + SessionMaker.delete(item) + SessionMaker.commit() + return True, ids + except Exception as e: + return False, None + finally: + SessionMaker.close() + + def deleteAllTable(self): + try: + self.delete(Product) + except Exception as e: + return False + + def delete(self, cls): + try: + SessionMaker.query(cls).delete() + SessionMaker.commit() + return True + except Exception as e: + return False + finally: + SessionMaker.close() + +Session = Session() diff --git a/mqtt_client.py b/mqtt_client.py new file mode 100644 index 0000000..8948b71 --- /dev/null +++ b/mqtt_client.py @@ -0,0 +1,612 @@ +import paho.mqtt.client as mqtt +import json +import time +import base64 +import socket +import httpx +from config import * +from PySide6.QtCore import Signal, Slot,QObject,QMetaObject,Qt,QTimer +from Manager.product_manager import productManager +from Manager.history_manager import historyManager +#from PySide6.QtNetWork import * +# 定义主题常量 +TOPICFIRST = "v1/cpy/" +TOPICINFOS = "/infos" +TOPICSTATUS = "/devstatus" +TOPICCAL = "/calculation" +TOPICCTRL = "/control" +TOPICREQUEST = "/request" +TOPICPRODUCT = "/product" +TOPICCOLLECT = "/collect" +TOPICRECEIVE = "/receive" +TOPICNOOP = "/noop" + + +DEVICE_CONTROL_TOPIC = "device/control" +class MQTTClient(QObject): + write_data = Signal(str, int) + update_direction = Signal(int, str) + update_motor_globaldev_info = Signal(dict) + update_motor_info = Signal(int, dict) + update_alu_info = Signal(int, dict) + update_wsu_info = Signal(int, dict) + update_osu_info = Signal(int, dict) + update_hsv_info = Signal(int, dict) + get_temperature = Signal(str, int) + calc_init = Signal() + + def __init__(self, device_id): + super().__init__() + self.device_id = device_id + self.local_client = mqtt.Client(client_id = 'controller_' + self.random_string(6)) # 创建本地客户端 + self.remote_client = mqtt.Client(client_id=device_id) # 创建远程客户端 + self.device_client = mqtt.Client(client_id = 'controller_dev_' + self.random_string(6)) # 创建设备客户端 + self.m_clienttimestamp = 0 + self.cur_product_id = "C8111D73-F387-981D-18D5-849816E1793C" + # 设置回调函数 + self.local_client.on_connect = self.on_connect + self.local_client.on_message = self.on_message + self.local_client.on_disconnect = self.on_disconnect + self.remote_client.on_connect = self.on_connect + self.remote_client.on_message = self.on_message + self.remote_client.on_disconnect = self.on_disconnect + self.device_client.on_connect = self.on_dev_connect + self.device_client.on_message = self.on_dev_message + self.device_client.on_disconnect = self.on_disconnect + self.local_client.username_pw_set(USER, PWD) + self.remote_client.username_pw_set("cpy_machine", "tgzz2025") # 设置用户名和密码 + self.device_client.username_pw_set(USER, PWD) # 设置用户名和密码 + self.sportModes = ["fast", "normal", "slow"] + self.sportIndex = 0 + self.noop_timer = QTimer(self) + self.noop_timer.setInterval(10000) + self.noop_timer.timeout.connect(self.send_noop) + self.noop_timer.start() + + self.conn_timer = QTimer(self) + self.conn_timer.setInterval(1000) + self.conn_timer.timeout.connect(self.connTimerHandler) + self.conn_timer.start() + + print("mqtt client init") + + def random_string(self, length=6): + import random + import string + return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) + + def get_emqx_status(self): + """获取EMQX服务状态""" + try: + EMQX_API_KEY = "79df0d17e0a8d2e8" + EMQX_API_SECRET = "9Aaz8KuCxj0wjh7zMYzMioGyT5henEfSBJbx7K7hcFHO" + client = httpx.Client( + base_url='http://127.0.0.1:18083/api/v5', + auth=(EMQX_API_KEY, EMQX_API_SECRET), + timeout=1.0 # 设置超时时间为5秒 + ) + + response = client.get("/nodes") + print("EMQX状态", response.status_code, response.text) + if response.status_code == 200: + nodes = response.json() + if nodes and len(nodes) > 0: + return True + else: + return False + else: + print(f"检查EMQX状态失败: {response.text}") + return False + except Exception as e: + print(f"检查EMQX状态失败: {e}") + return False + + def checkRemoteServer(self, host = '127.0.0.1', port = 1883, timeout=1): + """ + Check if the TCP server is available + :param host: Server IP address or domain name + :param port: Server port number + :param timeout: Connection timeout in seconds + :return: True if the server is available, False otherwise + """ + print(f"Starting to check if {host}:{port} is available") + sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + sock.settimeout(timeout) + try: + result = sock.connect_ex((host, port)) + if result == 0: + print(f"Successfully connected to {host}:{port}") + return True + else: + print(f"Failed to connect to {host}:{port}, error code: {result}") + return False + except Exception as e: + print(f"An exception occurred while connecting to {host}:{port}: {e}") + return False + finally: + sock.close() + + def connTimerHandler(self): + print("check broker") + self.conn_timer.stop() + if self.get_emqx_status() and self.checkRemoteServer(host=LOCALBORKER,port=LOCALPORT): + print("mqtt brokeris ready") + self.connectToBroker() + else: + print("mqtt brokeris not ready") + self.conn_timer.start() + + def connectToBroker(self): + try: + """连接到 MQTT 代理""" + print("connect to broker local ") + self.local_client.connect(host=LOCALBORKER,port=LOCALPORT) # 连接本地 MQTT 服务器 + time.sleep(0.5) + # print("connect to broker remote") + # self.remote_client.connect(host=BORKER,port=PORT) # 连接远程 MQTT 服务器 + time.sleep(0.5) + print("connect to broker local dev") + self.device_client.connect(host=DEVICEBORKER,port=DEVICEPORT) # 连接设备 MQTT 服务器 + time.sleep(0.5) + self.local_client.loop_start() # 开始循环以处理网络流量 + # self.remote_client.loop_start() # 开始循环以处理网络流量 + self.device_client.loop_start() # 开始循环以处理网络流量 + except Exception as e: + print(e) + return + + def on_connect(self, client, userdata, flags, rc): + """连接成功时调用""" + print(f"client {client._client_id} connected to {client.host}") + command_topic = TOPICFIRST + self.device_id + TOPICCTRL + request_topic = TOPICFIRST + self.device_id + TOPICREQUEST + client.subscribe(command_topic) # 订阅命令主题 + client.subscribe(request_topic) # 订阅命令主题 + + def on_disconnect(self, client, userdata, rc): + print(f"client {client._client_id} disconnect from {client.host}") + + def on_dev_connect(self, client, userdata, flags, rc): + """连接成功时调用""" + print(f"client {client._client_id} connected to {client.host}") + client.subscribe("device/status") + client.subscribe("service/status") + # self.write_alu_data("set_status", True) + + def on_message(self, client, userdata, msg): + """处理接收到的消息""" + # print(f"Message received on topic: {msg.topic} Message: {msg.payload.decode()}") + # 解析 JSON + try: + json_obj = json.loads(msg.payload.decode()) + self.handle_message(json_obj) + except json.JSONDecodeError: + print("Failed to decode JSON") + + def on_dev_message(self, client, userdata, msg): + """处理接收到的消息""" + # print(f"Message received on topic: {msg.topic} Message: {msg.payload.decode()}") + # 解析 JSON + try: + json_obj = json.loads(msg.payload.decode()) + if msg.topic == "device/status": + self.handle_dev_message(json_obj) + except json.JSONDecodeError: + print("Failed to decode JSON") + + def handle_dev_status(self, code, status): + if code == "1#MTO": + self.update_motor_info.emit(1, status) + # if 'direction' in status: + # self.update_direction.emit(1, status['direction']) + if code == "2#MTO": + self.update_motor_info.emit(2, status) + # if 'direction' in status: + # self.update_direction.emit(2, status['direction']) + if code == "3#MTO": + self.update_motor_globaldev_info.emit(status) + if code == "1#ALU": + pass + # self.update_alu_info.emit(1, status) + if code == "1#WSU": + self.update_wsu_info.emit(1, status) + if code == "2#WSU": + self.update_wsu_info.emit(2, status) + if code == "1#OSU": + self.update_osu_info.emit(1, status) + if code == "2#OSU": + self.update_osu_info.emit(2, status) + if code == "1#HVS": + self.update_hsv_info.emit(1, status) + if code == "2#HVS": + self.update_hsv_info.emit(2, status) + + def handle_dev_message(self, json_obj): + """处理接收到的 JSON 消息""" + if isinstance(json_obj, dict): + code = json_obj.get("device_code", None) + status = json_obj.get("status", None) + if code and status: + self.handle_dev_status(code, status) + elif isinstance(json_obj, list): + for item in json_obj: + code = item.get("device_code", None) + status = item.get("status", None) + if code and status: + self.handle_dev_status(code, status) + + def handle_message(self, json_obj): + """处理接收到的 JSON 消息""" + print("----------------handle_message:",json_obj) + method = json_obj.get("method") + if method == "noop": + if json_obj.get("type") == "remote": + self.m_clienttimestamp = time.time() + elif method == "follow": + if json_obj.get("value") == "true": + cid = json_obj.get("cid") + print("Follow,",cid) + self.send_current_product(self.cur_product_id) + elif method == "input": + key = json_obj.get("key") + value = json_obj.get("value") + """写入数据""" + self.write_data.emit(key, value) + + elif method == "devinput": + dev = json_obj.get("dev") + dev_index = json_obj.get("dev_index") + scanner = json_obj.get("scanner") + if scanner == "scanner1": + dev_index = 1 + elif scanner == "scanner2": + dev_index = 2 + key = json_obj.get("key") + value = json_obj.get("value") + """写入数据""" + if dev == "voltage": + print("voltage:",key,value) + self.write_voltage_data(dev_index, key, value) + elif dev == "xray" or dev == "power": + print("xray:",key,value) + self.write_voltage_data(dev_index, key, value) + elif dev == "motor": + self.write_motor_data(dev_index, key, value) + elif dev == "device": + self.write_global_dev_data(key, value) + + elif method == "mode": + mode_value = json_obj.get("value") + if mode_value == 1: + self.start_ys(False) + elif mode_value == 2: + self.start_ys(True) + + elif method == "loadProduct": + self.send_products() + + elif method == "insertProduct": + info = json_obj.get("info") + productManager.create(info) + print(f"Inserting Info: {info}") + self.send_products() + + elif method == "updateProduct": + id = json_obj.get("id") + info = json_obj.get("info") + productManager.update(id, info) + self.send_products() + + elif method == "removeProduct": + id = json_obj.get("id") + productManager.delete(id) + self.send_products() + + elif method == "currentProduct": + self.cur_product_id = json_obj.get("id") + print(f"Current product id: {self.cur_product_id}") + self.send_current_product(self.cur_product_id) + self.send_current_product_id(self.cur_product_id) + + elif method == "loadHistoryList": + cid = json_obj.get("cid") + date = json_obj.get("date") + hour = json_obj.get("hour") + print(f"loadHistoryList: {cid}, {date}, {hour}") + self.send_history_list(cid, date, hour) + elif method == "loadHistory": + cid = json_obj.get("cid") + filename = json_obj.get("file_name") + print(f"loadHistory: {cid}, {filename}") + self.send_history(cid, filename) + + elif method == "trend": + cid = json_obj.get("cid") + duration = json_obj.get("duration") + filters = json_obj.get("filters") + # self.send_trend(cid, duration, filters) + + elif method == "temperature": + cid = json_obj.get("cid") + duration = json_obj.get("duration") + self.get_temperature.emit(cid, duration) + + elif method == "calc_init": + self.calc_init.emit() + + elif method == "scan_control": + action = json_obj.get("action") + if action == "start": + self.start_device() + elif action == "stop": + self.pause_device() + + def write_global_dev_data(self, key, value): + if key == "sports_mode": + self.sportIndex = (self.sportIndex + 1) % len(self.sportModes) + value = self.sportModes[self.sportIndex] + print("sports_mode:",value) + data = { + "device_id": 101, + "device_address": 3, + "device_code": "3#MTO", + "command": key, + "value": value + } + + self.publish_device(DEVICE_CONTROL_TOPIC, data, 1) + + def write_voltage_data(self, voltage_index, key, value): + print("value:", value) + value = True if value ==1 else False + data = { + "device_id": voltage_index, + "device_code": f"{voltage_index}#HVS", + "command": "hv_switch", + "value": value + } + print("write_voltage_data:",data) + self.publish_device("device/hvs/control", data, 1) + # self.write_alu_data("set_status", value) + + def write_alu_data(self, key, value): + data = { + "device_id": '1', + "device_code": "1#ALU", + "command": key, # set_status + "value": value + } + print("write_voltage_data:",data) + self.publish_device("device/control", data, 1) + + def write_motor_data(self, motor_index, key, value): + + data = { + "device_address": motor_index, + "device_code": f"{motor_index}#MTO", + "command": key, + "value": value + } + print("write_motor_data:",data) + self.publish_device(DEVICE_CONTROL_TOPIC, data, 1) + + @Slot() + def start_device(self): + self.write_motor_data(1, "switch", 1) + self.write_motor_data(2, "switch", 1) + self.write_voltage_data(1, "switch", 1) + time.sleep(0.1) + self.write_voltage_data(2, "switch", 1) + @Slot() + def pause_device(self): + self.write_motor_data(3, "switch", 0) + self.write_voltage_data(1, "switch", 0) + time.sleep(0.1) + self.write_voltage_data(2, "switch", 0) + @Slot() + def stop_device(self): + self.write_motor_data(1, "emergency_stop", 0) + self.write_motor_data(2, "emergency_stop", 0) + self.write_voltage_data(1, "switch", 0) + time.sleep(0.1) + self.write_voltage_data(2, "switch", 0) + + def arr2Base64(self, arr): + obj = json.dumps(arr) + return base64.b64encode(obj.encode('utf-8')).decode('utf-8') + + def send_temperature_data(self, cid, temp_data): + """发送温度数据""" + temp_data["method"] = "temperature" + temp_data["datetime"] = self.arr2Base64(temp_data["datetime"]) + temp_data["SCANNER1"] = self.arr2Base64(temp_data["SCANNER1"]) + temp_data["SCANNER2"] = self.arr2Base64(temp_data["SCANNER2"]) + self.publish_rev_cpy(cid, temp_data) + + def safe_mean(self, lst): + non_zero = [x for x in lst if x != 0] + return sum(non_zero) / len(non_zero) if non_zero else 0 + def send_trend(self, cid, duration, filters): + print("===filters",filters) + """发送趋势数据""" + duration = 5000 + obj = historyManager.getTrend(duration) + keys_to_extract = [ + "WtOSC", "WtINS", "WtISC", "EccentricityINS", + "EccentricityOSC", "EccentricityISC", "DmALL", "DmCORE" + ] + extracted_data = {key: [] for key in keys_to_extract} + datetime_list = [] + for item in obj: + dt = item['datetime'] + datetime_list.append(dt.strftime("%Y-%m-%d %H:%M:%S")) + info_dict = json.loads(item['info']) + for key in keys_to_extract: + value = info_dict[key] + if isinstance(value, list): + extracted_data[key].append(self.safe_mean(value)) + else: + extracted_data[key].append(value) + data = dict() + data["method"] = "trend" + data["datetime"] = self.arr2Base64(datetime_list) + for key in keys_to_extract: + data[key] = self.arr2Base64(extracted_data[key]) + self.publish_rev_cpy(cid, data) + + def send_history_list(self, cid, date, hour): + """发送历史记录列表""" + data = historyManager.getDateTimes(date, hour) + obj = dict() + obj["method"] = "loadHistoryList" + obj["filenames"] = data + self.publish_rev_cpy(cid, obj) + + def send_history(self, cid, data_time_str): + data = historyManager.getInfoByDatetime(data_time_str) + print("====================",data) + """发送历史记录""" + obj = dict() + obj["method"] = "loadHistory" + obj["info"] = data["info"] + self.publish_rev_cpy(cid, obj) + # obj["info"] = { + # "WtOSC": [0.93, 0.86, 0.84, 0.81, 0.88, 0.92, 0.87, 0.79], + # "WtISC": [0.82, 0.76, 1.03, 0.96, 1.05, 0.84, 0.77, 0.89], + # "WtINS": [6.96, 6.57, 11.33, 13.54, 11.27, 6.47, 5.88, 7.62], + # "WtALL": [8.50, 8.20, 13.20, 15.32, 13.21, 8.22, 7.52, 9.30], + # "AngOSC": [304.75, 225.00, 21.88], + # "AngINS": [205.50, 135.00, 274.23], + # "AngISC": [248.50, 78.75, 301.21], + # "AngALL": [248.50, 135.00, 286.10], + # "DmCORE": [18.69, 14.54, 18.85], + # "DmALL": [38.21, 40.16, 36.27], + # "DmCOREDeviation": 2, + # "DmALLDeviation": 3, + # "AvgINS": 8.82, + # "AvgOSC": 0.95, + # "AvgISC": 0.88, + # "AvgALL": 9.63, + # "MinISC": 0.96, + # "MinOSC": 0.82, + # "MinINS": 5.89, + # "MinALL": 7.51, + # "EccentricINS": 0.96, + # "EccentricOSC": 2.04, + # "EccentricISC": 3.22, + # "EccentricALL": 8.82, + # "EccentricityINS": 16.043, + # "EccentricityOSC": 21.136, + # "EccentricityISC": 43.253, + # "EccentricityALL": 43.223, + # "ConcentricityALL" : 21.15, + # "ConcentricityINS" : 21.35, + # "ConcentricityOSC" : 11.43, + # "ConcentricityISC" : 6.51, + # "ConcentricityDeviationALL": 21.26, + # "ConcentricityDeviationINS": 21.26, + # "ConcentricityDeviationOSC": 11.65, + # "ConcentricityDeviationISC": 6.55, + # "EllipticityDmCORE": 6.53, + # "EllipticityDmALL": 9.61, + # "Volatility": [0.291, 0.188, 0.414], + # "EdgesA": [42.53, 41.66, 52.93, 53.28, 72.88, 77.58, 88.97, 81.19], + # "EdgesB": [38.36, 43.58, 51.69, 57.92, 71.64, 77.23, 85.77, 82.01] + # } + + + def publish_device(self, topic, data, qos=1): + json_data = json.dumps(data) # 将数据转换为 JSON 字符串 + self.device_client.publish(topic, json_data, qos) # 发布数据到本地 + + def publish_cpy_server(self, topicname, data, qos=0): + + self.publish_local(topicname, data, qos) # 发布数据到本地 + # if self.client_alive(): # 检查客户端是否存活 + # self.publish_remote(topicname, data, qos) # 如果存活,发布数据到远程 + + def publish_cpy(self, topicname, data, qos=0): + topicname = TOPICFIRST + self.device_id + topicname # 构建完整的主题名称 + self.publish_local(topicname, data, qos) # 发布数据到本地 + # if self.client_alive(): # 检查客户端是否存活 + # self.publish_remote(topicname, data, qos) # 如果存活,发布数据到远程 + + def publish_rev_cpy(self, cid, data, qos = 1): + topicname = TOPICFIRST + cid + TOPICRECEIVE # 构建完整的主题名称 + # print("topicname:",topicname) + self.publish_local(topicname, data, qos) # 发布数据到本地 + # if self.client_alive(): # 检查客户端是否存活 + # self.publish_remote(topicname, data, qos) # 如果存活,发布数据到远程 + # print("json_data:",data) + + def publish_local(self, topic, data, qos = 0): + json_data = json.dumps(data) # 将数据转换为 JSON 字符串 + self.local_client.publish(topic, json_data, qos) # 发布数据到本地 + # print(f"Published to local: {topic} -> {json_data}") + + def publish_remote(self, topic, data, qos = 0): + pass + # json_data = json.dumps(data) # 将数据转换为 JSON 字符串 + # self.remote_client.publish(topic, json_data, qos) # 发布数据到远程 + + def send_collect_data(self, data): + self.publish_cpy(TOPICCOLLECT, data, 1) # 发布 + + def send_kneed(self, data): + # print("TOPICCAL:",data) + self.publish_cpy(TOPICCAL, data, 1) # 发布计算结果 + + def send_deviceinfo(self, data): + + self.publish_cpy(TOPICINFOS, data) # 发布设备信息 + + def client_alive(self): + # 当前时间 + current_time = time.time() # 获取当前时间戳(秒) + # 计算时间差(秒) + seconds_diff = current_time - self.m_clienttimestamp + # 判断时间差是否小于 1 分钟(60 秒) + return seconds_diff <= 60 + + def send_products(self): + """发送产品信息""" + data = dict() + data["current_id"] = self.cur_product_id + data["method"] = "productList" + data["infos"] = productManager.getInfo() + print(f"Current product id: {self.cur_product_id}") + self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息 + + def start_ys(self, flag): + """启动或停止某个功能""" + print(f"Starting YS: {flag}") + + def send_current_product(self, id): + """发送当前产品信息""" + data = productManager.getInfo(id) + if data: + data["method"] = "currentProduct" + self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息 + + def send_current_product_id(self, id): + """发送当前产品ID""" + data = {"method": "currentProductId", "id": id} + + self.publish_cpy(TOPICPRODUCT, data, 1) # 发布设备信息 + + def disconnect_broker(self): + print("disconnect_broker") + self.local_client.disconnect() + self.local_client.loop_stop() + self.remote_client.disconnect() + self.remote_client.loop_stop() + self.device_client.disconnect() + self.device_client.loop_stop() + + def send_noop(self): + """发送空指令""" + data = { + "running": "true", + "running_time": "1h15m" } + self.publish_cpy(TOPICNOOP, data, 1) # 发布设备信息 + diff --git a/powerbus_service.pid b/powerbus_service.pid new file mode 100644 index 0000000..40fb191 --- /dev/null +++ b/powerbus_service.pid @@ -0,0 +1 @@ +2548 \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..e30f46b --- /dev/null +++ b/requirements.txt @@ -0,0 +1,10 @@ +colorzero==2.0 +gpiozero==2.0.1 +paho-mqtt==2.1.0 +pigpio==1.78 +pymodbus==3.8.2 +PySide6==6.8.0.2 +PySide6_Addons==6.8.0.2 +PySide6_Essentials==6.8.0.2 +RPi.GPIO==0.7.1 +shiboken6==6.8.0.2 diff --git a/tcp_modbus.py b/tcp_modbus.py new file mode 100644 index 0000000..956e6db --- /dev/null +++ b/tcp_modbus.py @@ -0,0 +1,217 @@ +import time +import threading +from pymodbus.client import ModbusTcpClient +from PySide6.QtCore import QObject, Signal, Slot, QThread,QTimer +class TCPModbus(QObject): + sig_start = Signal() + sig_pause = Signal() + sig_reset = Signal() + sig_stop = Signal() + def __init__(self, parent=None, host='localhost', port=502, timeout=3, retry_interval=1, max_retries=0): + super().__init__(parent) + """ + 初始化TCPModbus客户端 + :param host: 服务器IP地址 + :param port: 服务器端口 + :param timeout: 超时时间(秒) + :param retry_interval: 重连间隔(秒) + :param max_retries: 最大重连次数,0表示无限重试 + """ + self.host = host + self.port = port + self.timeout = timeout + self.retry_interval = retry_interval + self.max_retries = max_retries + self.client = None + self.is_connected = False + self.is_running = False + self.read_thread = None + self.register_values = {} + self.reconnect_count = 0 + self.reconnect_lock = threading.Lock() + self.button_states = [False] * 10 + + def _connect(self): + """ + 连接到Modbus服务器 + :return: 是否连接成功 + """ + try: + if self.client: + self.client.close() + self.client = ModbusTcpClient(host=self.host, port=self.port, timeout=self.timeout) + self.is_connected = self.client.connect() + if self.is_connected: + print(f"成功连接到Modbus服务器: {self.host}:{self.port}") + self.reconnect_count = 0 + else: + print(f"连接Modbus服务器失败: {self.host}:{self.port}") + return self.is_connected + except Exception as e: + print(f"连接失败: {e}") + self.is_connected = False + return False + + def start(self): + """ + 启动Modbus客户端,开始读取寄存器 + :return: 是否启动成功 + """ + + + self.is_running = True + self.read_thread = threading.Thread(target=self._read_data_loop) + self.read_thread.daemon = True + self.read_thread.start() + return True + + def stop(self): + """ + 停止Modbus客户端 + """ + self.is_running = False + if self.read_thread and self.read_thread.is_alive(): + self.read_thread.join(timeout=1.0) + if self.client: + self.client.close() + self.is_connected = False + print("Modbus客户端已停止") + + def _read_data_loop(self): + """ + 循环读取寄存器的内部方法 + """ + while self.is_running: + if not self.is_connected: + # 连接断开,尝试重连 + with self.reconnect_lock: + if not self.is_connected and self._auto_reconnect(): + print("连成功") + time.sleep(0.5) + continue + + try: + # 这里实现读取寄存器的逻辑 + self.read_data() + time.sleep(0.1) # 每秒读取一次 + except Exception as e: + print(f"读取寄存器出错: {e}") + # 读取错误可能是连接问题,标记为断开以便重连 + self.is_connected = False + time.sleep(0.5) + + def _auto_reconnect(self): + """ + 自动重连机制 + :return: 是否重连成功 + """ + # 只尝试一次重连,避免长时间持有锁 + if self.is_running and (self.max_retries == 0 or self.reconnect_count < self.max_retries): + self.reconnect_count += 1 + + if self._connect(): + return True + + return False + + def read_data(self): + """ + 读取寄存器的方法 + """ + try: + # 读取输入寄存器,起始地址为0,读取10个寄存器 + response = self.client.read_discrete_inputs(address=0, count= 4) + if not response.isError(): + for idx, bit in enumerate(response.bits): + if idx == 3: + # 检测下降沿:从抬起(True)变为按下(False) + previous_state = self.button_states[idx] + current_state = bit + + # 更新当前状态 + self.button_states[idx] = current_state + + # 下降沿检测 + if previous_state == True and current_state == False: + self.control_stop() + print("=================control_stop") + + else: + if bit: + print(f"寄存器 {idx} 的值是 {bit}") + self.button_states[idx] = True + + elif self.button_states[idx]: + self.button_states[idx] = False + if idx == 0: + self.control_start() + print("=================control_start") + elif idx == 1: + self.control_pause() + print("=================control_pause") + elif idx == 2: + self.control_reset() + print("=================control_reset") + + else: + print(f"读取寄存器出错: {response}") + self.is_connected = False + except Exception as e: + print(f"读取寄存器出错: {e}") + self.is_connected = False + + def control_start(self): + self.control_light(9, True) + """ + 控制设备启动 + """ + self.sig_start.emit() + + def control_pause(self): + self.control_light(9, False) + """ + 控制设备暂停 + """ + self.sig_pause.emit() + + def control_reset(self): + """ + 控制设备复位 + """ + self.sig_reset.emit() + + def control_stop(self): + self.control_light(9, False) + """ + 控制设备停止 + """ + self.sig_stop.emit() + + def control_light(self, index, value): + try: + self.client.write_coil(index, value) + except Exception as e: + print(f"写入线圈出错: {e}") + self.is_connected = False + + def get_register_value(self, register_address): + """ + 获取指定寄存器的值 + :param register_address: 寄存器地址 + :return: 寄存器值或None(如果不存在) + """ + return self.register_values.get(register_address) + +if __name__ == '__main__': + # 示例用法 + modbus_client = TCPModbus(host='192.168.8.211', port=502) + if modbus_client.start(): + print("Modbus客户端已启动") + try: + while True: + time.sleep(1) + except KeyboardInterrupt: + print("停止Modbus客户端") + modbus_client.stop() + else: + print("Modbus客户端启动失败") \ No newline at end of file diff --git a/udp_server_enhanced.py b/udp_server_enhanced.py new file mode 100755 index 0000000..52d9318 --- /dev/null +++ b/udp_server_enhanced.py @@ -0,0 +1,553 @@ +import socket +import base64 +import json +import time +import psutil +import struct +import csv +import threading +from collections import defaultdict +from typing import Dict, List, Tuple, Optional +import logging +from config import * +from x_ray_data_processor import processor +from PySide6.QtCore import QObject, Signal, Slot, QThread, QTimer +from scipy.ndimage import gaussian_filter1d +import numpy as np + +# 配置日志 +logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s') +logger = logging.getLogger(__name__) + +# 定义adcDataUnitDef结构体 +class adcDataUnitDef: + def __init__(self): + self.ucCmd = 0 + self.ucAddr = 0 + self.usData = 0 + +# 新增:UDP包头结构定义 (与C端保持一致) +class UDPPacketHeader: + """UDP包头结构""" + MAGIC = 0xAA55 + HEADER_SIZE = 16 # 包头大小 + + def __init__(self, data: bytes): + """ + 从字节数据解析包头 + """ + if len(data) < self.HEADER_SIZE: + raise ValueError("数据长度不足,无法解析包头") + + # 解析包头字段 (小端序) + (self.magic, self.total_size, self.big_packet_id, + self.packet_id, self.total_packets, self.payload_len) = struct.unpack(' bool: + """ + 添加一个包到重组器 + 返回True如果包是新接收的,False如果包已存在 + """ + if packet_id in self.packets: + return False # 包已存在 + + self.packets[packet_id] = payload + self.received_count += 1 + + # 检查是否所有包都已接收 + if self.received_count == self.total_packets: + self._reassemble() + return True + + return True + + def _reassemble(self): + """重组完整数据""" + try: + # 按包序号排序 + sorted_packets = sorted(self.packets.items()) + + # 重组数据 + reassembled_data = b'' + for packet_id, payload in sorted_packets: + reassembled_data += payload + + # 截取到指定长度 + self.data = reassembled_data[:self.total_size] + self.completed = True + + logger.info(f"大包 {self.big_packet_id} 重组完成,大小: {len(self.data)} 字节") + + except Exception as e: + logger.error(f"重组大包 {self.big_packet_id} 时出错: {e}") + + def is_timeout(self) -> bool: + """检查是否超时""" + return time.time() - self.start_time > self.timeout + + def is_completed(self) -> bool: + """检查是否完成重组""" + return self.completed + + def get_data(self) -> Optional[bytes]: + """获取重组后的数据""" + return self.data if self.completed else None + +class UdpServerEnhanced(QThread): + start_cal = Signal(int, bytearray, str, int) # 信号:接收到消息,包含数据、发送者地址和端口 + send_collect_data = Signal(dict) # + update_acquisition_info = Signal(int, dict) + + def __init__(self, ip="0.0.0.0", port=50009, parent=None): + super(UdpServerEnhanced, self).__init__(parent) + self.kill_udp_port(port) + self.ip = ip + self.port = port + self.server_socket = None + self.running = True + self.motor1_direction = "" + self.motor2_direction = "" + + # 新增:分包重组相关属性 + self.reassemblers: Dict[Tuple[Tuple[str, int], int], PacketReassembler] = {} + self.reassembler_lock = threading.Lock() + self.cleanup_thread = None + self.timeout = 1.0 # 1秒超时 + + self.collect_object1 = { + "method" : "scanner1", + "channelA_data" :"base64", + "channelB_data" :"base64", + "intensityA" : 98, + "intensityB" : 98 + } + self.collect_object2 = { + "method" : "scanner2", + "channelA_data" :"base64", + "channelB_data" :"base64", + "intensityA" : 98, + "intensityB" : 98 + } + self.debug_timer = QTimer(self) + self.debug_timer.timeout.connect(self.update_debug_timer) + if YSMODE: + self.debug_timer.start(1000) + + def update_debug_timer(self): + import random + channelA = [random.randint(1, 1000) for _ in range(3000)] + channelB = [random.randint(1, 1000) for _ in range(3000)] + self.collect_object1['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode() + self.collect_object1['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode() + self.collect_object2['channelA_data'] = base64.b64encode(json.dumps(channelA).encode()).decode() + self.collect_object2['channelB_data'] = base64.b64encode(json.dumps(channelB).encode()).decode() + self.send_collect_data.emit(self.collect_object1) + self.send_collect_data.emit(self.collect_object2) + + def kill_udp_port(self, port): + for proc in psutil.process_iter(): + try: + for conn in proc.connections(kind='udp'): + if conn.laddr.port == port: + print(f" PID={proc.pid}, procname={proc.name()}") + proc.kill() + except psutil.AccessDenied: + continue + + def packet_crc(self, data): + usSum = 0 + for byte in data: + usSum += byte + return usSum & 0xFFFF # 确保返回值为16位 + + def handle_sample_data(self, data): + # 确保数据长度是4的倍数 + if len(data) % 4 != 0: + raise ValueError("Data length must be a multiple of 4") + + # 使用列表推导式来简化代码 + unpacked_data = [struct.unpack_from(' len(binary_data): + print("offset:", offset, "data_len:", len(data_points)) + break + channel_A.append(struct.unpack(' bool: + """检查数据包是否以UDP_PACKET_MAGIC开头""" + if len(data) < 2: + return False + magic = struct.unpack(' Optional[PacketReassembler]: + """获取或创建包重组器""" + key = (addr, header.big_packet_id) + + with self.reassembler_lock: + # 检查是否已存在 + if key in self.reassemblers: + reassembler = self.reassemblers[key] + + # 检查是否超时 + if reassembler.is_timeout(): + logger.warning(f"大包 {header.big_packet_id} 超时,丢弃") + del self.reassemblers[key] + return None + + return reassembler + + # 创建新的重组器 + reassembler = PacketReassembler( + header.big_packet_id, + header.total_size, + header.total_packets, + addr, + self.timeout + ) + + self.reassemblers[key] = reassembler + logger.info(f"创建新的大包重组器: ID={header.big_packet_id}, " + f"大小={header.total_size}, 包数={header.total_packets}, 来源={addr}") + + return reassembler + + + def daq_data_packet_ack(self, ip, pid): + try: + # 构建命令数据包 + # 命令格式: AA CC 01 XX XX XX XX + # 其中XX XX XX XX为采集时长,小端格式 + command = bytearray([0xAA, 0xCC, 0x03]) + + # 将时长转换为4字节小端格式 + command.extend(struct.pack(' 100: + #gause filter + channelA_filtered = gaussian_filter1d(channelA, 0.5) + channelA = np.array(channelA_filtered).tolist() + channelB_filtered = gaussian_filter1d(channelB, 0.5) + channelB = np.array(channelB_filtered).tolist() + #save data to csv file + filename = f'/home/admin/PythonPro/TGX_PYSERVER/datas/data{time.strftime("%Y%m%d%H%M%S")}.csv' + with open(filename, 'w', newline='') as f: + writer = csv.writer(f) + writer.writerow(['INDEX', 'CH1', 'CH2']) + writer.writerows(zip(index_col, channelA, channelB)) + + channelA_average = np.mean(channelA) + channelB_average = np.mean(channelB) + + if COREECTMODE and channelA_average > 5000 and channelB_average > 5000: + try: + _channelA,_channelB,corrected = self.correct_data(filename) + if corrected: + file_content = corrected + channelA = _channelA + channelB = _channelB + except Exception as e: + print(f"Error correcting data: {e}") + channelA_json = json.dumps(channelA) + channelB_json = json.dumps(channelB) + # print("================channelA_json",channelA_json) + # print("================channelB_json",channelB_json) + channelA_bytes = channelA_json.encode('utf-8') + channelB_bytes = channelB_json.encode('utf-8') + + + if ip_address == "192.168.100.236": + self.collect_object1["method"] = "scanner1" + if channelA_average < 5000 or channelB_average < 5000: + print("xray low idensity") + else: + self.start_cal.emit(1, file_content, direction, row_count) + print("====emit direction[1]:", direction) + self.collect_object1['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8') + self.collect_object1['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8') + self.send_collect_data.emit(self.collect_object1) + elif ip_address == "192.168.100.237": + self.collect_object2["method"] = "scanner2" + if channelA_average < 5000 or channelB_average < 5000: + print("xray low idensity") + else: + self.start_cal.emit(2, file_content, direction, row_count) + print("====emit direction[2]:", direction) + self.collect_object2['channelA_data'] = base64.b64encode(channelA_bytes).decode('utf-8') + self.collect_object2['channelB_data'] = base64.b64encode(channelB_bytes).decode('utf-8') + self.send_collect_data.emit(self.collect_object2) + + except OSError as e: + print(f"Error handle_data_point: {e}") # 记录错误信息 + + def stop(self): + """停止 UDP 服务器""" + self.running = False + if self.server_socket: + self.server_socket.close() + self.wait() # 等待线程结束 + + def send_message(self, message, ip, port): + """发送消息到指定的 IP 和端口""" + if self.server_socket: + self.server_socket.sendto(message.encode(), (ip, port)) + + def __del__(self): + self.stop() # 确保在对象销毁时停止服务器 diff --git a/x_ray_data_processor.py b/x_ray_data_processor.py new file mode 100644 index 0000000..bb2ef13 --- /dev/null +++ b/x_ray_data_processor.py @@ -0,0 +1,458 @@ +""" +X光数据处理模块 +包含自动选择圆弧区间、拟合和数据校正等功能 +""" + +import numpy as np +import pandas as pd +from scipy.optimize import curve_fit +from scipy.ndimage import gaussian_filter1d +import os.path +import struct + +from scipy.signal import argrelextrema, savgol_filter + +class XRayDataProcessor: + def __init__(self): + """初始化X光数据处理器""" + # 初始化数据存储 + self.data = None + self.index_data = None + self.channel_data = None + self.smoothed_data = None + self.derivative_data = None + self.results = None + self.selected_spans = {'CH1': [], 'CH2': []} + + def load_data(self, filepath): + """加载CSV数据文件""" + try: + self.data = pd.read_csv(filepath) + self.channel_data = { + 'CH1': self.data['CH1'].values.astype(float), + 'CH2': self.data['CH2'].values.astype(float) + } + + try: + self.index_data = self.data['INDEX'].values.astype(int) + except: + self.index_data = np.arange(len(self.channel_data['CH1'])) + + # 计算平滑数据和导数 + self.calculate_smoothed_and_derivative() + + return True + except Exception as e: + print(f"加载数据出错: {str(e)}") + return False + + def calculate_smoothed_and_derivative(self, sigma=2.0): + """计算高斯滤波平滑数据和一阶导数""" + try: + if self.channel_data is None: + return False + + # 为每个通道计算平滑数据和导数 + self.smoothed_data = {} + self.derivative_data = {} + + for ch in self.channel_data.keys(): + # 使用高斯滤波平滑数据 + smoothed = gaussian_filter1d(self.channel_data[ch], sigma) + self.smoothed_data[ch] = smoothed + + # 计算平滑数据的一阶导数 + derivative = np.gradient(smoothed, self.index_data) + self.derivative_data[ch] = derivative + + return True + except Exception as e: + print(f"计算平滑数据和导数出错: {str(e)}") + return False + + def find_derivative_peaks(self, deriv_data, sigma=5, peak_threshold=0.3): + """ + 精准找出一阶导数绝对值的主要极值点 + :param deriv_data: 一阶导数数组(CH1或CH2的一阶导数) + :param sigma: 平滑窗口大小,建议5-11,越大去噪越强 + :param peak_threshold: 峰值过滤比例(0-1),越大越严格 + :return: 峰值索引列表,按强度从高到低排序 + """ + # 1. 平滑一阶导数,消除噪声 + deriv_smooth = savgol_filter(deriv_data, window_length=sigma, polyorder=2) + + # 2. 取绝对值,让正负跳变都变成正向峰值 + deriv_abs = np.abs(deriv_smooth) + + # 3. 找所有局部极大值点 + all_peaks_idx = argrelextrema(deriv_abs, np.greater)[0] + if len(all_peaks_idx) == 0: + return [] + + # 4. 按峰值强度排序,过滤掉小噪声峰 + peak_values = deriv_abs[all_peaks_idx] + sorted_idx = all_peaks_idx[np.argsort(peak_values)[::-1]] # 从大到小排序 + + # 只保留强度超过「最大峰值×阈值」的主峰值 + max_peak = deriv_abs.max() + valid_peaks = [idx for idx in sorted_idx if deriv_abs[idx] >= max_peak * peak_threshold] + + max4 = sorted([int(x) for x in valid_peaks[:4]]) + print(max4) + + return max4 # 最多返回前4个最强峰 + + def auto_select_arcs(self): + """自动选择两侧的圆弧部分,对CH1和CH2通道分别处理""" + if self.index_data is None or len(self.index_data) < 10: + print("无可用数据") + return False + + try: + # 清除之前的选择 + self.selected_spans = {'CH1': [], 'CH2': []} + + # 确保已计算平滑数据和导数 + if self.derivative_data is None: + self.calculate_smoothed_and_derivative() + + if self.derivative_data is None: + print("无法计算导数数据") + return False + + # 为两个通道分别寻找区间 + ch1_spans = self._find_spans_for_channel('CH1') + ch2_spans = self._find_spans_for_channel('CH2') + + # 为每个通道存储各自的区间 + success_count = 0 + + if ch1_spans: + self.selected_spans['CH1'] = ch1_spans + print(f"已为CH1通道选择{len(ch1_spans)}个区间") + success_count += 1 + + if ch2_spans: + self.selected_spans['CH2'] = ch2_spans + print(f"已为CH2通道选择{len(ch2_spans)}个区间") + success_count += 1 + + if success_count == 0: + # 两个通道都失败 + print("两个通道均未能找到合适的区间,请尝试手动选择") + return False + + return True + + except Exception as e: + print(f"自动选择过程中出错: {str(e)}") + return False + + def _find_spans_for_channel(self, channel): + """为指定通道寻找合适的区间""" + derivative = self.derivative_data[channel] + n = len(self.index_data) + + abs_derivative = np.abs(derivative) + + potential_extremes = self.find_derivative_peaks(abs_derivative) + + # 至少有两个极值点,选择第一个和最后一个 + p1 = potential_extremes[0] + p2 = potential_extremes[-1] + + # 计算区间边界: [p1*0.2, p1*0.9], [(n-p2)*0.1+p2, (n-p2)*0.7+p2] + left_start_idx = max(0, int(p1 * 0.1)) + left_end_idx = min(n-1, int(p1 * 0.99)) + + right_start_idx = min(n-1, int((n - p2) * 0.01 + p2)) + right_end_idx = min(n-1, int(n - (n - p2) * 0.1)) + + # 转换为INDEX值 + left_span = (self.index_data[left_start_idx], self.index_data[left_end_idx]) + right_span = (self.index_data[right_start_idx], self.index_data[right_end_idx]) + + # 记录找到的极值点信息 + print(f"{channel} 通道找到极值点: p1={p1}, p2={p2},区间: 左=({left_start_idx},{left_end_idx}), 右=({right_start_idx},{right_end_idx})") + + spans = [left_span, right_span] + return spans + + def set_manual_spans(self, spans, channel=None): + """手动设置区间列表 + + 参数: + spans: 区间列表或字典 + channel: 指定通道,None表示设置所有通道 + """ + if channel is not None and channel in ['CH1', 'CH2']: + self.selected_spans[channel] = spans + else: + # 如果是字典格式,分别设置每个通道 + if isinstance(spans, dict): + for ch in ['CH1', 'CH2']: + if ch in spans: + self.selected_spans[ch] = spans[ch] + else: + # 否则设置所有通道为相同的区间 + self.selected_spans = {'CH1': spans, 'CH2': spans} + return True + + def fit_data(self): + """根据选择的区间拟合数据""" + # 检查是否有任何通道选择了区间 + if not any(self.selected_spans.values()): + print("请先选择至少一个数据区间") + return False + + try: + self.results = {} + + # 为每个通道分别进行拟合 + for ch in ['CH1', 'CH2']: + if not self.selected_spans[ch]: + print(f"{ch}通道未选择区间,跳过拟合") + continue + + print(f"{ch}通道选择的区间: {self.selected_spans[ch]}") + + # 合并当前通道所有选中的数据点 + selected_indices = [] + for span in self.selected_spans[ch]: + indices_in_span = np.where((self.index_data >= span[0]) & (self.index_data <= span[1]))[0] + selected_indices.extend(indices_in_span) + + # 确保索引是唯一的并且排序 + selected_indices = sorted(list(set(selected_indices))) + + if len(selected_indices) < 10: + print(f"{ch}通道选择的数据点太少({len(selected_indices)}个),无法进行可靠拟合") + continue + + # 提取选中区间的数据 + selected_index_data = self.index_data[selected_indices] + selected_channel_data = self.channel_data[ch][selected_indices] + + # 分析数据 + self.results[ch] = self._analyze_channel(ch, selected_channel_data, selected_index_data) + + # 计算拟合曲线(对全部数据范围) + full_indices = self.index_data + params = self.results[ch]['params_opt'] + self.results[ch]['Q_fit_full'] = self._model(full_indices, *params) + self.results[ch]['index_full'] = full_indices + + # 检查是否有成功拟合的通道 + if not self.results: + print("没有通道成功进行拟合") + return False + + self._print_fit_results() + return True + + except Exception as e: + print(f"拟合过程中出错: {str(e)}") + return False + + def _model(self, index, Q0, mu, offset): + """X光束衰减模型""" + R = 65.0 + t = 0.8 + factor = 0.04 + X = factor * (index - offset) + X_clip = np.clip(X, -64.0, 64.0) + term1 = np.sqrt((R + t)**2 - X_clip**2) + term2 = np.sqrt(R**2 - X_clip**2) + L = 2 * (term1 - term2) + return Q0 * np.exp(-mu * L) + + def _analyze_channel(self, channel_name, Q_data, index_data): + """分析单个通道的数据""" + # 参数设置 + initial_guess = [np.max(Q_data)*1.5, 0.4, np.max(index_data) * 0.5] + bounds = ( + [np.max(Q_data), 0.3, np.max(index_data) * 0.2], + [2*np.max(Q_data), 0.5, np.max(index_data) * 0.8] + ) + + # 执行拟合 + params_opt, params_cov = curve_fit( + self._model, index_data, Q_data, + p0=initial_guess, + bounds=bounds, + maxfev=10000 + ) + + # 结果存储 + return { + 'params_opt': params_opt, + 'params_cov': params_cov + } + + def _print_fit_results(self): + """打印拟合结果参数""" + print("双通道拟合参数对比:") + + for ch in ['CH1', 'CH2']: + p = self.results[ch]['params_opt'] + e = np.sqrt(np.diag(self.results[ch]['params_cov'])) + print(f"\n{ch}通道:") + print(f"Q0 = {p[0]:.1f} ± {e[0]:.1f}") + print(f"μ = {p[1]:.6f} ± {e[1]:.6f} mm⁻¹") + print(f"offset = {p[2]:.1f} ± {e[2]:.1f}") + + def correct_data(self): + """根据拟合曲线校正数据""" + if self.results is None: + print("请先进行数据拟合") + return None + + try: + # 根据最大拟合值计算校正系数 + correction_factors = {} + corrected_data = {} + + for ch in ['CH1', 'CH2']: + # 获取当前通道的拟合结果 + res = self.results[ch] + + # 计算全部数据范围的拟合值 + full_fit_values = res['Q_fit_full'] # 已经是全部数据范围的拟合值 + + # 计算拟合曲线的最大值Q1 + Q1 = np.max(full_fit_values) + + # 为每个点计算校正系数,避免除以0 + safe_fit_values = np.maximum(full_fit_values, 0.1) # 避免除以0 + + # 计算校正系数:拟合值/最大拟合值 + factors = safe_fit_values / Q1 + + # 存储校正系数和校正后的数据 + correction_factors[ch] = factors + corrected_data[ch] = self.channel_data[ch] / factors + + return { + 'index_data': self.index_data, + 'original_data': self.channel_data, + 'corrected_data': corrected_data + } + + except Exception as e: + print(f"数据校正过程中出错: {str(e)}") + return None + + def save_corrected_data(self, corrected_result, output_path, trim_edges=True, trim_amount=200): + """保存校正后的数据 + + 参数: + corrected_result: correct_data()方法的返回结果 + output_path: 输出文件路径 + trim_edges: 是否裁剪边缘数据 + trim_amount: 裁剪数量,头尾各裁剪的点数 + """ + try: + if corrected_result is None: + print("没有校正数据可保存") + return None,None,None + + index_data = corrected_result['index_data'] + original_data = corrected_result['original_data'] + corrected_data = corrected_result['corrected_data'] + + # 检查数据长度 + data_length = len(index_data) + + # 如果需要裁剪但数据不足 + if trim_edges and data_length <= 2 * trim_amount: + print(f"数据总长度为{data_length}点,不足以去掉头尾各{trim_amount}点。") + print("将保存全部数据。") + trim_edges = False + + # 确定数据范围 + if trim_edges: + start_idx = trim_amount + end_idx = data_length - trim_amount + else: + start_idx = 0 + end_idx = data_length + + # 创建要保存的数据 + save_data = { + 'INDEX': index_data[start_idx:end_idx] + } + + # 添加原始数据和校正后的数据 + for ch in corrected_data.keys(): + save_data[f'{ch}_原始'] = original_data[ch][start_idx:end_idx] + save_data[f'{ch}'] = corrected_data[ch][start_idx:end_idx] + channel_A = [] + channel_B = [] + for value in save_data['CH1']: + channel_A.append(int(value)) + for value in save_data['CH2']: + channel_B.append(int(value)) + + # print("channel_A",channel_A) + file_content = bytearray() + for i in range (len(channel_A)): + file_content.extend(struct.pack('