def quit(self): """Stop player, stop loop, clean bus""" logging.debug("Quit player") self.stop() self.bus.disconnect(self.bus_handler_id) try:self.loop.quit() except:pass
def handle_command(self, command: object) -> None: """Handle a command from the server""" logging.debug('Server command: {}', command) if isinstance( command, SetMotorSpeedsCommand): # Server requested new motor speeds # Try and connect to the Arduino if it is not connected if not self.arduino.is_connected() and self.arduino.connect(): # Inform the server that the Arduino connection state has changed send_obj(self.sock, ArduinoConnectionMessage(True)) # Try and write the motor speeds to the Arduino if it is connected if self.arduino.is_connected(): try: self.arduino.write_speeds(command.motor_speeds) except serial.SerialException: # Error writing motor speeds, disconnect and inform the server self.arduino.disconnect() send_obj(self.sock, ArduinoConnectionMessage(False)) elif isinstance(command, SetCameraCommand): # Server requested new camera index # Set the currently playing camera stream to PAUSED self.active_camera_stream.set_paused() # Set the the new camera stream to PLAYING self.active_camera_stream = self.camera_streams[ command.camera_index] self.active_camera_stream.set_playing() elif isinstance( command, PlaySoundCommand): # Server requested that a sound be played # Stop the currently playing sound, if any self.sound_player.stop() # If a sound filename was provided, play the sound if command.filename is not None: self.sound_player.play(command.filename, command.vol_mb, command.amp_mb)
def fetch(url): ''' return arbitrary URL data ''' filename = posixpath.split(url)[-1] logging.info('attempting to fetch %s', filename) filepath = os.path.join(STORAGE, filename) if filename.endswith(".zip"): unzippedname = filename[:-4] unzippedpath = os.path.join(STORAGE, unzippedname) if os.path.exists(unzippedpath): logging.debug('found cached content %s', unzippedpath) with open(unzippedpath, 'rb') as infile: return infile.read() if not os.path.exists(filepath): logging.info('fetching %s', url) with urlopen(url) as infile: with open(filepath, 'wb') as outfile: outfile.write(infile.read()) if filename.endswith(".zip"): zipped = zipfile.ZipFile(filepath) with zipped.open(unzippedname, 'r') as datafile: # 'rb' not accepted data = datafile.read() logging.debug('caching %s for next time', unzippedname) with open(unzippedpath, 'wb') as outfile: outfile.write(data) return data else: with open(filepath, 'rb') as infile: return infile.read()
def handle_message(self, message: object) -> None: """Handle a message from the client""" logging.debug('Client message: {}', message) if isinstance(message, ArduinoConnectionMessage): pass # TODO: Update self.window elif isinstance(message, SystemInfoMessage): pass # TODO: Update self.window
def read(xpath): try: wait.until(ec.visibility_of_all_elements_located((By.XPATH, xpath))) text = driver.find_element_by_xpath(xpath).text return text.split() except: log.debug('Cannot Read:' + xpath) return []
def array(rawdata): ''' split HGT 16-bit signed values into an integer array ''' data = [ struct.unpack('>h', rawdata[i:i + 2])[0] for i in range(0, len(rawdata), 2) ] logging.debug('data[:10]: %s', data[:10]) return data
def hgtfetch(prefix=None): ''' return HGT data ''' if prefix is None: query = cgi.FieldStorage() logging.debug('query: %s', dict(query)) prefix = query.getfirst('request') url = posixpath.join(HGT_SERVER, prefix + ".hgt.zip") return fill_voids(array(fetch(url)))
def rawsize(f): try: raw = rawfile(f) pos = raw.tell() raw.seek(-1, 2) size = raw.tell() raw.seek(pos, 0) return size except Exception as e: logging.debug(e) return -1
def reads(xpath): try: wait.until(ec.visibility_of_all_elements_located((By.XPATH, xpath))) elements = driver.find_elements_by_xpath(xpath) texts = [] for element in elements: texts.append(element.text) return texts except: log.debug('Cannot Read:' + xpath) return []
def play(self,filepath): """ Call :func:`stop`, then :func:`load`. Finally, the gstreamer status is set to PLAY. If filepath can not be player, raise FileCannotBePlayed exception. :rtype: The return value of :func:`load`. """ self.stop() if self.load(filepath): self.player.set_state(gst.STATE_PLAYING) logging.debug("Play %s" % filepath) return True else: logging.warning("File '%s' can not be played" % filepath) raise FileCannotBePlayed(filepath)
def create_colormap(view=False): ''' map all expected values to a color -32768 means 'no data', and nothing outside of the range -1000 to +9000 is expected. ''' colormap = OrderedDict() colorbytes = b'' blueratio = math.floor(GREEN / BLUE) red, blue, green = NONE, COMPLETELY, COMPLETELY i = 0 underwater = {} while green > blueratio: underwater[i] = (red, green, blue, OPAQUE) blue -= 1 i -= 1 if green - blue == blueratio: green -= 1 blue = green colormap.update({k: underwater[k] for k in sorted(underwater)}) logging.debug('colormap with underwater values: %s', colormap) # now compute the positive values blueratio = math.floor(1 / BLUE) redratio = math.floor(1 / RED) # ensure that no values are greater than 255 maxgreen = 256 - max(blueratio, redratio) samples = ((i, 0, j) for i in range(redratio + 1) for j in range(blueratio + 1)) brightnesses = { sample: brightness(*sample) for sample in samples if brightness(*sample) < 1 } # sorted dict https://stackoverflow.com/a/613218/493161 pattern = OrderedDict(sorted(brightnesses.items(), key=lambda kv: kv[1])) logging.debug('pattern: %s', pattern) logging.debug('possibilities: about %d values', 256 * len(brightnesses)) permutations = list(pattern.keys()) colormap.update({ g * len(permutations) + i + 1: (permutations[i][0] + g, g, permutations[i][2] + g, OPAQUE) for g in range(maxgreen) for i in range(len(permutations)) }) values = len(colormap) logging.debug('colormap length: %d', values) if (view) and 'Image' in globals(): # display an image of the expected values width = height = 100 start = -1000 size = width * height colorbytes = b''.join( struct.pack('BBBB', *colormap[i]) for i in colormap.keys() if i > start and i < size) testimage = Image.frombytes('RGBA', (width, height), colorbytes) testimage.show() return colormap
def rawfile(f): if hasattr(f, 'myfileobj'): # for archive files such as gzip return f.myfileobj # if isinstance(f, gzip.GzipFile): # return f.myfileobj elif hasattr(f, 'buffer'): # for buffered files such as utf-8 mode #return f.buffer # might be duplicated buffer return rawfile(f.buffer) #elif isIOType(f): elif isinstance(f, FileType): return f else: logging.debug(f) #logging.debug(type(f)) #logging.debug(dir(f)) assert False
def _on_message(self, bus, message): t = message.type if t == gst.MESSAGE_EOS: self.player.set_state(gst.STATE_NULL) logging.debug("pygst: End of File") self.__pygstSetState__('eof') self._ready.clear() logging.debug("Player Thread : %s" % threading.currentThread()) self.queue() elif t == gst.MESSAGE_ERROR: self.player.set_state(gst.STATE_NULL) err, debug = message.parse_error() self.handle_error() self.__pygstSetState__('error') logging.critical("PyGST internal error : %s | %s" % (err, debug)) elif t == gst.MESSAGE_STATE_CHANGED: if message.src is self.player: old, new, pending = message.parse_state_changed() if new==gst.STATE_PAUSED or new==gst.STATE_PLAYING or new==gst.STATE_READY: self.__pygstSetState__('ready')
def load(self,filepath,secure=True): """ Load a file in pygst and set player to STATE_PAUSED. File can be played easily or you can get some informations on file (duration ...). If the thread player calls this method, errors are not detected, in particular, gstreamer error. However, you can see error in debug log. :rtype: False if: * the file type can not be determined * the file doesnt exist * the player is playing """ if filepath != None and os.path.isfile(filepath): if self.player.get_state()[1] == gst.STATE_PLAYING: return False else: self.player.set_property("uri", "file://" + urllib.quote(filepath)) s=self.player.set_state(gst.STATE_PAUSED) # Ensure that pygst acceptes file If player thread calls this method, # gst is waiting the return of this method, and then messages # (_on_message method) can not be handled. # if not threading.currentThread().ident == self._playerThreadId: # self._pygstCondition.acquire() # while True: # state=self.__pygstGetState__() # if state=='ready' or state=='error':break # print "Before Wait cur: %s , player: %s" % (threading.currentThread(),self._playerThreadId) # self._pygstCondition.wait() # print "End Wait %s" % threading.currentThread() # self._pygstCondition.release() # if state == 'error': # raise common.PyGstError(filepath) # return False if s == gst.STATE_CHANGE_FAILURE: logging.debug("File can not be loaded %s" % filepath) return False return True else: return False
row[indices[0]:indices[1]] = run indices[0] = indices[1] data[rowstart:rowstart + side] = row return data def find_run(array): ''' return array length in which a[n] == a[n + 1] where n = 0..len(array) - 2 >>> find_run([0, 0, 0, 1]) 3 >>> find_run([0, 0, 0, 0]) 4 ''' for key, iterator in groupby(array): return len(list(iterator)) if __name__ == '__main__': init() logging.debug('before cleaning: sys.argv: %s', sys.argv) sys.argv = [arg for arg in sys.argv if arg] logging.debug('after cleaning: sys.argv: %s', sys.argv) if len(sys.argv) == 1 or re.compile(r'^\w+$').match(sys.argv[1]): print('Content-type: text/json\r\n\r\n', end='') print(hgtfetch((sys.argv + [None])[1]), end='') else: print('Content-type: text/plain\r\n\r\n', end='') print(fetch(sys.argv[1]), end='')
def click(xpath): try: wait.until(ec.element_to_be_clickable((By.XPATH, xpath))) driver.find_element_by_xpath(xpath).click() except: log.debug('Cannot Click:' + xpath)
def insert(xpath, value): try: wait.until(ec.visibility_of_all_elements_located((By.XPATH, xpath))) driver.find_element_by_xpath(xpath).send_keys(value) except: log.debug('Cannot Insert:' + xpath)