def update_data(self, json_data): """New data for the model :param json_data: binary JSON, a dict or a filename :return: """ error = QJsonParseError() try: self.document = QJsonDocument.fromJson(json_data, error) except TypeError: if isinstance(json_data, dict): self.document = QJsonDocument.fromVariant(json_data) if self.document is not None: self.beginResetModel() if self.document.isArray(): self.root_item.init_tree(list(self.document.array())) else: self.root_item = self.root_item.init_tree( self.document.object()) self.endResetModel() return else: # try as file if self.load_from_file(filename=json_data): return msg = f"Unable to load as JSON:{json_data}" logging.log(logging.DEBUG, msg) raise ValueError(msg)
def exportJson(self): from PySide2.QtCore import QJsonDocument, QByteArray, QJsonArray jDoc = QJsonDocument() jObj = dict() if self._oroborusFlag == False: jObj["oroborusFlag"] = self._oroborusFlag if self._cycleFlag == False: jObj["cycleFlag"] = self._cycleFlag if self._radius != 100: jObj["radius"] = self._radius if self._speedRatio != 1.0: jObj["speedRatio"] = self._speedRatio if self._lineWidth != 1: jObj["lineWidth"] = self._lineWidth digitsArray = QJsonArray() for d in self._digitsList: digitsArray.append(int(d)) jObj["digits"] = digitsArray jObj["scale"] = self._scale if self._dotColor != QColor(Qt.green): jObj["dotColor"] = self._dotColor.name() if self._lineColor != QColor(Qt.black): jObj["lineColor"] = self._lineColor.name() jDoc.setObject(jObj) jsonString = jDoc.toJson(QJsonDocument.Compact).data().decode() return jsonString
def testToVariant(self): a = QJsonDocument.fromJson(b'{"test": null}') self.assertIsInstance(a, QJsonDocument) if py3k.IS_PY3K: self.assertEqual(str(a.toVariant()), "{'test': None}") else: self.assertEqual(str(a.toVariant()), "{u'test': None}") b = QJsonDocument.fromJson(b'{"test": [null]}') self.assertIsInstance(b, QJsonDocument) if py3k.IS_PY3K: self.assertEqual(str(b.toVariant()), "{'test': [None]}") else: self.assertEqual(str(b.toVariant()), "{u'test': [None]}")
def save_default_parameters(self): base_path = Path(__file__).parent settings_path = str( (base_path / '../resources/PRINTER_SETTINGS.json').resolve()) settings_file = QFile(settings_path) file_data = {} if settings_file.open(QIODevice.ReadOnly | QIODevice.Text): file_data = QJsonDocument.fromJson( settings_file.readAll()).object() settings_file.close() if settings_file.open(QIODevice.ReadWrite | QIODevice.Text | QIODevice.Truncate): file_data["printer_type"] = "DLP" file_data["dlp_settings"] = self.__default_parameters settings_file.write(QJsonDocument(file_data).toJson()) settings_file.close()
def prepareParams(self): objParams = { "method": self.mmethod, "params": self.mparams, "id": self.getId() } return QJsonDocument(objParams).toJson(QJsonDocument.Compact)
def divideJson(self, jsonString): from PySide2.QtCore import QJsonDocument, QByteArray, QJsonArray jBytes = QByteArray(jsonString.encode()) jDoc = QJsonDocument.fromJson(jBytes) jObj = jDoc.array() l2 = [] for i in range(0, jObj.size()): l2.append(str(jObj.at(i).toObject())) return l2
def textMessageReceived(self, message_data_in): """Deserialize the stringified JSON messageData and emit messageReceived.""" message_data = QByteArray(bytes(message_data_in, encoding='utf8')) message = QJsonDocument.fromJson(message_data) if message.isNull(): print("Failed to parse text message as JSON object:", message_data) return if not message.isObject(): print("Received JSON message that is not an object: ", message_data) return self.messageReceived.emit(message.object(), self)
def runReport(self, pid, method, par): self.boolDirect = True self.mtypeCall = "report" self.mpid = pid self.mmethod = method self.mparams = par # bparams = self.prepareParams() request = self.prepareRequest() # reply = self.data_request(request, bparams) data = reply.readAll() parseError = QJsonParseError() resultObject = {} resultObject["data"] = "error" document = QJsonDocument.fromJson(data, parseError) if parseError.error == True: resultObject["data"] = "error" else: if document.isObject(): jv = document.object() if jv.__contains__( "result") == True and jv["result"].__class__() == []: #tryton 4.0 #'result': ['pdf', {'base64':wwwwww, '__class__':'bytes'}, False,'Printis'] jre = jv["result"] namesecs = "tryton_" + self.mpid + str( QDateTime.currentMSecsSinceEpoch()) + "." + jre[0] mdir = QDir(self.mDir + QDir.separator() + "tempReports") if mdir.exists() == False: s = QDir(self.mDir) s.mkdir("tempReports") filename = self.mDir + QDir.separator( ) + "tempReports" + QDir.separator() + namesecs file = QFile(filename) if file.open(QIODevice.WriteOnly) == False: #error self.signalResponse.emit(self.mpid, 7, {}) print("error", filename, file.errorString()) else: bafile = QByteArray.fromBase64( jre[1]["base64"].encode()) file.write(bafile) file.close() QDesktopServices.openUrl(QUrl(filename)) else: if document.isArray() == True: self.signalResponse.emit(self.mpid, 7, {}) self.processingData(data, reply)
def __load_settings__(self): base_path = Path(__file__).parent settings_path = str( (base_path / '../resources/PRINTER_SETTINGS.json').resolve()) settings_file = QFile(settings_path) if settings_file.open(QIODevice.ReadOnly | QIODevice.Text): file_data = QJsonDocument.fromJson( settings_file.readAll()).object() if "metal_printer_settings" in file_data: printer_setup = str( file_data["metal_printer_settings"]["printer_setup"]) if printer_setup == self.supported_setups[0]: self.__select_setup__(0) else: return False return True settings_file.close() return False
file = QFile("Clock.qss") else: file = QFile(args.style) file.open(QFile.ReadOnly) style_sheet = file.readAll() # print(style_sheet.data().decode("utf-8")) app.setStyleSheet(style_sheet.data().decode("utf-8")) if os.uname().sysname == "Linux": f = open("/sys/class/backlight/rpi_backlight/brightness") num = int(f.readline()) f.close() else: num = 40 clock.LCD_brightness = num clock.Brightness.setSliderPosition(num) setting_file = os.getenv("HOME") + "/.Qt_Clock" loadfile = QFile(setting_file) if not loadfile.open(QFile.ReadOnly): print("Could not open setting JSon file: {}".format(setting_file)) else: data = loadfile.readAll() json = QJsonDocument.fromJson(data).object() clock.setup_from_json(json) clock.show() sys.exit(app.exec_())
def addResult(self, result, update=False): #QJsonArray jsonobj = {} mis = self._count() for res in result: mid = int(res["id"]) mapJsonDoc = res jsonobj = {} order = "" if self.m_order == "" else mapJsonDoc[ self.m_order].strip() metadata = "" jsonobj = mapJsonDoc if self.boolMetadata: doct = QJsonDocument(mapJsonDoc) metadata = doct.toJson( QJsonDocument.Compact).data().decode("utf-8") # if self.m_fields!= QJsonArray(): if len(self.m_fieldsPoint) > 0: fieldsdoc = list(mapJsonDoc) for fp in self.m_fieldsPoint: if fp not in fieldsdoc: lfp = fp.split(".") for li in range(len(lfp) - 1): lfp[li] = lfp[li] + "." temp = jsonobj[lfp[0]] for c in lfp[1:]: if temp != None: temp = temp[c] jsonobj[fp] = temp for vp in self.m_fieldsFormatDecimal: v = vp[0] if jsonobj.__contains__(v): if jsonobj[v] != None: if jsonobj[v].__contains__("decimal"): jsonobj[v + "_format"] = self.m_locale.toString( float(jsonobj[v]["decimal"]), 'f', vp[1]) #add suport else: jsonobj[v + "_format"] = "" else: jsonobj[v + "_format"] = "" for v in self.m_fieldsFormatDateTime: mfield = v[0] mformat = v[1] if jsonobj.__contains__(mfield): mdateTime = QDateTime() if jsonobj[mfield] != None: if jsonobj[mfield].__contains__("__class__"): if jsonobj[mfield]["__class__"] == "date": mdateTime = QDateTime( QDate(jsonobj[mfield]["year"], jsonobj[mfield]["month"], jsonobj[mfield]["day"]), QTime()) if jsonobj[mfield]["__class__"] == "datetime": mdateTime = QDateTime( QDate(jsonobj[mfield]["year"], jsonobj[mfield]["month"], jsonobj[mfield]["day"]), QTime(jsonobj[mfield]["hour"], jsonobj[mfield]["minute"], jsonobj[mfield]["second"])) jsonobj[mfield + "_format"] = mdateTime.toString(mformat) else: jsonobj[mfield + "_format"] = "" else: jsonobj[mfield + "_format"] = "" if update == False: dataJson = DataJson(mid, order, jsonobj, metadata, self) self.append(dataJson) self.m_hasIndexOfId[mid] = mis mis += 1 else: index = self.indexisOfId(mid) if index != -1: self.at(index).setProperty("order", order) self.at(index).setProperty("json", jsonobj) self.at(index).setProperty("metadata", metadata)
def sendMessage(self, message): """Serialize the JSON message and send it as a text message via the WebSocket to the client.""" doc = QJsonDocument(message) json_message = str(doc.toJson(QJsonDocument.Compact), "utf-8") self._socket.sendTextMessage(json_message)
def processingData(self, data, reply): parseError = QJsonParseError() error = reply.error() errorString = reply.errorString() statusCode = reply.attribute(QNetworkRequest.HttpStatusCodeAttribute) fraseStatusCode = reply.attribute( QNetworkRequest.HttpReasonPhraseAttribute) redirectUrl = QUrl( reply.attribute(QNetworkRequest.RedirectionTargetAttribute)) redirectUrlFix = self.redirectUrlComp(redirectUrl, self.urlServer) # print(errorString, statusCode) resultObject = { "status": statusCode, "fraseStatus": fraseStatusCode, "errorString": errorString } result = False # QJsonValue result=false; Bug QJsonValue(True) if self.mpid == "open@": resultObject["credentials"] = False if QNetworkReply.NoError == error: if redirectUrlFix.isEmpty() == False: if self.boolDirect == False: print("se redireciona", redirectUrl) self.urlServer = redirectUrl self.initOrderConnect() self.signalResponse.emit(self.mpid, 1, resultObject) else: document = QJsonDocument.fromJson(data, parseError) if parseError.error == True: resultObject["data"] = data.__str__() self.signalResponse.emit(self.mpid, 4, resultObject) #redireccion else: if document.isArray() == True: result = document.array() else: #supuestamente es un object json if self.mpid == "open@": if document.object().__contains__( "result") == True: if document.object()["result"].__class__( ) == []: if document.object()["result"].__len__( ) == 2: self.token = document.object( )["result"] self.boolConnect = True self.intCountConnect += 1 resultObject["credentials"] = True result = document.object() resultObject["data"] = result if self.boolDirect == False: self.signalResponse.emit(self.mpid, 2, resultObject) #ok else: #and report if self.mpid == "open@" and result.__contains__( "error") == False and self.boolRecursive == False: resultObject["extra"] = "direct" self.signalResponse.emit(self.mpid, 2, resultObject) # elif self.mpid=="open@" and result.__contains__("error")==False and resultObject["credentials"] == False and self.boolRecursive == True: # self.signalResponse.emit(self.mpid, 2, resultObject) elif result.__contains__("error") == True: if self.boolRecursive == True: if result["error"].__class__( ) == [] and result["error"].__contains__( "UserWarning" ) == False and result["error"][0].__contains__( "403") == False and result["error"][ 0].__contains__("401") == False: self.signalResponse.emit( self.mpid, 2, resultObject) elif document.isObject(): self.signalResponse.emit(self.mpid, 2, resultObject) else: print(error, statusCode, errorString) #, resultObject) if self.boolRecursive == True: if resultObject['status'] != 401 and resultObject[ 'status'] != 403: self.signalResponse.emit( self.mpid, 3, resultObject) #//error comunicacion else: self.signalResponse.emit(self.mpid, 3, resultObject) #//error comunicacion self.boolRun = False reply.deleteLater()
def callDirect(self, pid, method, par): if self.boolRecursive == False: self.clearMessagesWarning() resultObject = {} if self.boolRun == False: self.boolRun = True self.boolDirect = True self.mtypeCall = "order" self.mpid = pid self.mmethod = method self.mparams = par bparams = self.prepareParams() request = self.prepareRequest() reply = self.data_request(request, bparams) data = reply.readAll() ## QByteArray parseError = QJsonParseError() resultObject["data"] = "error" document = QJsonDocument.fromJson(data, parseError) error = reply.error() statusCode = reply.attribute( QNetworkRequest.HttpStatusCodeAttribute) if QNetworkReply.NoError == error: if parseError.error == True: resultObject["data"] = "error" else: if document.isObject(): jv = document.object() if jv.__contains__("result"): resultObject["data"] = jv else: if self.boolRecursive: if jv.__contains__("error"): if jv["error"].__class__() == []: if jv["error"].__contains__( "UserWarning" ) or jv["error"][0].__contains__( "403") or jv["error"][ 0].__contains__("401"): resultObject["data"] = jv elif self.mpid == "open@": resultObject["data"] = jv else: if document.isArray() == True: resultObject["data"] = document.array() else: resultObject["data"] = "error" else: if statusCode == 401 or statusCode == 403: resultObject["data"] = statusCode self.processingData(data, reply) # cath return resultObject else: resultObject["data"] = "error" if pid != self.mpid: self.signalResponse.emit("run@", 8, {}) return resultObject
def save_current_parameters(self): current_parameters = { 'printer_setup': self.printer_setup, 'projector_setup': self.projector_setup, 'motor_setup': self.motor_setup, # Support Parameters 'support_thickness (mm)': self.support_thickness, # mm 'support_exposure (ms)': self.support_exposure, # ms 'support_amplitude': self.support_amplitude, 'support_burn_layers': self.support_burn_layers, 'support_burn_exposure (ms)': self.support_burn_exposure, # ms 'support_burn_amplitude': self.support_burn_amplitude, # Features Parameters 'features_thickness (mm)': self.features_thickness, # mm 'features_exposure (ms)': self.features_exposure, # ms 'features_amplitude': self.features_amplitude, 'features_burn_layers': self.features_burn_layers, 'features_burn_exposure (ms)': self.features_burn_exposure, # ms 'features_burn_amplitude': self.features_burn_amplitude, # Advanced Parameters 'incremental_thickness': self.incremental_thickness, 'incremental_exposure': self.incremental_exposure, 'incremental_amplitude': self.incremental_amplitude, 'starting_incremental_thickness (mm)': self.starting_incremental_thickness, # mm 'incremental_step_thickness (mm)': self.incremental_step_thickness, # mm 'starting_incremental_exposure (ms)': self.starting_incremental_exposure, # ms 'incremental_step_exposure (ms)': self.incremental_step_exposure, # ms 'starting_incremental_amplitude': self.starting_incremental_amplitude, 'incremental_step_amplitude': self.incremental_step_amplitude, 'fixed_layer': self.fixed_layer, 'grayscale_correction': self.grayscale_correction, 'grayscale_alpha': self.grayscale_alpha, 'grayscale_beta': self.grayscale_beta, 'grayscale_gamma': self.grayscale_gamma, # Others 'projector_amplitude': self.projector_amplitude, 'feed_rate (mm/min)': self.__motor_controller.feed_rate, # mm/min 'spindle_pitch_microns': self.spindle_pitch_microns, 'motor_steps_per_revolution': self.motor_steps_per_revolution, 'projector_feed_rate (mm/min)': self.__motor_controller.projector_feed_rate, 'repositioning_delay (ms)': self.__motor_controller.repositioning_delay, # ms 'repositioning_offset (mm)': self.__motor_controller.repositioning_offset, # mm 'projector_pixel_size (mm)': self.projector_pixel_size, # mm 'projector_width': self.projector_width, 'projector_height': self.projector_height, 'horizontal_mirror': self.__projector_controller.horizontal_mirror, 'vertical_mirror': self.__projector_controller.vertical_mirror, 'samples_per_pixel': self.samples_per_pixel } base_path = Path(__file__).parent log_path = str((base_path / '../resources/PRINT_LOG.json').resolve()) log_file = QFile(log_path) file_data = {} # if log_file.open(QIODevice.ReadOnly | QIODevice.Text): # file_data = QJsonDocument.fromJson(log_file.readAll()).object() # log_file.close() if log_file.open(QIODevice.ReadWrite | QIODevice.Append): # Print Job Parameters file_data['date (yyyy.MM.dd)'] = self.printing_date file_data['time (hh.mm.ss)'] = self.printing_time file_data['username'] = self.username file_data['print_job_name'] = self.print_job_name file_data['print_job_status'] = self.print_status file_data['total_layers'] = self.number_of_layers file_data['support_layers'] = len(self.support_file_names) file_data['features_layers'] = len(self.features_file_names) file_data['printed_layers'] = self.current_layer file_data["printer_type"] = "DLP" if self.print_status == "FAILED": file_data["error_message"] = self.error_message file_data["dlp_settings"] = current_parameters log_file.write(QJsonDocument(file_data).toJson()) log_file.close()
def __load_default_parameters__(self): self.__default_parameters = { 'printer_setup': self.printer_setup, 'projector_setup': self.projector_setup, 'motor_setup': self.motor_setup, 'support_thickness (mm)': 0.018, # mm 'support_exposure (ms)': 3000, # ms 'support_amplitude': 230, 'support_burn_layers': 5, 'support_burn_exposure (ms)': 15000, # ms 'support_burn_amplitude': 500, # Features Parameters 'features_thickness (mm)': 0.018, # mm 'features_exposure (ms)': 3000, # ms 'features_amplitude': 230, 'features_burn_layers': 0, 'features_burn_exposure (ms)': 15000, # ms 'features_burn_amplitude': 500, # Advanced Parameters 'incremental_thickness': False, 'incremental_exposure': False, 'incremental_amplitude': False, 'starting_incremental_thickness (mm)': 0.001, # mm 'incremental_step_thickness (mm)': 0.001, # mm 'starting_incremental_exposure (ms)': 1000, # ms 'incremental_step_exposure (ms)': 100, # ms 'starting_incremental_amplitude': 10, 'incremental_step_amplitude': 10, 'fixed_layer': False, 'grayscale_correction': False, 'grayscale_alpha': 0, 'grayscale_beta': 0, 'grayscale_gamma': 0, # Others 'projector_amplitude': 0, 'horizontal_mirror': True, 'vertical_mirror': False, 'repositioning_delay (ms)': 500, # ms 'feed_rate (mm/min)': 300, # mm/min 'spindle_pitch_microns': 4000, 'motor_steps_per_revolution': 6400, 'projector_feed_rate (mm/min)': 300, 'repositioning_offset (mm)': 5, # mm 'projector_pixel_size (mm)': 0.00754, # mm 'projector_width': 2560, 'projector_height': 1600, 'samples_per_pixel': 1 } base_path = Path(__file__).parent settings_path = str( (base_path / '../resources/PRINTER_SETTINGS.json').resolve()) settings_file = QFile(settings_path) if settings_file.open(QIODevice.ReadOnly | QIODevice.Text): file_data = QJsonDocument.fromJson( settings_file.readAll()).object() if "dlp_settings" in file_data: for key, value in self.__default_parameters.items(): if key in file_data["dlp_settings"]: new_value = file_data["dlp_settings"][key] self.__default_parameters[key] = new_value settings_file.close()