def fromfile(cls, path): """Read a bloom filter from file-object `f' serialized with ``BloomFilter.tofile''. """ f = QFile(path) if not f.open(QIODevice.ReadOnly): raise ValueError("unable to open file " + path) data = QDataStream(f) file_fmt = data.readBytes() if file_fmt != cls.FILE_FMT: raise ValueError('unexpected file format') error_rate = data.readFloat() num_slices = data.readInt() bits_per_slice = data.readInt() capacity = data.readInt() count = data.readInt() bitarray = QBitArray() filter = cls(1) # Bogus instantiation, we will `_setup'. filter._setup(error_rate, num_slices, bits_per_slice, capacity, count) filter.bitarray = QBitArray() data >> filter.bitarray return filter
def readResponse(self): # 收命令,要做的事情, stream = QDataStream(self.socket) print('--------------------') print('服务器响应') stream.setVersion(QDataStream.Qt_5_7) while True: self.nextBlockSize = 0 if self.nextBlockSize == 0: if self.socket.bytesAvailable() < SIZEOF_UINT16: print('没有内容了') break self.nextBlockSize = stream.readUInt16() else: print('错误') # 客户端主动断开时,去掉字典中的对应,在这里做一部分操作。 # 客户端主动断开的时候,要将其从self.myParent.sockeIdToSocketDict self.myParent.fixIdToSocketIdDict 中删掉 break if self.socket.bytesAvailable() < self.nextBlockSize: print("错误2") if (not self.socket.waitForReadyRead(60000) or self.socket.bytesAvailable() < self.nextBlockSize): break state = stream.readQString() # 读命令 sendModel print('state==' + state) if state == 'SENDFILE': filename = stream.readQString() # 读文件名 fileSize = stream.readInt() # 读文件大小 with open('../TEST/' + filename, 'ab') as f: while self.nextBlockSize > 0: fileBytes = stream.readBytes() # 读文件部分字节 f.write(fileBytes) print(fileBytes.__len__()) self.nextBlockSize = stream.readUInt64() print('self.nextBlockSize:' + str(self.nextBlockSize)) state = stream.readQString() filename = stream.readQString() # 读文件名 fileSize = stream.readInt() # 读文件大小 print('filename:' + filename) print('fileSize:' + str(fileSize)) elif state == 'test': print(stream.readQString()) elif state == 'ORDER': # 收到一条命令 要执行的命令 order = stream.readQString() # 读是什么命令 if order: # shou dao doThing self.doSomeThing.emit(order)
def receiveMessage(self): print("received smtg") for s in self.connections: if s.bytesAvailable() > 0 : stream = QDataStream(s) stream.setVersion(QDataStream.Qt_4_9) if s.nextBlockSize == 0: if s.bytesAvailable() < SIZEOF_UINT32: return size = stream.readUInt32() print("size", size) s.nextBlockSize = size if s.bytesAvailable() < s.nextBlockSize: return header = stream.readUInt32() print("header", header) if header == 0: # QString textFromClient = stream.readQString() print(f"received '{textFromClient}' from {s}") answer = textFromClient + " Back at you!" if "CLOSE" in textFromClient: self.parent.quit() if header == 1: # QImage img_bytes = stream.readBytes() img = QImage() img.loadFromData(img_bytes) img.save("serverQt.jpg") print(f"received an image from {s}") answer = "image saved in the server on serverQt.jpg" s.nextBlockSize = 0 # BACK AT CLIENT self.sendMessage(answer, s) s.nextBlockSize = 0
class QmyMainWindow(QMainWindow): def __init__(self, parent=None): super().__init__(parent) #调用父类构造函数,创建窗体 self.ui = Ui_MainWindow() #创建UI对象 self.ui.setupUi(self) #构造UI界面 self.ui.groupBox.setEnabled(False) self.ui.actSaveALL.setEnabled(False) self.ui.actReadALL.setEnabled(False) self.__testFileName = "" self.__typeSize = { "char": 1, "bool": 1, "int8": 1, "uint8": 1, "int16": 2, "uint16": 2, "int32": 4, "uint32": 4, "int64": 8, "uint64": 8, "int": 4, "uint": 4, "float": 4, "single": 4, "double": 8 } ## ==============自定义功能函数============ def __iniWrite(self): ##开始写文件操作 self.fileDevice = QFile(self.__testFileName) #创建文件对象 if not self.fileDevice.open(QIODevice.WriteOnly): del self.fileDevice #删除对象 return False self.fileStream = QDataStream(self.fileDevice) self.fileStream.setVersion(QDataStream.Qt_5_12) #设置流版本号,写入和读取的版本号要兼容 if self.ui.radio_BigEndian.isChecked(): self.fileStream.setByteOrder(QDataStream.BigEndian) else: self.fileStream.setByteOrder(QDataStream.LittleEndian) if self.ui.radio_Single.isChecked(): #必须要设置,float和double都按照这个精度 self.fileStream.setFloatingPointPrecision( QDataStream.SinglePrecision) else: self.fileStream.setFloatingPointPrecision( QDataStream.DoublePrecision) return True def __delFileStream(self): ##结束写文件操作 self.fileDevice.close() del self.fileStream del self.fileDevice def __iniRead(self): ##开始写文件操作 if not QFile.exists(self.__testFileName): QMessageBox.critical(self, "错误", "文件不存在") return False self.fileDevice = QFile(self.__testFileName) #创建文件对象 if not self.fileDevice.open(QIODevice.ReadOnly): del self.fileDevice #删除对象 return False self.fileStream = QDataStream(self.fileDevice) self.fileStream.setVersion(QDataStream.Qt_5_12) #设置版本号,写入和读取的版本号要兼容 if self.ui.radio_BigEndian.isChecked(): self.fileStream.setByteOrder(QDataStream.BigEndian) else: self.fileStream.setByteOrder(QDataStream.LittleEndian) if self.ui.radio_Single.isChecked(): #必须要设置,float和double都按照这个精度 self.fileStream.setFloatingPointPrecision( QDataStream.SinglePrecision) else: self.fileStream.setFloatingPointPrecision( QDataStream.DoublePrecision) return True ## ==========由connectSlotsByName() 自动连接的槽函数================== @pyqtSlot() def on_btnFile_clicked(self): curPath = QDir.currentPath() #获取系统当前目录 title = "选择文件" #对话框标题 filt = "原始数据文件(*.raw)" #文件过滤器 fileName, flt = QFileDialog.getSaveFileName(self, title, curPath, filt) if (fileName == ""): return self.__testFileName = fileName #测试用文件 self.ui.editFilename.setText(fileName) self.ui.groupBox.setEnabled(True) self.ui.actSaveALL.setEnabled(True) self.ui.actReadALL.setEnabled(True) @pyqtSlot() ##写 int8 def on_btnInt8_Write_clicked(self): Value = self.ui.spin_Int8.value() # Python的int类型 if self.__iniWrite(): try: bts = struct.pack('b', Value) # 'b'=signed char=int8 ## writeRawData(self, bytes) -> int self.fileStream.writeRawData(bts) except Exception as e: print(e) QMessageBox.critical(self, "写int8过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 int8 def on_btnInt8_Read_clicked(self): if self.__iniRead(): ##readRawData(self, int) -> bytes try: bts = self.fileStream.readRawData(self.__typeSize["int8"]) ## unpack(fmt, buffer) -> (v1, v2, ...) Value, = struct.unpack('b', bts) # 'b'=signed char=int8 self.ui.edit_Int8.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读int8过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 uint8 def on_btnUInt8_Write_clicked(self): Value = self.ui.spin_UInt8.value() if self.__iniWrite(): try: bts = struct.pack('B', Value) # 'B'=unsigned char=uint8 self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写uint8过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 uint8 def on_btnUInt8_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["uint8"]) Value, = struct.unpack('B', bts) # 'B'=unsigned char=uint8 self.ui.edit_UInt8.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读uint8过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 int16 def on_btnInt16_Write_clicked(self): Value = self.ui.spin_Int16.value() if self.__iniWrite(): try: bts = struct.pack('h', Value) # 'h'=short, 2字节,=int16 self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写int16过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 int16 def on_btnInt16_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["int16"]) Value, = struct.unpack('h', bts) # 'h'=short, 2字节,=int16 self.ui.edit_Int16.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读int16过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 uint16 def on_btnUInt16_Write_clicked(self): Value = self.ui.spin_UInt16.value() if self.__iniWrite(): try: bts = struct.pack('H', Value) # 'H'=unsigned short, 2字节=uint16 self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写uint16过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 uint16 def on_btnUIn16_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["uint16"]) Value, = struct.unpack('H', bts) # 'H'=unsigned short, 2字节,=uint16 self.ui.edit_UInt16.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读uint16过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 int32 def on_btnInt32_Write_clicked(self): Value = self.ui.spin_Int32.value() if self.__iniWrite(): try: bts = struct.pack('>l', Value) # '>l'=大字节序 int32 self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写int32过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 int32 def on_btnInt32_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["int32"]) Value, = struct.unpack('>l', bts) # '>l'= 大字节序int32 self.ui.edit_Int32.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读int32过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 int64 def on_btnInt64_Write_clicked(self): Value = self.ui.spin_Int64.value() #Python的int类型 if self.__iniWrite(): try: bts = struct.pack('q', Value) # 'q'= long long, 8字节=int64 self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写int64过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 int64 def on_btnInt64_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["int64"]) Value, = struct.unpack('q', bts) # 'q'= long long, 8字节=int64 self.ui.edit_Int64.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读int64过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 int def on_btnInt_Write_clicked(self): Value = self.ui.spin_Int.value() if self.__iniWrite(): try: bts = struct.pack('i', Value) # 'i'= int, 4字节=int self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写int过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 int def on_btnInt_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["int"]) Value, = struct.unpack('i', bts) # 'i'= int, 4字节=int self.ui.edit_Int.setText("%d" % Value) except Exception as e: QMessageBox.critical(self, "读int过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 bool def on_btnBool_Write_clicked(self): Value = self.ui.chkBox_In.isChecked() if self.__iniWrite(): bts = struct.pack('?', Value) # '?'= bool, 1字节 self.fileStream.writeRawData(bts) self.__delFileStream() @pyqtSlot() ##读 bool def on_btnBool_Read_clicked(self): if self.__iniRead(): bts = self.fileStream.readRawData(self.__typeSize["bool"]) Value, = struct.unpack('?', bts) # '?'= bool, 1字节 self.ui.chkBox_Out.setChecked(Value) self.__delFileStream() @pyqtSlot() ##写 float def on_btnFloat_Write_clicked(self): Value = self.ui.spin_Float.value() #float型 if self.__iniWrite(): try: bts = struct.pack('f', Value) # 'f'= float, 4字节 self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写float过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 float def on_btnFloat_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["float"]) Value, = struct.unpack('f', bts) # 'f'= float, 4字节 self.ui.edit_Float.setText("%.4f" % Value) except Exception as e: QMessageBox.critical(self, "读float过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##写 double def on_btnDouble_Write_clicked(self): Value = self.ui.spin_Double.value() if self.__iniWrite(): try: bts = struct.pack('d', Value) # 'd'= double, 8字节=double self.fileStream.writeRawData(bts) except Exception as e: QMessageBox.critical(self, "写double过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ##读 double def on_btnDouble_Read_clicked(self): if self.__iniRead(): try: bts = self.fileStream.readRawData(self.__typeSize["double"]) Value, = struct.unpack('d', bts) # 'd'= double, 8字节 self.ui.edit_Double.setText("%.4f" % Value) except Exception as e: QMessageBox.critical(self, "读double过程出现错误", str(e)) finally: self.__delFileStream() ## BigEndian和LittleEndian会影响字符串前面表示长度的整数的存储顺序 @pyqtSlot() ## writeBytes写 String def on_btnStr_Write_clicked(self): strV = self.ui.editStr_In.text() #str类型 if self.__iniWrite(): bts = bytes(strV, encoding="utf-8") #转换为bytes类型 self.fileStream.writeBytes( bts) #writeBytes(self, bytes) -> QDataStream self.__delFileStream() @pyqtSlot() ## readBytes读 String def on_btnStr_Read_clicked(self): if self.__iniRead(): try: Value = self.fileStream.readBytes() #readBytes(self) -> bytes strV = Value.decode("utf-8") #从bytes类型解码为字符串,utf-8码 self.ui.editStr_Out.setText(strV) except Exception as e: QMessageBox.critical(self, "读String过程出现错误", str(e)) finally: self.__delFileStream() @pyqtSlot() ## writeRawData 写String, 未知长度无法读出 def on_btnStr_WriteRaw_clicked(self): strV = self.ui.editStr_RawIn.text() #str类型 if self.__iniWrite(): bts = bytes(strV, encoding="utf-8") #转换为bytes类型 self.fileStream.writeRawData(bts) self.__delFileStream() @pyqtSlot() ##读出编辑框全清空 def on_actClearOutput_triggered(self): self.ui.edit_Int8.clear() self.ui.edit_UInt8.clear() self.ui.edit_Int16.clear() self.ui.edit_UInt16.clear() self.ui.edit_Int32.clear() self.ui.edit_Int64.clear() self.ui.edit_Int.clear() self.ui.edit_Float.clear() self.ui.edit_Double.clear() self.ui.editStr_Out.clear() @pyqtSlot() ##连续写入文件 def on_actSaveALL_triggered(self): if not self.__iniWrite(): QMessageBox.critical(self, "错误", "为写入打开文件时出错") return #数据写入部分 Value = self.ui.spin_Int8.value() bts = struct.pack('b', Value) # 'b'=signed char, int8 self.fileStream.writeRawData(bts) Value = self.ui.spin_UInt8.value() bts = struct.pack('B', Value) # 'B'=unsigned char, uint8 self.fileStream.writeRawData(bts) Value = self.ui.spin_Int16.value() bts = struct.pack('h', Value) # 'h'=short, int16 self.fileStream.writeRawData(bts) Value = self.ui.spin_UInt16.value() bts = struct.pack('H', Value) # 'H'=unsigned short, uint16 self.fileStream.writeRawData(bts) Value = self.ui.spin_Int32.value() bts = struct.pack('l', Value) # 'l'= long, 4字节,int32 self.fileStream.writeRawData(bts) Value = self.ui.spin_Int64.value() bts = struct.pack('q', Value) # 'q'= long long, 8字节int64 self.fileStream.writeRawData(bts) Value = self.ui.spin_Int.value() bts = struct.pack('i', Value) # 'i'= int, 4字节int self.fileStream.writeRawData(bts) Value = self.ui.chkBox_In.isChecked() bts = struct.pack('?', Value) # '?'= bool, 1字节 self.fileStream.writeRawData(bts) Value = self.ui.spin_Float.value() bts = struct.pack('f', Value) # 'f'= float, 4字节 self.fileStream.writeRawData(bts) Value = self.ui.spin_Double.value() bts = struct.pack('d', Value) # 'd'= double, 8字节 self.fileStream.writeRawData(bts) strV = self.ui.editStr_In.text() #str类型 bts = bytes(strV, encoding="utf-8") #转换为bytes类型 self.fileStream.writeBytes(bts) #数据写入完成 self.__delFileStream() QMessageBox.information(self, "消息", "数据连续写入完成.") @pyqtSlot() ##连续读取文件 def on_actReadALL_triggered(self): if not self.__iniRead(): QMessageBox.critical(self, "错误", "为读取打开文件时出错") return #数据读取部分 bts = self.fileStream.readRawData(self.__typeSize["int8"]) Value, = struct.unpack('b', bts) # 'b'=signed char,int8 self.ui.edit_Int8.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["uint8"]) Value, = struct.unpack('B', bts) # 'B'=unsigned char self.ui.edit_UInt8.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["int16"]) Value, = struct.unpack('h', bts) # 'h'=short, 2字节 self.ui.edit_Int16.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["uint16"]) Value, = struct.unpack('H', bts) # 'H'=unsigned short, 2字节 self.ui.edit_UInt16.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["int32"]) Value, = struct.unpack('l', bts) # 'l'= long, 4字节 self.ui.edit_Int32.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["int64"]) Value, = struct.unpack('q', bts) # 'q'= long long, 8字节 self.ui.edit_Int64.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["int"]) Value, = struct.unpack('i', bts) # 'i'= int, 4字节 self.ui.edit_Int.setText("%d" % Value) bts = self.fileStream.readRawData(self.__typeSize["bool"]) Value, = struct.unpack('?', bts) # '?'= bool, 1字节 self.ui.chkBox_Out.setChecked(Value) bts = self.fileStream.readRawData(self.__typeSize["float"]) Value, = struct.unpack('f', bts) # 'f'= float, 4字节 self.ui.edit_Float.setText("%.4f" % Value) bts = self.fileStream.readRawData(self.__typeSize["double"]) Value, = struct.unpack('d', bts) # 'd'= double, 8字节 self.ui.edit_Double.setText("%.4f" % Value) Value = self.fileStream.readBytes() # bytes类型 strV = Value.decode("utf-8") #从bytes解码为字符串,utf-8码 self.ui.editStr_Out.setText(strV) #数据写入完成 self.__delFileStream() QMessageBox.information(self, "消息", "数据连续读取完成.")
class SendStream: def __init__(self, data : bytes = b''): self.byteArray = QByteArray(data) self.buffer = QBuffer(self.byteArray) self.buffer.open(QBuffer.ReadOnly if data else QBuffer.WriteOnly) self.stream = QDataStream(self.buffer) def atEnd(self): return self.stream.atEnd() def data(self): return self.byteArray.data() def clear(self): self.buffer.reset() self.byteArray.resize(0) def send(self, tcpSocket : QTcpSocket): writeInt(tcpSocket, len(self.byteArray)) tcpSocket.write(self.byteArray) def writeBytes(self, data: bytes): self.buffer.write(b'\xFE') self.stream.writeBytes(data) def readBytes(self): controlByte = self.buffer.read(1) if controlByte != b'\xFE': raise Exception('Failed to read bytes from stream') return self.stream.readBytes() def writeString(self, s: str): self.buffer.write(b'\xFD') self.stream.writeBytes(s.encode()) def readString(self): controlByte = self.buffer.read(1) if controlByte != b'\xFD': raise Exception('Failed to read string from stream.') return self.stream.readBytes().decode() def writeInt(self, i: int): self.buffer.write(b'\xFC') self.stream.writeInt(i) def readInt(self): controlByte = self.buffer.read(1) if controlByte != b'\xFC': raise Exception('Failed to read int from stream.') return self.stream.readInt() def writeBool(self, b: bool): self.buffer.write(b'\xFB' if b else b'\xFA') def readBool(self): b = self.buffer.read(1) if b == b'\xFB': return True elif b == b'\xFA': return False else: raise Exception('Failed to read bool from stream')
def run(self): print('-----------------------') socket = QTcpSocket() count = 0 if not socket.setSocketDescriptor(self.socketId): # 可能是分配的东西,具体作用不知道 # self.emit(SIGNAL("error(int)"), socket.error()) self.error.connect(socket.error) return while socket.state() == QAbstractSocket.ConnectedState: nextBlockSize = 0 stream = QDataStream(socket) stream.setVersion(QDataStream.Qt_5_8) sockeIdToSocketDict[self.socketId] = socket # print(sockeIdToSocketDict) # 将所有连接上来的socket保存起来 # print(fixIdToSocketIdDict) aim_ip = socket.peerAddress().toString() # 获得连上来的IP地址 # print(aim_ip) if (socket.waitForReadyRead() and socket.bytesAvailable() >= SIZEOF_UINT64): print('wait') nextBlockSize = stream.readUInt64() else: print('错误') # 客户端主动断开时,去掉字典中的对应,在这里做一部分操作。 # 客户端主动断开的时候,要将其从self.myParent.sockeIdToSocketDict self.myParent.fixIdToSocketIdDict 中删掉 sockeIdToSocketDict.pop(self.socketId) # 客户端主动断开的时候删掉。 fixIdToSocketIdDict.pop(fixID) threadDict.pop(self.socketId) self.popDeviceSignal.emit(fixID) self.sendError(socket, "Cannot read client request") return if socket.bytesAvailable() < nextBlockSize: print("错误2") if (not socket.waitForReadyRead(60000) or socket.bytesAvailable() < nextBlockSize): self.sendError(socket, "Cannot read client data") return # 这段数据流上 第一个是state 根据state判断接下来的状态, # 发送成功的状态,发送来 success 日期 信号类型 识别结果 识别开始时间 识别时间 state = stream.readQString() # 读状态 print('#61 ' + state) if state == 'successResult': # 如果状态是success,说明下一个发来的是识别的结果 resultBytes = stream.readBytes() try: Thread.lock.lockForRead() finally: Thread.lock.unlock() resultObject = pickle.loads(resultBytes) # print(fixID) # print(resultObject.dateNow) # print(resultObject.kind) # print(resultObject.result) # print(resultObject.startTime) # print(resultObject.usedTime) if resultObject.kind == "HDMI" and self.hdmi_old_result != resultObject.result: # 自动采集的不需要时间,他需要 日期 时间识别结果 发走的信息只有 类型 识别结果 ip地址 全是strhandleSql.pushResultInfo('123425','HDMI','北京卫视','2018-12-23 12:23:21',12) self.pushResultInfoSignal.emit( fixID, resultObject.kind, resultObject.result, resultObject.startTime, int(resultObject.usedTime )) # 发射信号,携带了信号类型,识别结果,aim_ip(当做区分控件的id)结果从这里发出去 self.hdmi_old_result = resultObject.result elif resultObject.kind == 'AV' and self.av_old_result != resultObject.result: self.pushResultInfoSignal.emit( fixID, resultObject.kind, resultObject.result, resultObject.startTime, int(resultObject.usedTime) ) # 发射信号,携带了信号类型,识别结果,aim_ip(当做区分空间的id) getMessgetMessageAllTcpageAllTcp self.av_old_result = resultObject.result elif state == 'sendImage': # 如果状态是wait_to_recognize,说明下一端是图片的16位整数# 图片的暂时不考虑,因为还不知道发给谁 kind = stream.readQString() # 读台标信号类型 try: Thread.lock.lockForRead() finally: Thread.lock.unlock() file = stream.readBytes() with open('image.jpg', 'wb') as f: f.write(file) elif state == 'deviceInfo': # 收到deviceInfo对象 deviceInfoByte = stream.readBytes() try: Thread.lock.lockForRead() finally: Thread.lock.unlock() # pictureSizeByte = stream.readBytes() deviceInfo = pickle.loads(deviceInfoByte) # pictureSize = pickle.loads(pictureSizeByte) fixID = deviceInfo['deviceFixId'] fixIdToSocketIdDict[fixID] = self.socketId print(deviceInfo['pictureSize']) self.pushDeviceInfoSignal.emit(deviceInfo['deviceFixId'], deviceInfo['regionProvince'], deviceInfo['regionCity'], deviceInfo['regionArea']) print("___________________________") print(deviceInfo['fileInfo']) self.pushPictureSizeSignal.emit(str(deviceInfo['pictureSize']), deviceInfo['deviceFixId'], deviceInfo['kind']) self.pushFileInfoSignal.emit(str(deviceInfo['fileInfo']), deviceInfo['deviceFixId']) elif state == 'sendFile': # 准备接受 文件 fileName = stream.readQString() # 读取文件名称 fileSize = stream.readQString() # 读取文件大小 fileBytes = stream.readBytes() # 读取文件部分字节 try: Thread.lock.lockForRead() finally: Thread.lock.unlock() # print(fileSize) with open('../TEST/' + fileName, 'ab') as f: f.write(fileBytes) count = count + fileBytes.__len__()
def remove_bookmark(self, spath): if not self.written: return if not os.path.exists(self.config_path): self.written = False return url = pathlib.Path(spath).as_uri() settings_qt4 = QSettings(self.config_path, QSettings.IniFormat) if not settings_qt4.isWritable(): self.written = False return data = settings_qt4.value('Qt/filedialog') stream = QDataStream(data, QIODevice.ReadOnly) magic = stream.readUInt32() version = stream.readUInt32() if not (magic == QFileDialogMagic and version == 3): self.written = False return split_states = stream.readBytes() bookmark_found = False bookmarks_len = stream.readUInt32() bookmarks = [] for bm in range(bookmarks_len): qUrl = QUrl() stream >> qUrl if qUrl.isLocalFile() and qUrl.toLocalFile() == spath: bookmark_found = True else: bookmarks.append(qUrl) if not bookmark_found: self.written = False return history_len = stream.readUInt32() history = [] for h in range(history_len): his = stream.readQString() history.append(his) current_dir = stream.readQString() header_data = stream.readBytes() view_mode = stream.readUInt32() #now rewrite bytes new_data = QByteArray() new_stream = QDataStream(new_data, QIODevice.WriteOnly) new_stream.writeUInt32(magic) new_stream.writeUInt32(3) new_stream.writeBytes(split_states) new_stream.writeUInt32(bookmarks_len-1) for bm in bookmarks: new_stream << bm qUrl = QUrl(url) new_stream << qUrl new_stream.writeQStringList(history) new_stream.writeQString(current_dir) new_stream.writeBytes(header_data) new_stream.writeUInt32(view_mode) settings_qt4.setValue('Qt/filedialog', new_data) settings_qt4.sync() self.written = False