def stop(self): """ Signals the process to stop acquiring data. :return: """ Log.i(TAG, "Process finishing...") self._exit.set()
def __init__(self, parser_process): """ Initialises values for process. :param parser_process: Reference to a ParserProcess instance. :type parser_process: ParserProcess """ multiprocessing.Process.__init__(self) self._exit = multiprocessing.Event() self._parser = parser_process self._socket_client = socket.socket(socket.AF_INET, socket.SOCK_STREAM) Log.i(TAG, "Process Ready")
def __init__(self, parser_process): """ Initialises values for process. :param parser_process: Reference to a ParserProcess instance. :type parser_process: ParserProcess. """ multiprocessing.Process.__init__(self) self._exit = multiprocessing.Event() self._period = None self._parser = parser_process Log.i(TAG, "Process Ready")
def stop(self): self._acquisition_process.stop() self._parser_process.stop() ''' for process in [self._acquisition_process, self._parser_process]: if process is not None and process.is_alive(): process.stop() process.join(Constants.process_join_timeout_ms) ''' print(TAG, 'Running processes stopped...') print(TAG, 'Processes finished') Log.i(TAG, "Running processes stopped...") Log.i(TAG, "Processes finished")
def run(self): """ Simulates raw data incoming as CSV. :return: """ Log.i(TAG, "Process starting...") timestamp = time() coef = 2 * np.pi while not self._exit.is_set(): stamp = time() - timestamp self._parser.add([stamp, str(("{},{},{}\r\n".format(np.sin(coef * stamp), np.cos(coef * stamp), np.cos(1.5*coef * stamp)))) .encode(Constants.app_encoding)]) sleep(self._period) Log.i(TAG, "Process finished")
def CSVsave(filename, path, data_save0, data_save1, data_save2, data_save3): """ :param filename: Name for the file :type filename: str. :param path: Path for the file :type path: str. :param data_save1: data to store (resonance frequency) :type float. :param data_save2: data to store (dissipation) :type float. """ # Creates a directory if the specified path doesn't exist #FileManager.create_dir(path) # Creates a file full path based on parameters full_path = FileManager.create_full_path( filename, extension=Constants.csv_extension, path=path) if not FileManager.file_exists(full_path): print("\n") print(TAG, "Exporting data to CSV file...") print(TAG, "Storing in: {}".format(full_path)) Log.i(TAG, "Storing in: {}".format(full_path)) # checks the path for the header insertion if os.path.exists(full_path): header_exists = True else: header_exists = False # opens the file to write data with open(full_path, 'a', newline='') as tempFile: tempFileWriter = csv.writer(tempFile) # inserts the header if it doesn't exist if not header_exists: tempFileWriter.writerow([ "Date", "Time", "Relative_time", "Temperature", "Resonance_Frequency", "Dissipation" ]) #csv_time_prefix = strftime(Constants.csv_default_prefix, localtime()) #now = datetime.datetime.now() #csv_time_prefix = "{}-{}-{}.{}:{}:{}.{}".format(now.year,now.month,now.day,now.hour,now.minute,now.second,now.microsecond) fix1 = "%Y-%m-%d" fix2 = "%H:%M:%S" csv_time_prefix1 = (strftime(fix1, localtime())) csv_time_prefix2 = (strftime(fix2, localtime())) d0 = float("{0:.2f}".format(data_save0)) d1 = float("{0:.2f}".format(data_save1)) d2 = float("{0:.2f}".format(data_save2)) #d3=float("{0:.4e}".format(data_save3)) tempFileWriter.writerow( [csv_time_prefix1, csv_time_prefix2, d0, d1, d2, data_save3]) #tempFileWriter.writerow([csv_time_prefix, data_save1, data_save2, data_save3]) tempFile.close()
def get_source_speeds(source): """ :param source: Source to get available speeds :type source: SourceType. :return: List of available speeds :rtype: str list. """ if source == SourceType.serial: return SerialProcess.get_speeds() elif source == SourceType.calibration: return CalibrationProcess.get_speeds() elif source == SourceType.SocketClient: return SocketProcess.get_default_port() else: print(TAG, 'Unknown source selected') Log.w(TAG, "Unknown source selected") return None
def open(self, port=None, speed=Constants.simulator_default_speed, timeout=0.5): """ Opens a specified serial port. :param port: Not used. :type port: str. :param speed: Period of the generated signal. :type speed: float. :param timeout: Not used. :type timeout: float. :return: True if the port is available. :rtype: bool. """ self._period = float(speed) Log.i(TAG, "Using sample rate at {}".format(self._period)) return True
def get_source_ports(source): """ :param source: Source to get available ports :type source: SourceType. :return: List of available ports :rtype: str list. """ if source == SourceType.serial: print(TAG, 'Port connected:', SerialProcess.get_ports()) return SerialProcess.get_ports() elif source == SourceType.calibration: print(TAG, 'Port connected:', CalibrationProcess.get_ports()) return CalibrationProcess.get_ports() elif source == SourceType.SocketClient: return SocketProcess.get_default_host() else: print(TAG, 'Warning: unknown source selected') Log.w(TAG, "Unknown source selected") return None
def open(self, port='', speed=5555, timeout=0.01): """ Opens a socket connection to specified host and port :param port: Host address to connect to. :type port: str. :param speed: Port number to connect to. :type speed: int. :param timeout: Sets timeout for socket interactions. :type timeout: float. :return: True if the connection was open. :rtype: bool. """ try: #self._socket_client.timeout = timeout speed = int(speed) self._socket_client.connect((port, speed)) Log.i(TAG, "Socket open {}:{}".format(port, speed)) return True except socket.timeout: Log.w(TAG, "Connection timeout") return False
def run(self): """ Reads the socket until a stop call is made. :return: """ Log.i(TAG, "Process starting...") timestamp = time() while not self._exit.is_set(): stamp = time() - timestamp try: data = self._socket_client.recv(Constants.SocketClient.buffer_recv_size).decode() if len(data) > 0: self._parser.add([stamp, data]) except socket.timeout: Log.w(TAG, "read timeout") Log.i(TAG, "Process finished")
def start(self): if self._source == SourceType.serial: self._samples = Constants.argument_default_samples elif self._source == SourceType.calibration: self._samples = Constants.calibration_default_samples self._readFREQ = Constants.calibration_readFREQ # Setup/reset the internal buffers self.reset_buffers(self._samples) # Instantiates process self._parser_process = ParserProcess(self._queue1, self._queue2, self._queue3, self._queue4, self._queue5, self._queue6) # Checks the type of source if self._source == SourceType.serial: self._acquisition_process = SerialProcess(self._parser_process) elif self._source == SourceType.calibration: self._acquisition_process = CalibrationProcess( self._parser_process) elif self._source == SourceType.SocketClient: self._acquisition_process = SocketProcess(self._parser_process) if self._acquisition_process.open(port=self._port, speed=self._speed): if self._source == SourceType.serial: (self._overtone_name, self._overtone_value, self._fStep, self._readFREQ, SG_window_size, spline_points, spline_factor) = self._acquisition_process.get_frequencies( self._samples) #print(TAG, "Quartz Crystal Sensor installed: {}".format(self._QCS_on)) print("") print(TAG, "DATA MAIN INFORMATION") print( TAG, "Selected frequency: {} - {}Hz".format( self._overtone_name, self._overtone_value)) print(TAG, "Frequency start: {}Hz".format(self._readFREQ[0])) print(TAG, "Frequency stop: {}Hz".format(self._readFREQ[-1])) print( TAG, "Frequency range: {}Hz".format(self._readFREQ[-1] - self._readFREQ[0])) print(TAG, "Number of samples: {}".format(self._samples - 1)) print(TAG, "Sample rate: {}Hz".format(self._fStep)) print(TAG, "History buffer size: 180 min\n") print(TAG, "MAIN PROCESSING INFORMATION") print(TAG, "Method for baseline estimation and correction:") print(TAG, "Least Squares Polynomial Fit (LSP)") #print(TAG, "Degree of the fitting polynomial: 8") print(TAG, "Savitzky-Golay Filtering") print( TAG, "Order of the polynomial fit: {}".format( Constants.SG_order)) print( TAG, "Size of data window (in samples): {}".format( SG_window_size)) print(TAG, "Oversampling using spline interpolation") print( TAG, "Spline points (in samples): {}".format(spline_points - 1)) print( TAG, "Resolution after oversampling: {}Hz".format( (self._readFREQ[-1] - self._readFREQ[0]) / (spline_points - 1))) elif self._source == SourceType.calibration: print("") print(TAG, "MAIN CALIBRATION INFORMATION") print( TAG, "Calibration frequency start: {}Hz".format( Constants.calibration_frequency_start)) print( TAG, "Calibration frequency stop: {}Hz".format( Constants.calibration_frequency_stop)) print( TAG, "Frequency range: {}Hz".format( Constants.calibration_frequency_stop - Constants.calibration_frequency_start)) print( TAG, "Number of samples: {}".format( Constants.calibration_default_samples - 1)) print(TAG, "Sample rate: {}Hz".format(Constants.calibration_fStep)) print(TAG, 'Training for plot...\n') # Starts processes self._acquisition_process.start() self._parser_process.start() return True else: print(TAG, 'Warning: port is not available') Log.i(TAG, "Warning: Port is not available") return False
def set_user_log_level(self): if self._parser is not None: self._parse_log_level() else: Log.w(TAG, "Parser was not created!") return None