INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Return Roster object that contains roster info for a team
def roster(team_id): """Return Roster object that contains roster info for a team""" data = mlbgame.info.roster(team_id) return mlbgame.info.Roster(data)
Return Standings object that contains standings info date should be a datetime object, leave empty to get current standings
def standings(date=datetime.now()): """Return Standings object that contains standings info date should be a datetime object, leave empty to get current standings """ data = mlbgame.info.standings(date) return mlbgame.info.Standings(data)
Return BroadcastInfo object that containts information about the television and radio broadcasts for the team_id and year
def broadcast_info(team_id, date=datetime.now()): """Return BroadcastInfo object that containts information about the television and radio broadcasts for the team_id and year""" data = mlbgame.info.broadcast_info(team_id, date) return [mlbgame.info.BroadcastInfo(x) for x in data]
Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return the data from both.
def player_stats(game_id): """Return dictionary of individual stats of a game with matching id. The additional pitching/batting is mostly the same stats, except it contains some useful stats such as groundouts/flyouts per pitcher (go/ao). MLB decided to have two box score files, thus we return...
Return team stats of a game with matching id. The additional pitching/batting is mostly the same stats. MLB decided to have two box score files, thus we return the data from both.
def team_stats(game_id): """Return team stats of a game with matching id. The additional pitching/batting is mostly the same stats. MLB decided to have two box score files, thus we return the data from both. """ # get data from data module box_score = mlbgame.data.get_box_score(game_id) raw...
Returns the xml object corresponding to the league Only designed for internal use
def __get_league_object(): """Returns the xml object corresponding to the league Only designed for internal use""" # get data data = mlbgame.data.get_properties() # return league object return etree.parse(data).getroot().find('leagues').find('league')
Returns a dictionary of league information
def league_info(): """Returns a dictionary of league information""" league = __get_league_object() output = {} for x in league.attrib: output[x] = league.attrib[x] return output
Returns a list of team information dictionaries
def team_info(): """Returns a list of team information dictionaries""" teams = __get_league_object().find('teams').findall('team') output = [] for team in teams: info = {} for x in team.attrib: info[x] = team.attrib[x] output.append(info) return output
Returns a dictionary of important dates
def important_dates(year): """Returns a dictionary of important dates""" output = {} data = mlbgame.data.get_important_dates(year) important_dates = etree.parse(data).getroot().\ find('queryResults').find('row') try: for x in important_dates.attrib: output[x] = important_...
Returns a dictionary of broadcast information for a given team during a given season
def broadcast_info(team_id, date=datetime.now()): """Returns a dictionary of broadcast information for a given team during a given season""" year = date.year game_date = date.strftime('%Y-%m-%dT00:00:00') data = mlbgame.data.get_broadcast_info(team_id, year) schedule = json.loads(data.read().dec...
Returns a dictionary of roster information for team id
def roster(team_id): """Returns a dictionary of roster information for team id""" data = mlbgame.data.get_roster(team_id) parsed = json.loads(data.read().decode('utf-8')) players = parsed['roster_40']['queryResults']['row'] return {'players': players, 'team_id': team_id}
Return a string for printing
def nice_output(self): """Return a string for printing""" dates = [ str_format('Opening Day {0}: {1}.', [self.year, date_format(self.first_date_seas)]), str_format('Last day of the 1st half: {0}.', [date_format(self.last_date_1sth)]),...
Return dictionary of events for a game with matching id.
def game_events(game_id, innings_endpoint=False): """Return dictionary of events for a game with matching id.""" # get data from data module if not innings_endpoint: data = mlbgame.data.get_game_events(game_id) endpoint = 'game_events' else: data = mlbgame.data.get_innings(game_i...
Return a DHT platform interface for the currently detected platform.
def get_platform(): """Return a DHT platform interface for the currently detected platform.""" plat = platform_detect.platform_detect() if plat == platform_detect.RASPBERRY_PI: # Check for version 1 or 2 of the pi. version = platform_detect.pi_version() if version == 1: f...
Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Note that because the sensor requires strict timing to read and Linux is not a real time OS, a...
def read(sensor, pin, platform=None): """Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Note that because the sensor requires strict timing t...
Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Unlike the read function, this read_retry function will attempt to read multiple times (up to ...
def read_retry(sensor, pin, retries=15, delay_seconds=2, platform=None): """Read DHT sensor of specified sensor type (DHT11, DHT22, or AM2302) on specified pin and return a tuple of humidity (as a floating point value in percent) and temperature (as a floating point value in Celsius). Unlike the read fu...
Connect to Google Docs spreadsheet and return the first worksheet.
def login_open_sheet(oauth_key_file, spreadsheet): """Connect to Google Docs spreadsheet and return the first worksheet.""" try: scope = ['https://spreadsheets.google.com/feeds'] credentials = ServiceAccountCredentials.from_json_keyfile_name(oauth_key_file, scope) gc = gspread.authorize...
Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.
def platform_detect(): """Detect if running on the Raspberry Pi or Beaglebone Black and return the platform type. Will return RASPBERRY_PI, BEAGLEBONE_BLACK, or UNKNOWN.""" # Handle Raspberry Pi pi = pi_version() if pi is not None: return RASPBERRY_PI # Handle Beaglebone Black # TO...
Detect the revision number of a Raspberry Pi, useful for changing functionality like default I2C bus based on revision.
def pi_revision(): """Detect the revision number of a Raspberry Pi, useful for changing functionality like default I2C bus based on revision.""" # Revision list available at: http://elinux.org/RPi_HardwareHistory#Board_Revision_History with open('/proc/cpuinfo', 'r') as infile: for line in infil...
Handles getting the password
def handle_password(user, password): # pragma: no cover """ Handles getting the password""" if password is None: try: password = keyring.get_password("yagmail", user) except NameError as e: print( "'keyring' cannot be loaded. Try 'pip install keyring' or ...
Handle the targets addresses, adding aliases when defined
def resolve_addresses(user, useralias, to, cc, bcc): """ Handle the targets addresses, adding aliases when defined """ addresses = {"recipients": []} if to is not None: make_addr_alias_target(to, addresses, "To") elif cc is not None and bcc is not None: make_addr_alias_target([user, user...
This is the function that is run from commandline with `yagmail`
def main(): """ This is the function that is run from commandline with `yagmail` """ import argparse parser = argparse.ArgumentParser(description='Send a (g)mail with yagmail.') subparsers = parser.add_subparsers(dest="command") oauth = subparsers.add_parser('oauth') oauth.add_argument( ...
Prepare a MIME message
def prepare_message(user, useralias, addresses, subject, contents, attachments, headers, encoding, newline_to_break=True): # check if closed!!!!!! XXX """ Prepare a MIME message """ if isinstance(contents, text_type): contents = [contents] if isinstance(attachments, text_type): attachmen...
Note that this will only filter out syntax mistakes in emailaddresses. If a human would think it is probably a valid email, it will most likely pass. However, it could still very well be that the actual emailaddress has simply not be claimed by anyone (so then this function fails to devalidate).
def validate_email_with_regex(email_address): """ Note that this will only filter out syntax mistakes in emailaddresses. If a human would think it is probably a valid email, it will most likely pass. However, it could still very well be that the actual emailaddress has simply not be claimed by anyon...
This function allows to change the logging backend, either output or file as backend It also allows to set the logging level (whether to display only critical/error/info/debug. for example:: yag = yagmail.SMTP() yag.set_logging(yagmail.logging.DEBUG) # to see everything ...
def set_logging(self, log_level=logging.ERROR, file_path_name=None): """ This function allows to change the logging backend, either output or file as backend It also allows to set the logging level (whether to display only critical/error/info/debug. for example:: yag = yagma...
Use this to send an email with gmail
def send( self, to=None, subject=None, contents=None, attachments=None, cc=None, bcc=None, preview_only=False, headers=None, newline_to_break=True, ): """ Use this to send an email with gmail""" self.login() reci...
Emails that were not being able to send will be stored in :attr:`self.unsent`. Use this function to attempt to send these again
def send_unsent(self): """ Emails that were not being able to send will be stored in :attr:`self.unsent`. Use this function to attempt to send these again """ for i in range(len(self.unsent)): recipients, msg_string = self.unsent.pop(i) self._attempt_send(...
Close the connection to the SMTP server
def close(self): """ Close the connection to the SMTP server """ self.is_closed = True try: self.smtp.quit() except (TypeError, AttributeError, smtplib.SMTPServerDisconnected): pass
Login to the SMTP server using password. `login` only needs to be manually run when the connection to the SMTP server was closed by the user.
def _login(self, password): """ Login to the SMTP server using password. `login` only needs to be manually run when the connection to the SMTP server was closed by the user. """ self.smtp = self.connection(self.host, self.port, **self.kwargs) self.smtp.set_debuglevel(self...
Start the server.
def start(self): """ Start the server. """ plugins = voltron.plugin.pm.web_plugins self.app = DispatcherMiddleware( RootFlaskApp(), { "/api": APIFlaskApp(server=self), "/view": SharedDataMiddleware( None,...
Stop the server.
def stop(self): """ Stop the server. """ log.debug("Stopping listeners") self.queue_lock.acquire() for s in self.listeners: log.debug("Stopping {}".format(s)) s.shutdown() s.socket.close() self.cancel_queue() for t in se...
Cancel all requests in the queue so we can exit.
def cancel_queue(self): """ Cancel all requests in the queue so we can exit. """ q = list(self.queue) self.queue = [] log.debug("Canceling requests: {}".format(q)) for req in q: req.response = APIServerNotRunningErrorResponse() for req in q: ...
Dispatch any queued requests. Called by the debugger when it stops.
def dispatch_queue(self): """ Dispatch any queued requests. Called by the debugger when it stops. """ self.queue_lock.acquire() q = list(self.queue) self.queue = [] self.queue_lock.release() log.debug("Dispatching requests: {}".format(q)) ...
Dispatch a request object.
def dispatch_request(self, req): """ Dispatch a request object. """ log.debug("Dispatching request: {}".format(str(req))) # make sure it's valid res = None try: req.validate() except MissingFieldError as e: res = APIMissingFieldErr...
Send a request to the server. `request` is an APIRequest subclass. Returns an APIResponse or subclass instance. If an error occurred, it will be an APIErrorResponse, if the request was successful it will be the plugin's specified response class if one exists, otherwise it will ...
def send_request(self, request): """ Send a request to the server. `request` is an APIRequest subclass. Returns an APIResponse or subclass instance. If an error occurred, it will be an APIErrorResponse, if the request was successful it will be the plugin's specified res...
Send a set of requests. Each request is sent over its own connection and the function will return when all the requests have been fulfilled.
def send_requests(self, *args): """ Send a set of requests. Each request is sent over its own connection and the function will return when all the requests have been fulfilled. """ threads = [ClientThread(self, req) for req in args] for t in threads: ...
Create and send a request. `request_type` is the request type (string). This is used to look up a plugin, whose request class is instantiated and passed the remaining arguments passed to this function.
def perform_request(self, request_type, *args, **kwargs): """ Create and send a request. `request_type` is the request type (string). This is used to look up a plugin, whose request class is instantiated and passed the remaining arguments passed to this function. """ ...
Update the display
def update(self): """ Update the display """ # build requests for this iteration reqs = self.build_requests() for r in reqs: r.block = self.block results = self.send_requests(*reqs) # call callback with the results self.callback(result...
Run the client in a loop, calling the callback each time the debugger stops.
def run(self, build_requests=None, callback=None): """ Run the client in a loop, calling the callback each time the debugger stops. """ if callback: self.callback = callback if build_requests: self.build_requests = build_requests def norma...
Run the client using a background thread.
def start(self, build_requests=None, callback=None): """ Run the client using a background thread. """ if callback: self.callback = callback if build_requests: self.build_requests = build_requests # spin off requester thread self.sw = thre...
Decorator to designate an API method applicable only to server-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion.
def server_side(func): """ Decorator to designate an API method applicable only to server-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion. """ def inner(*args, **kwargs): if args and hasat...
Decorator to designate an API method applicable only to client-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion.
def client_side(func): """ Decorator to designate an API method applicable only to client-side instances. This allows us to use the same APIRequest and APIResponse subclasses on the client and server sides without too much confusion. """ def inner(*args, **kwargs): if args and hasat...
Return a transmission-safe dictionary representation of the API message properties.
def to_dict(self): """ Return a transmission-safe dictionary representation of the API message properties. """ d = {field: getattr(self, field) for field in self._top_fields if hasattr(self, field)} # set values of data fields d['data'] = {} for field in self._fi...
Initialise an API message from a transmission-safe dictionary.
def from_dict(self, d): """ Initialise an API message from a transmission-safe dictionary. """ for key in d: if key == 'data': for dkey in d['data']: if dkey in self._encode_fields: setattr(self, str(dkey), base64.b6...
Initialise an API message from a JSON representation.
def from_json(self, data): """ Initialise an API message from a JSON representation. """ try: d = json.loads(data) except ValueError: raise InvalidMessageException() self.from_dict(d)
Validate the message. Ensure all the required fields are present and not None.
def validate(self): """ Validate the message. Ensure all the required fields are present and not None. """ required_fields = list(filter(lambda x: self._fields[x], self._fields.keys())) for field in (self._top_fields + required_fields): if not hasattr(self, f...
Wait for the request to be dispatched.
def wait(self): """ Wait for the request to be dispatched. """ self.wait_event = threading.Event() timeout = int(self.timeout) if self.timeout else None self.timed_out = not self.wait_event.wait(timeout)
A decorator that ensures that the specified target_id exists and is valid. Expects the target ID to be either the 'target_id' param in kwargs, or the first positional parameter. Raises a NoSuchTargetException if the target does not exist.
def validate_target(func, *args, **kwargs): """ A decorator that ensures that the specified target_id exists and is valid. Expects the target ID to be either the 'target_id' param in kwargs, or the first positional parameter. Raises a NoSuchTargetException if the target does not exist. """...
A decorator that raises an exception if the specified target is busy. Expects the target ID to be either the 'target_id' param in kwargs, or the first positional parameter. Raises a TargetBusyException if the target does not exist.
def validate_busy(func, *args, **kwargs): """ A decorator that raises an exception if the specified target is busy. Expects the target ID to be either the 'target_id' param in kwargs, or the first positional parameter. Raises a TargetBusyException if the target does not exist. """ def inne...
A decorator that acquires a lock before accessing the debugger to avoid API locking related errors with the debugger host.
def lock_host(func, *args, **kwargs): """ A decorator that acquires a lock before accessing the debugger to avoid API locking related errors with the debugger host. """ def inner(self, *args, **kwargs): self.host_lock.acquire() try: res = func(self, *args, **kwargs) ...
Returns True or False indicating whether or not the specified target is present and valid. `target_id` is a target ID (or None for the first target)
def target_exists(self, target_id=0): """ Returns True or False indicating whether or not the specified target is present and valid. `target_id` is a target ID (or None for the first target) """ try: target = self._target(target_id=target_id) except E...
Returns True or False indicating whether or not the specified target is present and valid. `target_id` is a target ID (or None for the first target)
def target_is_valid(self, target_id=0): """ Returns True or False indicating whether or not the specified target is present and valid. `target_id` is a target ID (or None for the first target) """ try: target = self._target(target_id=target_id) except...
Returns True or False indicating whether or not the specified target is busy. `target_id` is a target ID (or None for the first target)
def target_is_busy(self, target_id=0): """ Returns True or False indicating whether or not the specified target is busy. `target_id` is a target ID (or None for the first target) """ try: target = self._target(target_id=target_id) except: ...
Remove a listener.
def remove_listener(self, callback): """ Remove a listener. """ listeners = filter(lambda x: x['callback'] == callback, self.listeners) for l in listeners: self.listeners.remove(l)
Disassemble with capstone.
def disassemble_capstone(self, target_id=0, address=None, count=None): """ Disassemble with capstone. """ target = self._target(target_id) if not address: pc_name, address = self.pc() mem = self.memory(address, count * 16, target_id=target_id) md = c...
Create an API request. `request_type` is the request type (string). This is used to look up a plugin, whose request class is instantiated and passed the remaining arguments passed to this function.
def api_request(request, *args, **kwargs): """ Create an API request. `request_type` is the request type (string). This is used to look up a plugin, whose request class is instantiated and passed the remaining arguments passed to this function. """ plugin = pm.api_plugin_for_request(request...
Register a new plugin with the PluginManager. `plugin` is a subclass of scruffy's Plugin class. This is called by __init__(), but may also be called by the debugger host to load a specific plugin at runtime.
def register_plugin(self, plugin): """ Register a new plugin with the PluginManager. `plugin` is a subclass of scruffy's Plugin class. This is called by __init__(), but may also be called by the debugger host to load a specific plugin at runtime. """ if hasattr(...
Validate an API plugin, ensuring it is an API plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class.
def valid_api_plugin(self, plugin): """ Validate an API plugin, ensuring it is an API plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class. """ if (issubclass(plugin, APIPlugin) and hasattr(plugin, 'plugin_type')...
Validate a debugger plugin, ensuring it is a debugger plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class.
def valid_debugger_plugin(self, plugin): """ Validate a debugger plugin, ensuring it is a debugger plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class. """ if (issubclass(plugin, DebuggerAdaptorPlugin) and hasattr(plu...
Validate a view plugin, ensuring it is a view plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class.
def valid_view_plugin(self, plugin): """ Validate a view plugin, ensuring it is a view plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class. """ if (issubclass(plugin, ViewPlugin) and hasattr(plugin, 'plugin_type'...
Validate a web plugin, ensuring it is a web plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class.
def valid_web_plugin(self, plugin): """ Validate a web plugin, ensuring it is a web plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class. """ if (issubclass(plugin, WebPlugin) and hasattr(plugin, 'plugin_type') ...
Validate a command plugin, ensuring it is a command plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class.
def valid_command_plugin(self, plugin): """ Validate a command plugin, ensuring it is a command plugin and has the necessary fields present. `plugin` is a subclass of scruffy's Plugin class. """ if (issubclass(plugin, CommandPlugin) and hasattr(plugin, 'plu...
Try to detect the two most common installation errors: 1. Installing on macOS using a Homebrew version of Python 2. Installing on Linux using Python 2 when GDB is linked with Python 3
def check_install(): """ Try to detect the two most common installation errors: 1. Installing on macOS using a Homebrew version of Python 2. Installing on Linux using Python 2 when GDB is linked with Python 3 """ if platform.system() == 'Darwin' and sys.executable != '/usr/bin/python': ...
Run the view event loop.
def run(self): """ Run the view event loop. """ def render(results=[], error=None): if len(results) and not results[0].timed_out: self.render(results) elif error: self.do_render(error=error) # start the client self....
Handle a keypress. Concrete subclasses can implement this method if custom keypresses need to be handled other than for exit and scrolling.
def handle_key(self, key): """ Handle a keypress. Concrete subclasses can implement this method if custom keypresses need to be handled other than for exit and scrolling. """ try: func = None if key.is_sequence: try: fun...
Handle reception of a new CastStatus.
def new_cast_status(self, cast_status): """Handle reception of a new CastStatus.""" casts = self._casts group_members = self._mz.members for member_uuid in group_members: if member_uuid not in casts: continue for listener in list(casts[member_uuid]...
Handle reception of a new MediaStatus.
def new_media_status(self, media_status): """Handle reception of a new MediaStatus.""" casts = self._casts group_members = self._mz.members for member_uuid in group_members: if member_uuid not in casts: continue for listener in list(casts[member_uu...
Handle reception of a new ConnectionStatus.
def new_connection_status(self, conn_status): """Handle reception of a new ConnectionStatus.""" if conn_status.status == CONNECTION_STATUS_CONNECTED: self._mz.update_members() if (conn_status.status == CONNECTION_STATUS_DISCONNECTED or conn_status.status == CONNECTION...
Handle added audio group member.
def multizone_member_added(self, member_uuid): """Handle added audio group member.""" casts = self._casts if member_uuid not in casts: casts[member_uuid] = {'listeners': [], 'groups': set()} casts[member_uuid]['groups'].add(self._group_uuid) ...
Handle removed audio group member.
def multizone_member_removed(self, member_uuid): """Handle removed audio group member.""" casts = self._casts if member_uuid not in casts: casts[member_uuid] = {'listeners': [], 'groups': set()} casts[member_uuid]['groups'].discard(self._group_uuid) for listener in li...
Start managing a group
def add_multizone(self, group_cast): """ Start managing a group """ self._groups[str(group_cast.uuid)] = { 'chromecast': group_cast, 'listener': Listener(group_cast, self._casts), 'members': set()}
Stop managing a group
def remove_multizone(self, group_uuid): """ Stop managing a group """ group_uuid = str(group_uuid) group = self._groups.pop(group_uuid, None) # Inform all group members that they are no longer members if group is not None: group['listener']._mz.reset_members() # noqa...
Register a listener for audio group changes of cast uuid. On update will call: listener.added_to_multizone(group_uuid) The cast has been added to group uuid listener.removed_from_multizone(group_uuid) The cast has been removed from group uuid ...
def register_listener(self, member_uuid, listener): """ Register a listener for audio group changes of cast uuid. On update will call: listener.added_to_multizone(group_uuid) The cast has been added to group uuid listener.removed_from_multizone(group_uuid) ...
Deregister listener for audio group changes of cast uuid.
def deregister_listener(self, member_uuid, listener): """ Deregister listener for audio group changes of cast uuid.""" self._casts[str(member_uuid)]['listeners'].remove(listener)
Called when a multizone message is received.
def receive_message(self, message, data): # noqa: E501 pylint: disable=too-many-return-statements """ Called when a multizone message is received. """ if data[MESSAGE_TYPE] == TYPE_DEVICE_ADDED: uuid = data['device']['deviceId'] name = data['device']['name'] self._ad...
Creates a Chromecast object from a zeroconf host.
def _get_chromecast_from_host(host, tries=None, retry_wait=None, timeout=None, blocking=True): """Creates a Chromecast object from a zeroconf host.""" # Build device status from the mDNS info, this information is # the primary source and the remaining will be fetched # late...
Creates a Chromecast object from a zeroconf service.
def _get_chromecast_from_service(services, tries=None, retry_wait=None, timeout=None, blocking=True): """Creates a Chromecast object from a zeroconf service.""" # Build device status from the mDNS service name info, this # information is the primary source and the remaining ...
Searches the network for chromecast devices. If blocking = True, returns a list of discovered chromecast devices. If blocking = False, triggers a callback for each discovered chromecast, and returns a function which can be executed to stop discovery. May r...
def get_chromecasts(tries=None, retry_wait=None, timeout=None, blocking=True, callback=None): """ Searches the network for chromecast devices. If blocking = True, returns a list of discovered chromecast devices. If blocking = False, triggers a callback for each discovered chromecast...
Returns whether the CEC data should be ignored.
def ignore_cec(self): """ Returns whether the CEC data should be ignored. """ return self.device is not None and \ any([fnmatch.fnmatchcase(self.device.friendly_name, pattern) for pattern in IGNORE_CEC])
Returns if there is currently an app running.
def is_idle(self): """ Returns if there is currently an app running. """ return (self.status is None or self.app_id in (None, IDLE_APP_ID) or (not self.status.is_active_input and not self.ignore_cec))
Called when a new status received from the Chromecast.
def new_cast_status(self, status): """ Called when a new status received from the Chromecast. """ self.status = status if status: self.status_event.set()
Start an app on the Chromecast.
def start_app(self, app_id, force_launch=False): """ Start an app on the Chromecast. """ self.logger.info("Starting app %s", app_id) self.socket_client.receiver_controller.launch_app(app_id, force_launch)
Decrement the volume by 0.1 (or delta) unless it is already 0. Returns the new volume.
def volume_down(self, delta=0.1): """ Decrement the volume by 0.1 (or delta) unless it is already 0. Returns the new volume. """ if delta <= 0: raise ValueError( "volume delta must be greater than zero, not {}".format(delta)) return self.set_volume(sel...
Increment volume by 0.1 (or delta) unless it is already maxed. Returns the new volume.
def volume_up(self, delta=0.1): """ Increment volume by 0.1 (or delta) unless it is already maxed. Returns the new volume. """ if delta <= 0: raise ValueError( "volume delta must be greater than zero, not {}".format(delta)) return self.set_volume(self...
Waits until the cast device is ready for communication. The device is ready as soon a status message has been received. If the worker thread is not already running, it will be started. If the status has already been received then the method returns immediately. :param timeout:...
def wait(self, timeout=None): """ Waits until the cast device is ready for communication. The device is ready as soon a status message has been received. If the worker thread is not already running, it will be started. If the status has already been received then the method ret...
Parses a PB2 message into JSON format.
def _json_from_message(message): """ Parses a PB2 message into JSON format. """ try: return json.loads(message.payload_utf8) except ValueError: logger = logging.getLogger(__name__) logger.warning("Ignoring invalid json in namespace %s: %s", message.namespace, m...
Disconnects the chromecast and waits for it to terminate. :param timeout: a floating point number specifying a timeout for the operation in seconds (or fractions thereof). Or None to block forever. :param blocking: If True it will block until the disconne...
def disconnect(self, timeout=None, blocking=True): """ Disconnects the chromecast and waits for it to terminate. :param timeout: a floating point number specifying a timeout for the operation in seconds (or fractions thereof). Or None to block for...
Gives a string representation of a PB2 message.
def _message_to_string(message, data=None): """ Gives a string representation of a PB2 message. """ if data is None: data = _json_from_message(message) return "Message {} from {} to {}: {}".format( message.namespace, message.source_id, message.destination_id, data)
Create a new socket with OS-specific parameters Try to set SO_REUSEPORT for BSD-flavored systems if it's an option. Catches errors if not.
def new_socket(): """ Create a new socket with OS-specific parameters Try to set SO_REUSEPORT for BSD-flavored systems if it's an option. Catches errors if not. """ new_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) new_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) ...
Initialize a socket to a Chromecast, retrying as necessary.
def initialize_connection(self): # noqa: E501 pylint:disable=too-many-statements, too-many-branches """Initialize a socket to a Chromecast, retrying as necessary.""" tries = self.tries if self.socket is not None: self.socket.close() self.socket = None # Make su...
Connect socket connection to Chromecast device. Must only be called if the worker thread will not be started.
def connect(self): """ Connect socket connection to Chromecast device. Must only be called if the worker thread will not be started. """ try: self.initialize_connection() except ChromecastConnectionError: self._report_connection_status( ...
Register a new namespace handler.
def register_handler(self, handler): """ Register a new namespace handler. """ self._handlers[handler.namespace] = handler handler.registered(self)
Called when a new cast status has been received.
def new_cast_status(self, cast_status): """ Called when a new cast status has been received. """ new_channel = self.destination_id != cast_status.transport_id if new_channel: self.disconnect_channel(self.destination_id) self.app_namespaces = cast_status.namespaces s...
Connect to the cast and start polling the socket.
def run(self): """ Connect to the cast and start polling the socket. """ try: self.initialize_connection() except ChromecastConnectionError: self._report_connection_status( ConnectionStatus(CONNECTION_STATUS_DISCONNECTED, N...
Use run_once() in your own main loop after you receive something on the socket (get_socket()).
def run_once(self): """ Use run_once() in your own main loop after you receive something on the socket (get_socket()). """ # pylint: disable=too-many-branches, too-many-return-statements try: if not self._check_connection(): return 0 e...
Checks if the connection is active, and if not reconnect :return: True if the connection is active, False if the connection was reset.
def _check_connection(self): """ Checks if the connection is active, and if not reconnect :return: True if the connection is active, False if the connection was reset. """ # check if connection is expired reset = False if self._force_recon: ...
Route message to any handlers on the message namespace
def _route_message(self, message, data): """ Route message to any handlers on the message namespace """ # route message to handlers if message.namespace in self._handlers: # debug messages if message.namespace != NS_HEARTBEAT: self.logger.debug( ...
Cleanup open channels and handlers
def _cleanup(self): """ Cleanup open channels and handlers """ for channel in self._open_channels: try: self.disconnect_channel(channel) except Exception: # pylint: disable=broad-except pass for handler in self._handlers.values(): ...
Report a change in the connection status to any listeners
def _report_connection_status(self, status): """ Report a change in the connection status to any listeners """ for listener in self._connection_listeners: try: self.logger.debug("[%s:%s] connection listener: %x (%s)", self.fn or self.host, se...
Read bytes from the socket.
def _read_bytes_from_socket(self, msglen): """ Read bytes from the socket. """ chunks = [] bytes_recd = 0 while bytes_recd < msglen: if self.stop.is_set(): raise InterruptLoop("Stopped while reading from socket") try: chunk = self.s...