code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
cls_attrs = {f.name: f for f in attr.fields(cls)}
unknown = {k: v for k, v in kwargs.items() if k not in cls_attrs}
if len(unknown) > 0:
_LOGGER.warning(
"Got unknowns for %s: %s - please create an issue!", cls.__name__, unknown
)
missing = [k for k in cls_attrs if k not in kwargs]
data = {k: v for k, v in kwargs.items() if k in cls_attrs}
# initialize missing values to avoid passing default=None
# for the attrs attribute definitions
for m in missing:
default = cls_attrs[m].default
if isinstance(default, attr.Factory):
if not default.takes_self:
data[m] = default.factory()
else:
raise NotImplementedError
else:
_LOGGER.debug("Missing key %s with no default for %s", m, cls.__name__)
data[m] = None
# initialize and store raw data for debug purposes
inst = cls(**data)
setattr(inst, "raw", kwargs)
return inst
|
def make(cls, **kwargs)
|
Create a container.
Reports extra keys as well as missing ones.
Thanks to habnabit for the idea!
| 3.717507 | 3.64033 | 1.0212 |
if params is None:
params = {}
headers = {"Content-Type": "application/json"}
payload = {
"method": method,
"params": [params],
"id": next(self.idgen),
"version": "1.0",
}
if self.debug > 1:
_LOGGER.debug("> POST %s with body: %s", self.guide_endpoint, payload)
async with aiohttp.ClientSession(headers=headers) as session:
res = await session.post(self.guide_endpoint, json=payload, headers=headers)
if self.debug > 1:
_LOGGER.debug("Received %s: %s" % (res.status_code, res.text))
if res.status != 200:
raise SongpalException(
"Got a non-ok (status %s) response for %s" % (res.status, method),
error=await res.json()["error"],
)
res = await res.json()
# TODO handle exceptions from POST? This used to raise SongpalException
# on requests.RequestException (Unable to get APIs).
if "error" in res:
raise SongpalException("Got an error for %s" % method, error=res["error"])
if self.debug > 1:
_LOGGER.debug("Got %s: %s", method, pf(res))
return res
|
async def create_post_request(self, method: str, params: Dict = None)
|
Call the given method over POST.
:param method: Name of the method
:param params: dict of parameters
:return: JSON object
| 3.567483 | 3.620965 | 0.98523 |
response = await self.request_supported_methods()
if "result" in response:
services = response["result"][0]
_LOGGER.debug("Got %s services!" % len(services))
for x in services:
serv = await Service.from_payload(
x, self.endpoint, self.idgen, self.debug, self.force_protocol
)
if serv is not None:
self.services[x["service"]] = serv
else:
_LOGGER.warning("Unable to create service %s", x["service"])
for service in self.services.values():
if self.debug > 1:
_LOGGER.debug("Service %s", service)
for api in service.methods:
# self.logger.debug("%s > %s" % (service, api))
if self.debug > 1:
_LOGGER.debug("> %s" % api)
return self.services
return None
|
async def get_supported_methods(self)
|
Get information about supported methods.
Calling this as the first thing before doing anything else is
necessary to fill the available services table.
| 3.630481 | 3.451545 | 1.051843 |
if value:
status = "active"
else:
status = "off"
# TODO WoL works when quickboot is not enabled
return await self.services["system"]["setPowerStatus"](status=status)
|
async def set_power(self, value: bool)
|
Toggle the device on and off.
| 17.104525 | 14.476555 | 1.181533 |
info = await self.services["avContent"]["getPlayingContentInfo"]({})
return PlayInfo.make(**info.pop())
|
async def get_play_info(self) -> PlayInfo
|
Return of the device.
| 29.779387 | 19.624887 | 1.51743 |
return [
Setting.make(**x)
for x in await self.services["system"]["getPowerSettings"]({})
]
|
async def get_power_settings(self) -> List[Setting]
|
Get power settings.
| 11.365149 | 9.182787 | 1.237658 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["system"]["setPowerSettings"](params)
|
async def set_power_settings(self, target: str, value: str) -> None
|
Set power settings.
| 7.365614 | 5.687055 | 1.295154 |
return [
Setting.make(**x)
for x in await self.services["system"]["getWuTangInfo"]({})
]
|
async def get_googlecast_settings(self) -> List[Setting]
|
Get Googlecast settings.
| 37.777733 | 34.120007 | 1.107202 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["system"]["setWuTangInfo"](params)
|
async def set_googlecast_settings(self, target: str, value: str)
|
Set Googlecast settings.
| 20.698013 | 15.418168 | 1.342443 |
settings = await self.request_settings_tree()
return [SettingsEntry.make(**x) for x in settings["settings"]]
|
async def get_settings(self) -> List[SettingsEntry]
|
Get a list of available settings.
See :func:request_settings_tree: for raw settings.
| 8.309102 | 5.187991 | 1.601603 |
misc = await self.services["system"]["getDeviceMiscSettings"](target="")
return [Setting.make(**x) for x in misc]
|
async def get_misc_settings(self) -> List[Setting]
|
Return miscellaneous settings such as name and timezone.
| 23.975203 | 21.433273 | 1.118597 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["system"]["setDeviceMiscSettings"](params)
|
async def set_misc_settings(self, target: str, value: str)
|
Change miscellaneous settings.
| 10.023089 | 7.894351 | 1.269653 |
return [
Setting.make(**x)
for x in await self.services["system"]["getSleepTimerSettings"]({})
]
|
async def get_sleep_timer_settings(self) -> List[Setting]
|
Get sleep timer settings.
| 13.5862 | 10.719815 | 1.267391 |
return [
Storage.make(**x)
for x in await self.services["system"]["getStorageList"]({})
]
|
async def get_storage_list(self) -> List[Storage]
|
Return information about connected storage devices.
| 12.822328 | 8.42851 | 1.521304 |
if from_network:
from_network = "true"
else:
from_network = "false"
# from_network = ""
info = await self.services["system"]["getSWUpdateInfo"](network=from_network)
return SoftwareUpdateInfo.make(**info)
|
async def get_update_info(self, from_network=True) -> SoftwareUpdateInfo
|
Get information about updates.
| 6.111925 | 5.847208 | 1.045272 |
res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]()
return [Input.make(services=self.services, **x) for x in res if 'meta:zone:output' not in x['meta']]
|
async def get_inputs(self) -> List[Input]
|
Return list of available outputs.
| 22.969172 | 19.245495 | 1.193483 |
res = await self.services["avContent"]["getCurrentExternalTerminalsStatus"]()
zones = [Zone.make(services=self.services, **x) for x in res if 'meta:zone:output' in x['meta']]
if not zones:
raise SongpalException("Device has no zones")
return zones
|
async def get_zones(self) -> List[Zone]
|
Return list of available zones.
| 13.428253 | 12.718037 | 1.055843 |
return await self.services[service][method](target=target)
|
async def get_setting(self, service: str, method: str, target: str)
|
Get a single setting for service.
:param service: Service to query.
:param method: Getter method for the setting, read from ApiMapping.
:param target: Setting to query.
:return: JSON response from the device.
| 12.987372 | 17.388695 | 0.746886 |
bt = await self.services["avContent"]["getBluetoothSettings"]({})
return [Setting.make(**x) for x in bt]
|
async def get_bluetooth_settings(self) -> List[Setting]
|
Get bluetooth settings.
| 14.380941 | 12.280938 | 1.170997 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["avContent"]["setBluetoothSettings"](params)
|
async def set_bluetooth_settings(self, target: str, value: str) -> None
|
Set bluetooth settings.
| 9.139332 | 7.138566 | 1.280276 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setCustomEqualizerSettings"](params)
|
async def set_custom_eq(self, target: str, value: str) -> None
|
Set custom EQ settings.
| 11.533964 | 8.040471 | 1.434489 |
return [
SupportedFunctions.make(**x)
for x in await self.services["avContent"]["getSupportedPlaybackFunction"](
uri=uri
)
]
|
async def get_supported_playback_functions(
self, uri=""
) -> List[SupportedFunctions]
|
Return list of inputs and their supported functions.
| 9.732341 | 8.512875 | 1.14325 |
return [
Setting.make(**x)
for x in await self.services["avContent"]["getPlaybackModeSettings"]({})
]
|
async def get_playback_settings(self) -> List[Setting]
|
Get playback settings such as shuffle and repeat.
| 19.415148 | 17.459652 | 1.112001 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["avContent"]["setPlaybackModeSettings"](params)
|
async def set_playback_settings(self, target, value) -> None
|
Set playback settings such a shuffle and repeat.
| 10.190302 | 8.556425 | 1.190953 |
return [
Scheme.make(**x)
for x in await self.services["avContent"]["getSchemeList"]()
]
|
async def get_schemes(self) -> List[Scheme]
|
Return supported uri schemes.
| 15.497036 | 13.457348 | 1.151567 |
res = await self.services["avContent"]["getSourceList"](scheme=scheme)
return [Source.make(**x) for x in res]
|
async def get_source_list(self, scheme: str = "") -> List[Source]
|
Return available sources for playback.
| 12.271544 | 8.861937 | 1.384747 |
params = {"uri": source, "type": None, "target": "all", "view": "flat"}
return ContentInfo.make(
**await self.services["avContent"]["getContentCount"](params)
)
|
async def get_content_count(self, source: str)
|
Return file listing for source.
| 17.773167 | 13.687966 | 1.298452 |
contents = [
Content.make(**x)
for x in await self.services["avContent"]["getContentList"](uri=uri)
]
contentlist = []
for content in contents:
if content.contentKind == "directory" and content.index >= 0:
# print("got directory %s" % content.uri)
res = await self.get_contents(content.uri)
contentlist.extend(res)
else:
contentlist.append(content)
# print("%s%s" % (' ' * depth, content))
return contentlist
|
async def get_contents(self, uri) -> List[Content]
|
Request content listing recursively for the given URI.
:param uri: URI for the source.
:return: List of Content objects.
| 4.516172 | 4.569272 | 0.988379 |
res = await self.services["audio"]["getVolumeInformation"]({})
volume_info = [Volume.make(services=self.services, **x) for x in res]
if len(volume_info) < 1:
logging.warning("Unable to get volume information")
elif len(volume_info) > 1:
logging.debug("The device seems to have more than one volume setting.")
return volume_info
|
async def get_volume_information(self) -> List[Volume]
|
Get the volume information.
| 4.633659 | 4.505046 | 1.028549 |
res = await self.services["audio"]["getSoundSettings"]({"target": target})
return [Setting.make(**x) for x in res]
|
async def get_sound_settings(self, target="") -> List[Setting]
|
Get the current sound settings.
:param str target: settings target, defaults to all.
| 7.360696 | 7.330989 | 1.004052 |
res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"})
return Setting.make(**res[0])
|
async def get_soundfield(self) -> List[Setting]
|
Get the current sound field settings.
| 16.266209 | 13.371063 | 1.216523 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setSoundSettings"](params)
|
async def set_sound_settings(self, target: str, value: str)
|
Change a sound setting.
| 7.899018 | 5.796053 | 1.362827 |
speaker_settings = await self.services["audio"]["getSpeakerSettings"]({})
return [Setting.make(**x) for x in speaker_settings]
|
async def get_speaker_settings(self) -> List[Setting]
|
Return speaker settings.
| 9.863965 | 8.492321 | 1.161516 |
params = {"settings": [{"target": target, "value": value}]}
return await self.services["audio"]["setSpeakerSettings"](params)
|
async def set_speaker_settings(self, target: str, value: str)
|
Set speaker settings.
| 7.672875 | 5.573627 | 1.37664 |
tasks = []
async def handle_notification(notification):
if type(notification) not in self.callbacks:
if not fallback_callback:
_LOGGER.debug("No callbacks for %s", notification)
# _LOGGER.debug("Existing callbacks for: %s" % self.callbacks)
else:
await fallback_callback(notification)
return
for cb in self.callbacks[type(notification)]:
await cb(notification)
for serv in self.services.values():
tasks.append(
asyncio.ensure_future(
serv.listen_all_notifications(handle_notification)
)
)
try:
print(await asyncio.gather(*tasks))
except Exception as ex:
# TODO: do a slightly restricted exception handling?
# Notify about disconnect
await handle_notification(ConnectChange(connected=False, exception=ex))
return
|
async def listen_notifications(self, fallback_callback=None)
|
Listen for notifications from the device forever.
Use :func:on_notification: to register what notifications to listen to.
| 4.464389 | 4.581167 | 0.974509 |
_LOGGER.debug("Stopping listening for notifications..")
for serv in self.services.values():
await serv.stop_listen_notifications()
return True
|
async def stop_listen_notifications(self)
|
Stop listening on notifications.
| 6.307399 | 5.263602 | 1.198305 |
notifications = []
for serv in self.services:
for notification in self.services[serv].notifications:
notifications.append(notification)
return notifications
|
async def get_notifications(self) -> List[Notification]
|
Get available notifications, which can then be subscribed to.
Call :func:activate: to enable notifications, and :func:listen_notifications:
to loop forever for notifications.
:return: List of Notification objects
| 3.837837 | 5.211737 | 0.736383 |
_LOGGER.info("Calling %s.%s(%s)", service, method, params)
return await self.services[service][method](params)
|
async def raw_command(self, service: str, method: str, params: Any)
|
Call an arbitrary method with given parameters.
This is useful for debugging and trying out commands before
implementing them properly.
:param service: Service, use list(self.services) to get a list of availables.
:param method: Method to call.
:param params: Parameters as a python object (e.g., dict, list)
:return: Raw JSON response from the device.
| 4.972762 | 4.20695 | 1.182035 |
requester = AiohttpRequester()
factory = UpnpFactory(requester)
device = await factory.async_create_device(self.url)
self.service = device.service('urn:schemas-sony-com:service:Group:1')
if not self.service:
_LOGGER.error("Unable to find group service!")
return False
for act in self.service.actions.values():
_LOGGER.debug("Action: %s (%s)", act, [arg.name for arg in act.in_arguments()])
return True
|
async def connect(self)
|
Available actions
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetDeviceInfo)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetState)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetStateM)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupName)> (['GroupName'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_ChangeGroupVolume)> (['GroupVolume'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetAllGroupMemory)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_DeleteGroupMemory)> (['MemoryID'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_UpdateGroupMemory)> (['MemoryID', 'GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Start)> (['GroupMode', 'GroupName', 'SlaveList', 'CodecType', 'CodecBitrate'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Entry)> (['MasterSessionID', 'SlaveList'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_EntryM)> (['MasterSessionID', 'SlaveList'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Leave)> (['MasterSessionID', 'SlaveList'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_LeaveM)> (['MasterSessionID', 'SlaveList'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Abort)> (['MasterSessionID'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetGroupMute)> (['GroupMute'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_SetCodec)> (['CodecType', 'CodecBitrate'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_GetCodec)> ([])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Invite)> (['GroupMode', 'GroupName', 'MasterUUID', 'MasterSessionID'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Exit)> (['SlaveSessionID'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Play)> (['MasterSessionID'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Stop)> (['MasterSessionID'])
INFO:songpal.upnpctl:Action: <UpnpService.Action(X_Delegate)> (['GroupMode', 'SlaveList', 'DelegateURI', 'DelegateURIMetaData'])
| 5.229106 | 4.614878 | 1.133097 |
act = self.service.action(action)
_LOGGER.info("Calling %s with %s", action, kwargs)
res = await act.async_call(**kwargs)
_LOGGER.info(" Result: %s" % res)
return res
|
async def call(self, action, **kwargs)
|
Make an action call with given kwargs.
| 4.577528 | 3.947476 | 1.159609 |
act = self.service.action("X_GetDeviceInfo")
res = await act.async_call()
return res
|
async def info(self)
|
Return device info.
| 23.000879 | 12.290206 | 1.87148 |
act = self.service.action("X_GetState")
res = await act.async_call()
return GroupState.make(**res)
|
async def state(self) -> GroupState
|
Return the current group state
| 16.241833 | 14.430502 | 1.125521 |
# Returns an XML with groupMemoryList
act = self.service.action("X_GetAllGroupMemory")
res = await act.async_call()
return res
|
async def get_group_memory(self)
|
Return group memory.
| 24.259741 | 17.756615 | 1.366237 |
act = self.service.action("X_UpdateGroupMemory")
res = await act.async_call(MemoryID=memory_id,
GroupMode=mode,
GroupName=name,
SlaveList=slaves,
CodecType=codectype,
CodecBitrate=bitrate)
return res
|
async def update_group_memory(self, memory_id, mode, name, slaves, codectype=0x0040, bitrate=0x0003)
|
Update existing memory? Can be used to create new ones, too?
| 4.174232 | 3.918923 | 1.065148 |
act = self.service.action("X_DeleteGroupMemory")
res = await act.async_call(MemoryID=memory_id)
|
async def delete_group_memory(self, memory_id)
|
Delete group memory.
| 10.611815 | 8.687245 | 1.22154 |
act = self.service.action("X_GetCodec")
res = await act.async_call()
return res
|
async def get_codec(self)
|
Get codec settings.
| 14.94151 | 10.215034 | 1.462698 |
act = self.service.action("X_SetCodec")
res = await act.async_call(CodecType=codectype, CodecBitrate=bitrate)
return res
|
async def set_codec(self, codectype=0x0040, bitrate=0x0003)
|
Set codec settings.
| 6.586452 | 6.2029 | 1.061834 |
state = await self.state()
res = await self.call("X_Abort", MasterSessionID=state.MasterSessionID)
return res
|
async def abort(self)
|
Abort current group session.
| 14.468177 | 10.456488 | 1.383656 |
state = await self.state()
res = await self.call("X_Stop", MasterSessionID=state.MasterSessionID)
return res
|
async def stop(self)
|
Stop playback?
| 16.383944 | 11.984909 | 1.367048 |
state = await self.state()
res = await self.call("X_Play", MasterSessionID=state.MasterSessionID)
return res
|
async def play(self)
|
Start playback?
| 15.233172 | 11.339387 | 1.343386 |
# NOTE: codectype and codecbitrate were simply chosen from an example..
res = await self.call("X_Start", GroupMode="GROUP",
GroupName=name,
SlaveList=",".join(slaves),
CodecType=0x0040,
CodecBitrate=0x0003)
return res
|
async def create(self, name, slaves)
|
Create a group.
| 15.954228 | 13.638363 | 1.169805 |
async with aiohttp.ClientSession() as session:
req = {
"method": "getMethodTypes",
"params": [''],
"version": "1.0",
"id": next(idgen),
}
if protocol == ProtocolType.WebSocket:
async with session.ws_connect(endpoint, timeout=2) as s:
await s.send_json(req)
res = await s.receive_json()
return res
else:
res = await session.post(endpoint, json=req)
json = await res.json()
return json
|
async def fetch_signatures(endpoint, protocol, idgen)
|
Request available methods for the service.
| 3.190451 | 2.977434 | 1.071544 |
service_name = payload["service"]
if "protocols" not in payload:
raise SongpalException(
"Unable to find protocols from payload: %s" % payload
)
protocols = payload["protocols"]
_LOGGER.debug("Available protocols for %s: %s", service_name, protocols)
if force_protocol and force_protocol.value in protocols:
protocol = force_protocol
elif "websocket:jsonizer" in protocols:
protocol = ProtocolType.WebSocket
elif "xhrpost:jsonizer" in protocols:
protocol = ProtocolType.XHRPost
else:
raise SongpalException(
"No known protocols for %s, got: %s" % (service_name, protocols)
)
_LOGGER.debug("Using protocol: %s" % protocol)
service_endpoint = "%s/%s" % (endpoint, service_name)
# creation here we want to pass the created service class to methods.
service = cls(service_name, service_endpoint, protocol, idgen, debug)
sigs = await cls.fetch_signatures(
service_endpoint, protocol, idgen
)
if debug > 1:
_LOGGER.debug("Signatures: %s", sigs)
if "error" in sigs:
_LOGGER.error("Got error when fetching sigs: %s", sigs["error"])
return None
methods = {}
for sig in sigs["results"]:
name = sig[0]
parsed_sig = MethodSignature.from_payload(*sig)
if name in methods:
_LOGGER.debug("Got duplicate signature for %s, existing was %s. Keeping the existing one",
parsed_sig, methods[name])
else:
methods[name] = Method(service, parsed_sig, debug)
service.methods = methods
if "notifications" in payload and "switchNotifications" in methods:
notifications = [
Notification(
service_endpoint, methods["switchNotifications"], notification
)
for notification in payload["notifications"]
]
service.notifications = notifications
_LOGGER.debug("Got notifications: %s" % notifications)
return service
|
async def from_payload(cls, payload, endpoint, idgen, debug, force_protocol=None)
|
Create Service object from a payload.
| 3.626131 | 3.530619 | 1.027052 |
_LOGGER.debug(
"%s got called with args (%s) kwargs (%s)" % (method.name, args, kwargs)
)
# Used for allowing keeping reading from the socket
_consumer = None
if "_consumer" in kwargs:
if self.active_protocol != ProtocolType.WebSocket:
raise SongpalException(
"Notifications are only supported over websockets"
)
_consumer = kwargs["_consumer"]
del kwargs["_consumer"]
if len(kwargs) == 0 and len(args) == 0:
params = [] # params need to be empty array, if none is given
elif len(kwargs) > 0:
params = [kwargs]
elif len(args) == 1 and args[0] is not None:
params = [args[0]]
else:
params = []
# TODO check for type correctness
# TODO note parameters are not always necessary, see getPlaybackModeSettings
# which has 'target' and 'uri' but works just fine without anything (wildcard)
# if len(params) != len(self._inputs):
# _LOGGER.error("args: %s signature: %s" % (args,
# self.signature.input))
# raise Exception("Invalid number of inputs, wanted %s got %s / %s" % (
# len(self.signature.input), len(args), len(kwargs)))
async with aiohttp.ClientSession() as session:
req = {
"method": method.name,
"params": params,
"version": method.version,
"id": next(self.idgen),
}
if self.debug > 1:
_LOGGER.debug("sending request: %s (proto: %s)", req, self.active_protocol)
if self.active_protocol == ProtocolType.WebSocket:
async with session.ws_connect(
self.endpoint, timeout=self.timeout, heartbeat=self.timeout * 5
) as s:
await s.send_json(req)
# If we have a consumer, we are going to loop forever while
# emiting the incoming payloads to e.g. notification handler.
if _consumer is not None:
self.listening = True
while self.listening:
res_raw = await s.receive_json()
res = self.wrap_notification(res_raw)
_LOGGER.debug("Got notification: %s", res)
if self.debug > 1:
_LOGGER.debug("Got notification raw: %s", res_raw)
await _consumer(res)
res = await s.receive_json()
return res
else:
res = await session.post(self.endpoint, json=req)
return await res.json()
|
async def call_method(self, method, *args, **kwargs)
|
Call a method (internal).
This is an internal implementation, which formats the parameters if necessary
and chooses the preferred transport protocol.
The return values are JSON objects.
Use :func:__call__: provides external API leveraging this.
| 4.095994 | 4.026069 | 1.017368 |
if "method" in data:
method = data["method"]
params = data["params"]
change = params[0]
if method == "notifyPowerStatus":
return PowerChange.make(**change)
elif method == "notifyVolumeInformation":
return VolumeChange.make(**change)
elif method == "notifyPlayingContentInfo":
return ContentChange.make(**change)
elif method == "notifySettingsUpdate":
return SettingChange.make(**change)
elif method == "notifySWUpdateInfo":
return SoftwareUpdateChange.make(**change)
else:
_LOGGER.warning("Got unknown notification type: %s", method)
elif "result" in data:
result = data["result"][0]
if "enabled" in result and "enabled" in result:
return NotificationChange(**result)
else:
_LOGGER.warning("Unknown notification, returning raw: %s", data)
return data
|
def wrap_notification(self, data)
|
Convert notification JSON to a notification class.
| 3.488734 | 3.416138 | 1.021251 |
everything = [noti.asdict() for noti in self.notifications]
if len(everything) > 0:
await self._methods["switchNotifications"](
{"enabled": everything}, _consumer=callback
)
else:
_LOGGER.debug("No notifications available for %s", self.name)
|
async def listen_all_notifications(self, callback)
|
Enable all exposed notifications.
:param callback: Callback to call when a notification is received.
| 7.698858 | 8.662801 | 0.888726 |
return {
"methods": {m.name: m.asdict() for m in self.methods},
"protocols": self.protocols,
"notifications": {n.name: n.asdict() for n in self.notifications},
}
|
def asdict(self)
|
Return dict presentation of this service.
Useful for dumping the device information into JSON.
| 3.004256 | 2.706607 | 1.109971 |
if infn is not None:
infn = Path(infn).expanduser()
if infn.suffix == '.h5':
TR = xarray.open_dataset(infn)
return TR
c1.update({'model': 0, # 0: user meterological data
'itype': 1, # 1: horizontal path
'iemsct': 1, # 1: radiance model
'im': 1, # 1: for horizontal path (see Lowtran manual p.42)
'ird1': 1, # 1: use card 2C2)
})
# %% read csv file
if not infn: # demo mode
c1['p'] = [949., 959.]
c1['t'] = [283.8, 285.]
c1['wmol'] = [[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
[93.96, 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]]
c1['time'] = [parse('2017-04-05T12'),
parse('2017-04-05T18')]
else: # read csv, normal case
PTdata = read_csv(infn)
c1['p'] = PTdata['p']
c1['t'] = PTdata['Ta']
c1['wmol'] = np.zeros((PTdata.shape[0], 12))
c1['wmol'][:, 0] = PTdata['RH']
c1['time'] = [parse(t) for t in PTdata['time']]
# %% TR is 3-D array with axes: time, wavelength, and [transmission,radiance]
TR = loopuserdef(c1)
return TR
|
def horizrad(infn: Path, outfn: Path, c1: dict) -> xarray.Dataset
|
read CSV, simulate, write, plot
| 4.82923 | 4.666354 | 1.034904 |
short = 1e7 / short_nm
long = 1e7 / long_nm
N = int(np.ceil((short-long) / step_cminv)) + 1 # yes, ceil
return short, long, N
|
def nm2lt7(short_nm: float, long_nm: float, step_cminv: float = 20) -> Tuple[float, float, float]
|
converts wavelength in nm to cm^-1
minimum meaningful step is 20, but 5 is minimum before crashing lowtran
short: shortest wavelength e.g. 200 nm
long: longest wavelength e.g. 30000 nm
step: step size in cm^-1 e.g. 20
output in cm^-1
| 5.016104 | 5.24446 | 0.956458 |
wmol = np.atleast_2d(c1['wmol'])
P = np.atleast_1d(c1['p'])
T = np.atleast_1d(c1['t'])
time = np.atleast_1d(c1['time'])
assert wmol.shape[0] == len(P) == len(T) == len(time), 'WMOL, P, T,time must be vectors of equal length'
N = len(P)
# %% 3-D array indexed by metadata
TR = xarray.Dataset(coords={'time': time, 'wavelength_nm': None, 'angle_deg': None})
for i in range(N):
c = c1.copy()
c['wmol'] = wmol[i, :]
c['p'] = P[i]
c['t'] = T[i]
c['time'] = time[i]
TR = TR.merge(golowtran(c))
# TR = TR.sort_index(axis=0) # put times in order, sometimes CSV is not monotonic in time.
return TR
|
def loopuserdef(c1: Dict[str, Any]) -> xarray.DataArray
|
golowtran() is for scalar parameters only
(besides vector of wavelength, which Lowtran internally loops over)
wmol, p, t must all be vector(s) of same length
| 4.317495 | 3.655698 | 1.181032 |
angles = np.atleast_1d(c1['angle'])
TR = xarray.Dataset(coords={'wavelength_nm': None, 'angle_deg': angles})
for a in angles:
c = c1.copy()
c['angle'] = a
TR = TR.merge(golowtran(c))
return TR
|
def loopangle(c1: Dict[str, Any]) -> xarray.Dataset
|
loop over "ANGLE"
| 6.053443 | 5.545906 | 1.091516 |
# %% default parameters
c1.setdefault('time', None)
defp = ('h1', 'h2', 'angle', 'im', 'iseasn', 'ird1', 'range_km', 'zmdl', 'p', 't')
for p in defp:
c1.setdefault(p, 0)
c1.setdefault('wmol', [0]*12)
# %% input check
assert len(c1['wmol']) == 12, 'see Lowtran user manual for 12 values of WMOL'
assert np.isfinite(c1['h1']), 'per Lowtran user manual Table 14, H1 must always be defined'
# %% setup wavelength
c1.setdefault('wlstep', 20)
if c1['wlstep'] < 5:
logging.critical('minimum resolution 5 cm^-1, specified resolution 20 cm^-1')
wlshort, wllong, nwl = nm2lt7(c1['wlshort'], c1['wllong'], c1['wlstep'])
if not 0 < wlshort and wllong <= 50000:
logging.critical('specified model range 0 <= wavelength [cm^-1] <= 50000')
# %% invoke lowtran
Tx, V, Alam, trace, unif, suma, irrad, sumvv = lowtran7.lwtrn7(
True, nwl, wllong, wlshort, c1['wlstep'],
c1['model'], c1['itype'], c1['iemsct'], c1['im'],
c1['iseasn'], c1['ird1'],
c1['zmdl'], c1['p'], c1['t'], c1['wmol'],
c1['h1'], c1['h2'], c1['angle'], c1['range_km'])
dims = ('time', 'wavelength_nm', 'angle_deg')
TR = xarray.Dataset({'transmission': (dims, Tx[:, 9][None, :, None]),
'radiance': (dims, sumvv[None, :, None]),
'irradiance': (dims, irrad[:, 0][None, :, None]),
'pathscatter': (dims, irrad[:, 2][None, :, None])},
coords={'time': [c1['time']],
'wavelength_nm': Alam*1e3,
'angle_deg': [c1['angle']]})
return TR
|
def golowtran(c1: Dict[str, Any]) -> xarray.Dataset
|
directly run Fortran code
| 6.166883 | 6.099809 | 1.010996 |
for t in TR.time: # for each time
plotirrad(TR.sel(time=t), c1, log)
|
def plotradtime(TR: xarray.Dataset, c1: Dict[str, Any], log: bool = False)
|
make one plot per time for now.
TR: 3-D array: time, wavelength, [transmittance, radiance]
radiance is currently single-scatter solar
| 7.052588 | 7.358434 | 0.958436 |
return {
"service": self.service.name,
**self.signature.serialize(),
}
|
def asdict(self) -> Dict[str, Union[Dict, Union[str, Dict]]]
|
Return a dictionary describing the method.
This can be used to dump the information into a JSON file.
| 11.757274 | 11.650298 | 1.009182 |
try:
errcode = DeviceErrorCode(self.error_code)
return "%s (%s): %s" % (errcode.name, errcode.value, self.error_message)
except:
return "Error %s: %s" % (self.error_code, self.error_message)
|
def error(self)
|
Return user-friendly error message.
| 2.917737 | 2.718203 | 1.073406 |
click.echo(click.style(msg, fg="red", bold=True))
|
def err(msg)
|
Pretty-print an error.
| 4.017249 | 4.258719 | 0.9433 |
f = asyncio.coroutine(f)
def wrapper(*args, **kwargs):
loop = asyncio.get_event_loop()
try:
return loop.run_until_complete(f(*args, **kwargs))
except KeyboardInterrupt:
click.echo("Got CTRL+C, quitting..")
dev = args[0]
loop.run_until_complete(dev.stop_listen_notifications())
except SongpalException as ex:
err("Error: %s" % ex)
if len(args) > 0 and hasattr(args[0], "debug"):
if args[0].debug > 0:
raise ex
return update_wrapper(wrapper, f)
|
def coro(f)
|
Run a coroutine and handle possible errors for the click cli.
Source https://github.com/pallets/click/issues/85#issuecomment-43378930
| 3.445319 | 3.4016 | 1.012852 |
for setting in settings:
if setting.is_directory:
print("%s%s (%s)" % (depth * " ", setting.title, module))
return await traverse_settings(dev, module, setting.settings, depth + 2)
else:
try:
print_settings([await setting.get_value(dev)], depth=depth)
except SongpalException as ex:
err("Unable to read setting %s: %s" % (setting, ex))
continue
|
async def traverse_settings(dev, module, settings, depth=0)
|
Print all available settings.
| 4.598381 | 4.312665 | 1.06625 |
# handle the case where a single setting is passed
if isinstance(settings, Setting):
settings = [settings]
for setting in settings:
cur = setting.currentValue
print(
"%s* %s (%s, value: %s, type: %s)"
% (
" " * depth,
setting.title,
setting.target,
click.style(cur, bold=True),
setting.type,
)
)
for opt in setting.candidate:
if not opt.isAvailable:
logging.debug("Unavailable setting %s", opt)
continue
click.echo(
click.style(
"%s - %s (%s)" % (" " * depth, opt.title, opt.value),
bold=opt.value == cur,
)
)
|
def print_settings(settings, depth=0)
|
Print all available settings of the device.
| 3.849707 | 3.763638 | 1.022869 |
lvl = logging.INFO
if debug:
lvl = logging.DEBUG
click.echo("Setting debug level to %s" % debug)
logging.basicConfig(level=lvl)
if ctx.invoked_subcommand == "discover":
ctx.obj = {"debug": debug}
return
if endpoint is None:
err("Endpoint is required except when with 'discover'!")
return
protocol = None
if post and websocket:
err("You can force either --post or --websocket")
return
elif websocket:
protocol = ProtocolType.WebSocket
elif post:
protocol = ProtocolType.XHRPost
logging.debug("Using endpoint %s", endpoint)
x = Device(endpoint, force_protocol=protocol, debug=debug)
try:
await x.get_supported_methods()
except (requests.exceptions.ConnectionError, SongpalException) as ex:
err("Unable to get supported methods: %s" % ex)
sys.exit(-1)
ctx.obj = x
|
async def cli(ctx, endpoint, debug, websocket, post)
|
Songpal CLI.
| 4.411127 | 4.25464 | 1.03678 |
power = await dev.get_power()
click.echo(click.style("%s" % power, bold=power))
vol = await dev.get_volume_information()
click.echo(vol.pop())
play_info = await dev.get_play_info()
if not play_info.is_idle:
click.echo("Playing %s" % play_info)
else:
click.echo("Not playing any media")
outs = await dev.get_inputs()
for out in outs:
if out.active:
click.echo("Active output: %s" % out)
sysinfo = await dev.get_system_info()
click.echo("System information: %s" % sysinfo)
|
async def status(dev: Device)
|
Display status information.
| 3.400129 | 3.183527 | 1.068038 |
TIMEOUT = 5
async def print_discovered(dev):
pretty_name = "%s - %s" % (dev.name, dev.model_number)
click.echo(click.style("\nFound %s" % pretty_name, bold=True))
click.echo("* API version: %s" % dev.version)
click.echo("* Endpoint: %s" % dev.endpoint)
click.echo(" Services:")
for serv in dev.services:
click.echo(" - Service: %s" % serv)
click.echo("\n[UPnP]")
click.echo("* URL: %s" % dev.upnp_location)
click.echo("* UDN: %s" % dev.udn)
click.echo(" Services:")
for serv in dev.upnp_services:
click.echo(" - Service: %s" % serv)
click.echo("Discovering for %s seconds" % TIMEOUT)
await Discover.discover(TIMEOUT, ctx.obj["debug"] or 0, callback=print_discovered)
|
async def discover(ctx)
|
Discover supported devices.
| 3.167711 | 3.056093 | 1.036523 |
async def try_turn(cmd):
state = True if cmd == "on" else False
try:
return await dev.set_power(state)
except SongpalException as ex:
if ex.code == 3:
err("The device is already %s." % cmd)
else:
raise ex
if cmd == "on" or cmd == "off":
click.echo(await try_turn(cmd))
elif cmd == "settings":
settings = await dev.get_power_settings()
print_settings(settings)
elif cmd == "set" and target and value:
click.echo(await dev.set_power_settings(target, value))
else:
power = await dev.get_power()
click.echo(click.style(str(power), bold=power))
|
async def power(dev: Device, cmd, target, value)
|
Turn on and off, control power settings.
Accepts commands 'on', 'off', and 'settings'.
| 3.380265 | 3.14993 | 1.073124 |
inputs = await dev.get_inputs()
if input:
click.echo("Activating %s" % input)
try:
input = next((x for x in inputs if x.title == input))
except StopIteration:
click.echo("Unable to find input %s" % input)
return
zone = None
if output:
zone = await dev.get_zone(output)
if zone.uri not in input.outputs:
click.echo("Input %s not valid for zone %s" % (input.title, output))
return
await input.activate(zone)
else:
click.echo("Inputs:")
for input in inputs:
act = False
if input.active:
act = True
click.echo(" * " + click.style(str(input), bold=act))
for out in input.outputs:
click.echo(" - %s" % out)
|
async def input(dev: Device, input, output)
|
Get and change outputs.
| 3.01505 | 2.942303 | 1.024724 |
if zone:
zone = await dev.get_zone(zone)
click.echo("%s %s" % ("Activating" if activate else "Deactivating", zone))
await zone.activate(activate)
else:
click.echo("Zones:")
for zone in await dev.get_zones():
act = False
if zone.active:
act = True
click.echo(" * " + click.style(str(zone), bold=act))
|
async def zone(dev: Device, zone, activate)
|
Get and change outputs.
| 3.311001 | 3.297462 | 1.004106 |
if target and value:
click.echo("Setting %s = %s" % (target, value))
await dev.set_googlecast_settings(target, value)
print_settings(await dev.get_googlecast_settings())
|
async def googlecast(dev: Device, target, value)
|
Return Googlecast settings.
| 4.119795 | 3.541843 | 1.163178 |
if scheme is None:
schemes = await dev.get_schemes()
schemes = [scheme.scheme for scheme in schemes] # noqa: T484
else:
schemes = [scheme]
for schema in schemes:
try:
sources = await dev.get_source_list(schema)
except SongpalException as ex:
click.echo("Unable to get sources for %s" % schema)
continue
for src in sources:
click.echo(src)
if src.isBrowsable:
try:
count = await dev.get_content_count(src.source)
if count.count > 0:
click.echo(" %s" % count)
for content in await dev.get_contents(src.source):
click.echo(" %s\n\t%s" % (content.title, content.uri))
else:
click.echo(" No content to list.")
except SongpalException as ex:
click.echo(" %s" % ex)
|
async def source(dev: Device, scheme)
|
List available sources.
If no `scheme` is given, will list sources for all sc hemes.
| 2.98512 | 2.884525 | 1.034874 |
vol = None
vol_controls = await dev.get_volume_information()
if output is not None:
click.echo("Using output: %s" % output)
output_uri = (await dev.get_zone(output)).uri
for v in vol_controls:
if v.output == output_uri:
vol = v
break
else:
vol = vol_controls[0]
if vol is None:
err("Unable to find volume controller: %s" % output)
return
if volume and volume == "mute":
click.echo("Muting")
await vol.set_mute(True)
elif volume and volume == "unmute":
click.echo("Unmuting")
await vol.set_mute(False)
elif volume:
click.echo("Setting volume to %s" % volume)
await vol.set_volume(volume)
if output is not None:
click.echo(vol)
else:
[click.echo(x) for x in vol_controls]
|
async def volume(dev: Device, volume, output)
|
Get and set the volume settings.
Passing 'mute' as new volume will mute the volume,
'unmute' removes it.
| 2.656288 | 2.653617 | 1.001006 |
schemes = await dev.get_schemes()
for scheme in schemes:
click.echo(scheme)
|
async def schemes(dev: Device)
|
Print supported uri schemes.
| 5.151859 | 4.047268 | 1.272923 |
if internet:
print("Checking updates from network")
else:
print("Not checking updates from internet")
update_info = await dev.get_update_info(from_network=internet)
if not update_info.isUpdatable:
click.echo("No updates available.")
return
if not update:
click.echo("Update available: %s" % update_info)
click.echo("Use --update to activate update!")
else:
click.echo("Activating update, please be seated.")
res = await dev.activate_system_update()
click.echo("Update result: %s" % res)
|
async def check_update(dev: Device, internet: bool, update: bool)
|
Print out update information.
| 4.46423 | 4.091959 | 1.090976 |
if target and value:
await dev.set_bluetooth_settings(target, value)
print_settings(await dev.get_bluetooth_settings())
|
async def bluetooth(dev: Device, target, value)
|
Get or set bluetooth settings.
| 6.701153 | 5.754786 | 1.164449 |
click.echo(await dev.get_system_info())
click.echo(await dev.get_interface_information())
|
async def sysinfo(dev: Device)
|
Print out system information (version, MAC addrs).
| 6.25007 | 4.576351 | 1.365732 |
settings_tree = await dev.get_settings()
for module in settings_tree:
await traverse_settings(dev, module.usage, module.settings)
|
async def settings(dev: Device)
|
Print out all possible settings.
| 10.324426 | 8.108216 | 1.273329 |
storages = await dev.get_storage_list()
for storage in storages:
click.echo(storage)
|
async def storage(dev: Device)
|
Print storage information.
| 5.80425 | 4.235472 | 1.370391 |
if target and value:
click.echo("Setting %s to %s" % (target, value))
click.echo(await dev.set_sound_settings(target, value))
print_settings(await dev.get_sound_settings())
|
async def sound(dev: Device, target, value)
|
Get or set sound settings.
| 4.211438 | 3.921815 | 1.073849 |
if soundfield is not None:
await dev.set_sound_settings("soundField", soundfield)
soundfields = await dev.get_sound_settings("soundField")
print_settings(soundfields)
|
async def soundfield(dev: Device, soundfield: str)
|
Get or set sound field.
| 3.945779 | 3.373053 | 1.169795 |
if target and value:
dev.set_playback_settings(target, value)
if cmd == "support":
click.echo("Supported playback functions:")
supported = await dev.get_supported_playback_functions("storage:usb1")
for i in supported:
print(i)
elif cmd == "settings":
print_settings(await dev.get_playback_settings())
# click.echo("Playback functions:")
# funcs = await dev.get_available_playback_functions()
# print(funcs)
else:
click.echo("Currently playing: %s" % await dev.get_play_info())
|
async def playback(dev: Device, cmd, target, value)
|
Get and set playback settings, e.g. repeat and shuffle..
| 4.418232 | 4.237834 | 1.042568 |
if target and value:
click.echo("Setting %s to %s" % (target, value))
await dev.set_speaker_settings(target, value)
print_settings(await dev.get_speaker_settings())
|
async def speaker(dev: Device, target, value)
|
Get and set external speaker settings.
| 4.074145 | 3.818927 | 1.06683 |
notifications = await dev.get_notifications()
async def handle_notification(x):
click.echo("got notification: %s" % x)
if listen_all:
if notification is not None:
await dev.services[notification].listen_all_notifications(
handle_notification
)
else:
click.echo("Listening to all possible notifications")
await dev.listen_notifications(fallback_callback=handle_notification)
elif notification:
click.echo("Subscribing to notification %s" % notification)
for notif in notifications:
if notif.name == notification:
await notif.activate(handle_notification)
click.echo("Unable to find notification %s" % notification)
else:
click.echo(click.style("Available notifications", bold=True))
for notification in notifications:
click.echo("* %s" % notification)
|
async def notifications(dev: Device, notification: str, listen_all: bool)
|
List available notifications and listen to them.
Using --listen-all [notification] allows to listen to all notifications
from the given subsystem.
If the subsystem is omited, notifications from all subsystems are
requested.
| 3.429034 | 3.661096 | 0.936614 |
for name, service in dev.services.items():
click.echo(click.style("\nService %s" % name, bold=True))
for method in service.methods:
click.echo(" %s" % method.name)
|
def list_all(dev: Device)
|
List all available API calls.
| 3.657275 | 3.211462 | 1.138819 |
params = None
if parameters is not None:
params = ast.literal_eval(parameters)
click.echo("Calling %s.%s with params %s" % (service, method, params))
res = await dev.raw_command(service, method, params)
click.echo(res)
|
async def command(dev, service, method, parameters)
|
Run a raw command.
| 2.871955 | 2.727268 | 1.053052 |
import attr
methods = await dev.get_supported_methods()
res = {
"supported_methods": {k: v.asdict() for k, v in methods.items()},
"settings": [attr.asdict(x) for x in await dev.get_settings()],
"sysinfo": attr.asdict(await dev.get_system_info()),
"interface_info": attr.asdict(await dev.get_interface_information()),
}
if file:
click.echo("Saving to file: %s" % file.name)
json.dump(res, file, sort_keys=True, indent=4)
else:
click.echo(json.dumps(res, sort_keys=True, indent=4))
|
async def dump_devinfo(dev: Device, file)
|
Dump developer information.
Pass `file` to write the results directly into a file.
| 2.713936 | 2.658498 | 1.020853 |
state = await gc.state()
click.echo(state)
click.echo("Full state info: %s" % repr(state))
|
async def state(gc: GroupControl)
|
Current group state.
| 7.645175 | 6.408669 | 1.192943 |
click.echo("Creating group %s with slaves: %s" % (name, slaves))
click.echo(await gc.create(name, slaves))
|
async def create(gc: GroupControl, name, slaves)
|
Create new group
| 3.855831 | 3.5822 | 1.076386 |
click.echo("Adding to existing group: %s" % slaves)
click.echo(await gc.add(slaves))
|
async def add(gc: GroupControl, slaves)
|
Add speakers to group.
| 6.484451 | 5.677693 | 1.142092 |
click.echo("Removing from existing group: %s" % slaves)
click.echo(await gc.remove(slaves))
|
async def remove(gc: GroupControl, slaves)
|
Remove speakers from group.
| 7.467178 | 6.136631 | 1.216821 |
click.echo("Setting volume to %s" % volume)
click.echo(await gc.set_group_volume(volume))
|
async def volume(gc: GroupControl, volume)
|
Adjust volume [-100, 100]
| 4.913045 | 4.163093 | 1.180143 |
click.echo("Muting group: %s" % mute)
click.echo(await gc.set_mute(mute))
|
async def mute(gc: GroupControl, mute)
|
(Un)mute group.
| 6.384895 | 5.504424 | 1.159957 |
ST = "urn:schemas-sony-com:service:ScalarWebAPI:1"
_LOGGER.info("Discovering for %s seconds" % timeout)
from async_upnp_client import UpnpFactory
from async_upnp_client.aiohttp import AiohttpRequester
async def parse_device(device):
requester = AiohttpRequester()
factory = UpnpFactory(requester)
url = device["location"]
device = await factory.async_create_device(url)
if debug > 0:
print(etree.ElementTree.tostring(device.xml).decode())
NS = {
'av': 'urn:schemas-sony-com:av',
}
info = device.xml.find(".//av:X_ScalarWebAPI_DeviceInfo", NS)
if not info:
_LOGGER.error("Unable to find X_ScalaerWebAPI_DeviceInfo")
return
endpoint = info.find(".//av:X_ScalarWebAPI_BaseURL", NS).text
version = info.find(".//av:X_ScalarWebAPI_Version", NS).text
services = [x.text for x in info.findall(".//av:X_ScalarWebAPI_ServiceType", NS)]
dev = DiscoveredDevice(name=device.name,
model_number=device.model_number,
udn=device.udn,
endpoint=endpoint,
version=version,
services=services,
upnp_services=list(device.services.keys()),
upnp_location=url)
_LOGGER.debug("Discovered: %s" % dev)
if callback is not None:
await callback(dev)
await async_search(timeout=timeout,
service_type=ST,
async_callback=parse_device)
|
async def discover(timeout, debug=0, callback=None)
|
Discover supported devices.
| 3.136099 | 3.069013 | 1.021859 |
payload = {
'id': 1,
'jsonrpc': '2.0',
'method': method,
'params': kwargs
}
credentials = base64.b64encode('{}:{}'.format(self._username, self._password).encode())
auth_header_prefix = 'Basic ' if self._auth_header == DEFAULT_AUTH_HEADER else ''
headers = {
self._auth_header: auth_header_prefix + credentials.decode(),
'Content-Type': 'application/json',
}
return self._do_request(headers, payload)
|
def execute(self, method, **kwargs)
|
Call remote API procedure
Args:
method: Procedure name
kwargs: Procedure named arguments
Returns:
Procedure result
Raises:
urllib2.HTTPError: Any HTTP error (Python 2)
urllib.error.HTTPError: Any HTTP error (Python 3)
| 2.568578 | 2.804067 | 0.916019 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.