def DeletePreset(self): current_config_name = self.get_config_name() if current_config_name in self.configs_data['Config Name'].values: user_decision = PopUpNotifier.PresetDeleteQuestion(current_config_name) if user_decision == True: self.RemovePreset(current_config_name) self.ResetSliders(1) # Чтобы после удаления пресета "обнулить" график, оставшийся от удалённого пресета self.set_config_name("") # Обнулить имя конфига else: PopUpNotifier.Warning(f'Preset {current_config_name} was not found in preset base!')
def Connect(self): already_connected = self.DeltaCPClient.if_connected if already_connected: PopUpNotifier.Info(f'Client is already connected!') return ConnectionParameters = self.ConnectionParameters.GetConnectionParameters( ) try: self.DeltaCPClient.CreateClient( Protocol=ConnectionParameters['Protocol'], COMPort=ConnectionParameters['COMPort'], Timeout=ConnectionParameters['Timeout'], StopBits=ConnectionParameters['StopBits'], ByteSize=ConnectionParameters['ByteSize'], Parity=ConnectionParameters['Parity'], BaudRate=ConnectionParameters['BaudRate']) except: loggers['Debug'].debug(f'Exception while creating DeltaCP Client') return if_connected = self.DeltaCPClient.Connect() self.notify_connection_success(if_connected) loggers['Application'].info(f'Connection successful? {if_connected}') loggers['Debug'].debug(f'If client connected: {if_connected}')
def check_columns_correctness(self, df): cols = df.columns for c in self.NecessaryColumns: if not c in cols: PopUpNotifier.Error( f'The .xlsx file does not have column "{c}".\nIncorrect source data!' ) return False return True
def SavePreset(self): current_config_name = self.get_config_name() if current_config_name in self.configs_data['Config Name'].values: user_decision = PopUpNotifier.PresetSavingQUestion() if user_decision == True: self.RemovePreset(current_config_name) self.WriteNewPreset(current_config_name) else: return else: self.WriteNewPreset(current_config_name)
def AutoFill(self): try: self.config_name = self.get_config_name() self.init_config_params() self.init_values_to_set() self.init_autofill_parameters() self.set_signal_parameters( self.autofill_parameters ) except KeyError: PopUpNotifier.Warning(f'Preset "{self.config_name}" was not found in preset base!') loggers['Debug'].debug(f'AutoFillOperator: AutoFill: Preset {self.config_name} not found')
def check_acceleration_deceleration(self, necessary_t_acceleration, necessary_t_deceleration): # Перед началом отправки, надо: # 1. Опросить текущие t разгона, замедления # 2. Понять, какие t разгона, замедления нам нужны # 3. Проверить - необходимые времёна в пределах критических? # 4. Если времёна больше критических, опросить пользователя - ОК ли продолжать отправку с # требуемыми t разгона замедления? # 4. Если ОК, то задаём новые значения на частотник, # и погнали отправлять сигнал # 1 current_t_acceleration = self.DeltaCPClient.RequestAccelerationTime1() current_t_deceleration = self.DeltaCPClient.RequestDecelerationTime1() # 2 diff_freq = abs(self.model.HighLevelFrequency - self.model.LowLevelFrequency) try: necessary_acceleration = diff_freq / necessary_t_acceleration necessary_deceleration = diff_freq / necessary_t_deceleration except ZeroDivisionError: PopUpNotifier.Error(f'Zero Acceleration/Deceleration time!') return False # 3 critical_acceleration = self.model.CriticalAcceleration critical_deceleration = self.model.CriticalDeceleration if (abs(necessary_acceleration) >= abs(critical_acceleration)) or ( abs(necessary_deceleration) >= abs(critical_deceleration)): user_decision = PopUpNotifier.CriticalAccelerDecelerQuestion( current_t_acceleration, current_t_deceleration, critical_acceleration, critical_deceleration, necessary_acceleration, necessary_deceleration) return user_decision else: return True
def AutoConnect(self): already_connected = self.DeltaCPClient.if_connected if already_connected: PopUpNotifier.Info('Client already connected!') return for index, config in self.ConnectionConfigs.iterrows(): self.set_config_into_comboboxes\ ( [config['Protocol'], self.window.ProtocolcomboBox], [str(config['Byte Size']), self.window.ByteSizecomboBox], [config['Parity'], self.window.ParitycomboBox], [str(config['Stop Bits']), self.window.StopBitscomboBox], [str(config['Baud Rate']), self.window.BaudRatecomboBox] ) ConnectionParameters = self.ConnectionParameters.GetConnectionParameters( ) self.DeltaCPClient.CreateClient( Protocol=ConnectionParameters['Protocol'], COMPort=ConnectionParameters['COMPort'], Timeout=ConnectionParameters['Timeout'], StopBits=ConnectionParameters['StopBits'], ByteSize=ConnectionParameters['ByteSize'], Parity=ConnectionParameters['Parity'], BaudRate=ConnectionParameters['BaudRate']) if_connected = self.DeltaCPClient.Connect() if if_connected: msg_success = 'Auto connection successful!' loggers['Application'].info(msg_success) PopUpNotifier.Info(msg_success) return msg = f'Auto Connect unsuccessful. Please write other configs into ConnectionConfigs.xlsx' \ f' file or set parameters manually' loggers['Application'].info(msg) PopUpNotifier.Warning(msg)
def AutoFill(self): config_name = self.config_line_edit.text() config_filepath = self.configs_folder + config_name + '.xlsx' configs_df = pd.read_excel(config_filepath) absent_columns = self.check_data_validity(configs_df) if len(absent_columns) == 0: # Значит, все необходимые колонки # были заполнены, данные правильные frequencies = configs_df['Frequencies'].values seconds = configs_df['Seconds'].values request_freq = configs_df['Request every N seconds'].values[0] self.model.frequencies = frequencies self.model.seconds = seconds self.model.request_every_N_sec = request_freq else: PopUpNotifier.Error( f'Missing Columns in file "{config_name}":\n{absent_columns}' ) # Закроем файл del configs_df
def VisualizeLog(self): filename = self.window.LogFilenamelineEdit.text() + '.xlsx' if self.window.TrapezoidradioButton.isChecked(): logfile_dir = self.TrapezoidDir + filename elif self.window.ScheduleradioButton.isChecked(): logfile_dir = self.ScheduleDir + filename log_plot = self.window.LogPlot log_plot.set_up_plot() real_t_label = self.window.RealTimelabel expect_t_label = self.window.ExpectTimelabel sigma_label = self.window.StandardDeviationlabel avg_command_delay_label = self.window.AverageCommandDelaylabel cycle_delay_label = self.window.CycleDelaylabel try: log_df = pd.read_excel(logfile_dir) cols_correct = self.check_columns_correctness(log_df) if cols_correct: t_expect = log_df['Expect Time'].values f_expect = log_df['Expect Freq, Hz'].values t_real = log_df['Real Time (Synchronized), Sec'].values cycle_delays = log_df['Cycle dt delay, Sec'].values if self.DebugMode: f_real = f_expect else: f_real = log_df['Real Freq, Hz'].values standard_deviation = self.calc_standard_deviation( f_real, f_expect) sigma_label.setText(self.value_to_text(standard_deviation)) average_cycle_dt_delay = self.calc_average_cycle_dt_delay( cycle_delays) cycle_delay_label.setText( self.calc_time_representation(average_cycle_dt_delay)) average_command_delay = self.calc_average_command_delay( t_expect, t_real) avg_command_delay_label.setText( self.calc_time_representation(average_command_delay)) whole_t_real = self.calc_time_representation(t_real[-1]) real_t_label.setText(whole_t_real) whole_t_expect = self.calc_time_representation(t_expect[-1]) expect_t_label.setText(whole_t_expect) log_plot.plot(t_expect, f_expect, do_cla=False, label='Expect', marker='o', markersize=4) log_plot.plot(t_real, f_real, do_cla=False, label='Real', marker='o', markersize=4) except FileNotFoundError: PopUpNotifier.Error(f'Cannot find file {logfile_dir}') except: import sys print(sys.exc_info())
def notify_connection_success(self, if_connected): if if_connected: PopUpNotifier.Info(f'Client connection successful!') else: PopUpNotifier.Error(f'Client connection failed!')
def UpdateSignalData(self): WholePeriod = self.SignalData.StartTime + self.SignalData.AccelerationTime + self.SignalData.PlateauTime + \ self.SignalData.DecelerationTime + self.SignalData.EndTime LowLevelFreq = self.SignalData.LowLevelFrequency HighLevelFreq = self.SignalData.HighLevelFrequency StartTime = self.SignalData.StartTime AccTime = self.SignalData.AccelerationTime PlateauTime = self.SignalData.PlateauTime DecTime = self.SignalData.DecelerationTime EndTime = self.SignalData.EndTime PointsDensity = self.SignalData.PointsDensity AccelerationTime = self.SignalData.AccelerationTime DecelerationTime = self.SignalData.DecelerationTime if WholePeriod != 0: StartX = self.prepare_data_arr(time_from=0, time_to=StartTime, points_density=PointsDensity, endpoint=True, subtract=True) if AccelerationTime != 0: AccelerationTangent = (HighLevelFreq - LowLevelFreq) / AccelerationTime AccelerationX = self.prepare_acceleration_arr(time_from=StartTime, time_to=StartTime + AccTime, tangent=AccelerationTangent, endpoint=True) if len(StartX) != 0: # Если на старте уже есть точки - крайнюю точку слева у ускорения убираем, чтоб два раза не учесть AccelerationX = AccelerationX[1:] else: AccelerationX = [] PlateauX = self.prepare_data_arr(time_from=StartTime + AccTime, time_to=StartTime + AccTime + PlateauTime, points_density=PointsDensity, endpoint=True, subtract=True) if DecelerationTime != 0: DecelerationTangent = (LowLevelFreq - HighLevelFreq) / DecelerationTime DecelerationX = self.prepare_deceleration_arr(time_from=StartTime + AccTime + PlateauTime, time_to=StartTime + AccTime + PlateauTime + DecTime, tangent=DecelerationTangent, endpoint=True) if len(PlateauX): # Значит, плато построено. И включает обе крайние точки, слева и справа (endpoint) # Тогда надо убрать крайнюю правую точку на ускорении, и крайнюю левую точку у замедления, # чтоб 2 раза не учесть AccelerationX = AccelerationX[:-1] DecelerationX = DecelerationX[1:] else: DecelerationX = [] # Ещё был баг - если PlateauX = [], т.е. пустой, тогда края у AccelerationX и DecelerationX совпадают ( # края на состыковке содержат одинаковые точки). У одного из массивов надо её убрать if len(PlateauX) == 0: # Допустим, убираем у DecelerationX DecelerationX = DecelerationX[1:] EndX = self.prepare_data_arr(time_from=StartTime + AccTime + PlateauTime + DecTime, time_to=StartTime + AccTime + PlateauTime + DecTime + EndTime, points_density=PointsDensity, endpoint=True, subtract=True) if len(EndX): # Значит, конечный отрезок построен, он включает и левую и правую крайние точки, # Так что у deceleration_x надо убрать крайнюю правую точку DecelerationX = DecelerationX[:-1] StartY = [LowLevelFreq for x in StartX] EndY = [LowLevelFreq for x in EndX] PlateauY = [HighLevelFreq for x in PlateauX] # Линейная зависимость виде y_0 + k * (x - x_0). Поэтому определим x_0 для # Участка с ускорением и замедлением AccelerationX0 = StartX[-1] if len(StartX) else 0 if len(PlateauX): DecelerationX0 = PlateauX[-1] elif len(AccelerationX): DecelerationX0 = AccelerationX[-1] elif len(StartX): DecelerationX0 = StartX[-1] else: DecelerationX0 = 0 AccelerationY = [LowLevelFreq + AccelerationTangent * (x - AccelerationX0) for x in AccelerationX] DecelerationY = [HighLevelFreq + DecelerationTangent * (x - DecelerationX0) for x in DecelerationX] # Подправляем баги на стыках линейных функций AccelerationY = [y if y <= HighLevelFreq else HighLevelFreq for y in AccelerationY] DecelerationY = [y if y >= LowLevelFreq else LowLevelFreq for y in DecelerationY] SignalData.y = StartY + AccelerationY + PlateauY + DecelerationY + EndY SignalData.x = np.concatenate((StartX, AccelerationX, PlateauX, DecelerationX, EndX)) # проверим, что в SignalData.x после наших построений не попались повторяющиеся точки if not self.all_x_are_unique(): PopUpNotifier.Error(f'X array in Signal contains non-unique values!\nThere will be an error during sending')