code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
|---|---|---|---|---|---|
sha1 = hashlib.sha1()
with open(path, "rb") as f:
while True:
block = f.read(2 ** 10)
if not block:
break
sha1.update(block)
return sha1.hexdigest()
|
def file_sha1(path)
|
Compute SHA1 hash of a file.
| 1.866966
| 1.794528
| 1.040366
|
command = ["-an", "-frames:v", "1", "-c:v", output_format]
# open input for capture 1 frame
is_open = await self.open(
cmd=command,
input_source=input_source,
output="-f image2pipe -",
extra_cmd=extra_cmd,
)
# error after open?
if not is_open:
_LOGGER.warning("Error starting FFmpeg.")
return None
# read image
try:
proc_func = functools.partial(self._proc.communicate, timeout=timeout)
image, _ = await self._loop.run_in_executor(None, proc_func)
return image
except (subprocess.TimeoutExpired, ValueError):
_LOGGER.warning("Timeout reading image.")
self.kill()
return None
|
async def get_image(
self,
input_source: str,
output_format: str = IMAGE_JPEG,
extra_cmd: Optional[str] = None,
timeout: int = 15,
) -> Optional[bytes]
|
Open FFmpeg process as capture 1 frame.
| 4.364331
| 3.68453
| 1.184501
|
command = ["-version"]
# open input for capture 1 frame
is_open = await self.open(cmd=command, input_source=None, output="")
# error after open?
if not is_open:
_LOGGER.warning("Error starting FFmpeg.")
return
# read output
try:
proc_func = functools.partial(self._proc.communicate, timeout=timeout)
output, _ = await self._loop.run_in_executor(None, proc_func)
result = re.search(r"ffmpeg version (\S*)", output.decode())
if result is not None:
return result.group(1)
except (subprocess.TimeoutExpired, ValueError):
_LOGGER.warning("Timeout reading stdout.")
self.kill()
return None
|
async def get_version(self, timeout: int = 15) -> Optional[str]
|
Execute FFmpeg process and parse the version information.
Return full FFmpeg version string. Such as 3.4.2-tessus
| 5.481933
| 5.236951
| 1.046779
|
command = ["-an", "-c:v", "mjpeg"]
return self.open(
cmd=command,
input_source=input_source,
output="-f mpjpeg -",
extra_cmd=extra_cmd,
)
|
def open_camera(
self, input_source: str, extra_cmd: Optional[str] = None
) -> Coroutine
|
Open FFmpeg process as mjpeg video stream.
Return A coroutine.
| 5.232351
| 4.55362
| 1.149053
|
if sizeof(c_void_p) == 8:
if system() == 'Windows':
def_lib_name = 'nvrtc64_92.dll'
elif system() == 'Darwin':
def_lib_name = 'libnvrtc.dylib'
else:
def_lib_name = 'libnvrtc.so'
else:
raise NVRTCException('NVRTC is not supported on 32-bit platforms.')
if len(lib_path) == 0:
name = def_lib_name
else:
name = lib_path
self._lib = cdll.LoadLibrary(name)
self._lib.nvrtcCreateProgram.argtypes = [
POINTER(c_void_p), # prog
c_char_p, # src
c_char_p, # name
c_int, # numHeaders
POINTER(c_char_p), # headers
POINTER(c_char_p) # include_names
]
self._lib.nvrtcCreateProgram.restype = c_int
self._lib.nvrtcDestroyProgram.argtypes = [
POINTER(c_void_p) # prog
]
self._lib.nvrtcDestroyProgram.restype = c_int
self._lib.nvrtcCompileProgram.argtypes = [
c_void_p, # prog
c_int, # numOptions
POINTER(c_char_p) # options
]
self._lib.nvrtcCompileProgram.restype = c_int
self._lib.nvrtcGetPTXSize.argtypes = [
c_void_p, # prog
POINTER(c_size_t) # ptxSizeRet
]
self._lib.nvrtcGetPTXSize.restype = c_int
self._lib.nvrtcGetPTX.argtypes = [
c_void_p, # prog
c_char_p # ptx
]
self._lib.nvrtcGetPTX.restype = c_int
self._lib.nvrtcGetProgramLogSize.argtypes = [
c_void_p, # prog
POINTER(c_size_t) # logSizeRet
]
self._lib.nvrtcGetProgramLogSize.restype = c_int
self._lib.nvrtcGetProgramLog.argtypes = [
c_void_p, # prog
c_char_p # log
]
self._lib.nvrtcGetProgramLog.restype = c_int
self._lib.nvrtcAddNameExpression.argtypes = [
c_void_p, # prog
c_char_p # nameExpression
]
self._lib.nvrtcAddNameExpression.restype = c_int
self._lib.nvrtcGetLoweredName.argtypes = [
c_void_p, # prog
c_char_p, # nameExpression
POINTER(c_char_p) # loweredName
]
self._lib.nvrtcGetLoweredName.restype = c_int
self._lib.nvrtcGetErrorString.argtypes = [
c_int # result
]
self._lib.nvrtcGetErrorString.restype = c_char_p
self._lib.nvrtcVersion.argtypes = [
POINTER(c_int), # major
POINTER(c_int) # minor
]
self._lib.nvrtcVersion.restype = c_int
|
def _load_nvrtc_lib(self, lib_path)
|
Loads the NVRTC shared library, with an optional search path in
lib_path.
| 1.619162
| 1.620802
| 0.998988
|
res = c_void_p()
headers_array = (c_char_p * len(headers))()
headers_array[:] = encode_str_list(headers)
include_names_array = (c_char_p * len(include_names))()
include_names_array[:] = encode_str_list(include_names)
code = self._lib.nvrtcCreateProgram(byref(res),
c_char_p(encode_str(src)), c_char_p(encode_str(name)),
len(headers),
headers_array, include_names_array)
self._throw_on_error(code)
return res
|
def nvrtcCreateProgram(self, src, name, headers, include_names)
|
Creates and returns a new NVRTC program object.
| 2.001831
| 2.022063
| 0.989994
|
code = self._lib.nvrtcDestroyProgram(byref(prog))
self._throw_on_error(code)
return
|
def nvrtcDestroyProgram(self, prog)
|
Destroys the given NVRTC program object.
| 4.203535
| 3.922353
| 1.071687
|
options_array = (c_char_p * len(options))()
options_array[:] = encode_str_list(options)
code = self._lib.nvrtcCompileProgram(prog, len(options), options_array)
self._throw_on_error(code)
return
|
def nvrtcCompileProgram(self, prog, options)
|
Compiles the NVRTC program object into PTX, using the provided options
array. See the NVRTC API documentation for accepted options.
| 3.041172
| 3.022619
| 1.006138
|
size = c_size_t()
code = self._lib.nvrtcGetPTXSize(prog, byref(size))
self._throw_on_error(code)
buf = create_string_buffer(size.value)
code = self._lib.nvrtcGetPTX(prog, buf)
self._throw_on_error(code)
return buf.value.decode('utf-8')
|
def nvrtcGetPTX(self, prog)
|
Returns the compiled PTX for the NVRTC program object.
| 2.106316
| 2.091531
| 1.007069
|
size = c_size_t()
code = self._lib.nvrtcGetProgramLogSize(prog, byref(size))
self._throw_on_error(code)
buf = create_string_buffer(size.value)
code = self._lib.nvrtcGetProgramLog(prog, buf)
self._throw_on_error(code)
return buf.value.decode('utf-8')
|
def nvrtcGetProgramLog(self, prog)
|
Returns the log for the NVRTC program object.
Only useful after calls to nvrtcCompileProgram or nvrtcVerifyProgram.
| 2.081004
| 2.204177
| 0.944118
|
code = self._lib.nvrtcAddNameExpression(prog,
c_char_p(encode_str(name_expression)))
self._throw_on_error(code)
return
|
def nvrtcAddNameExpression(self, prog, name_expression)
|
Notes the given name expression denoting a __global__ function or
function template instantiation.
| 4.171294
| 4.288367
| 0.9727
|
lowered_name = c_char_p()
code = self._lib.nvrtcGetLoweredName(prog,
c_char_p(encode_str(name_expression)),
byref(lowered_name))
self._throw_on_error(code)
return lowered_name.value.decode('utf-8')
|
def nvrtcGetLoweredName(self, prog, name_expression)
|
Notes the given name expression denoting a __global__ function or
function template instantiation.
| 2.353155
| 2.511985
| 0.936771
|
code_int = c_int(code)
res = self._lib.nvrtcGetErrorString(code_int)
return res.decode('utf-8')
|
def nvrtcGetErrorString(self, code)
|
Returns a text identifier for the given NVRTC status code.
| 3.107767
| 2.860224
| 1.086547
|
major = c_int()
minor = c_int()
code = self._lib.nvrtcVersion(byref(major), byref(minor))
self._throw_on_error(code)
return (major.value, minor.value)
|
def nvrtcVersion(self)
|
Returns the loaded NVRTC library version as a (major, minor) tuple.
| 2.56989
| 2.13634
| 1.20294
|
if self._proc is None or self._proc.returncode is not None:
return False
return True
|
def is_running(self) -> bool
|
Return True if ffmpeg is running.
| 4.844814
| 3.529279
| 1.372749
|
self._argv = [self._ffmpeg]
# start command init
if input_source is not None:
self._put_input(input_source)
self._argv.extend(cmd)
# exists a extra cmd from customer
if extra_cmd is not None:
self._argv.extend(shlex.split(extra_cmd))
self._merge_filters()
self._put_output(output)
|
def _generate_ffmpeg_cmd(
self,
cmd: List[str],
input_source: Optional[str],
output: Optional[str],
extra_cmd: Optional[str] = None,
) -> None
|
Generate ffmpeg command line.
| 5.128026
| 4.754685
| 1.078521
|
input_cmd = shlex.split(str(input_source))
if len(input_cmd) > 1:
self._argv.extend(input_cmd)
else:
self._argv.extend(["-i", input_source])
|
def _put_input(self, input_source: str) -> None
|
Put input string to ffmpeg command.
| 3.625287
| 2.788386
| 1.300138
|
if output is None:
self._argv.extend(["-f", "null", "-"])
return
output_cmd = shlex.split(str(output))
if len(output_cmd) > 1:
self._argv.extend(output_cmd)
else:
self._argv.append(output)
|
def _put_output(self, output: Optional[str]) -> None
|
Put output string to ffmpeg command.
| 3.535629
| 2.538541
| 1.39278
|
for opts in (["-filter:a", "-af"], ["-filter:v", "-vf"]):
filter_list = []
new_argv = []
cmd_iter = iter(self._argv)
for element in cmd_iter:
if element in opts:
filter_list.insert(0, next(cmd_iter))
else:
new_argv.append(element)
# update argv if changes
if filter_list:
new_argv.extend([opts[0], ",".join(filter_list)])
self._argv = new_argv.copy()
|
def _merge_filters(self) -> None
|
Merge all filter config in command line.
| 3.811101
| 3.405031
| 1.119256
|
stdout = subprocess.PIPE if stdout_pipe else subprocess.DEVNULL
stderr = subprocess.PIPE if stderr_pipe else subprocess.DEVNULL
if self.is_running:
_LOGGER.warning("FFmpeg is already running!")
return True
# set command line
self._generate_ffmpeg_cmd(cmd, input_source, output, extra_cmd)
# start ffmpeg
_LOGGER.debug("Start FFmpeg with %s", str(self._argv))
try:
proc_func = functools.partial(
subprocess.Popen,
self._argv,
bufsize=0,
stdin=subprocess.PIPE,
stdout=stdout,
stderr=stderr,
)
self._proc = await self._loop.run_in_executor(None, proc_func)
except Exception as err: # pylint: disable=broad-except
_LOGGER.exception("FFmpeg fails %s", err)
self._clear()
return False
return self._proc is not None
|
async def open(
self,
cmd: List[str],
input_source: Optional[str],
output: Optional[str] = "-",
extra_cmd: Optional[str] = None,
stdout_pipe: bool = True,
stderr_pipe: bool = False,
) -> bool
|
Start a ffmpeg instance and pipe output.
| 2.614352
| 2.441902
| 1.070621
|
if not self.is_running:
_LOGGER.warning("FFmpeg isn't running!")
return
# Can't use communicate because we attach the output to a streamreader
def _close():
self._proc.stdin.write(b"q")
self._proc.wait(timeout=timeout)
# send stop to ffmpeg
try:
await self._loop.run_in_executor(None, _close)
_LOGGER.debug("Close FFmpeg process")
except (subprocess.TimeoutExpired, ValueError):
_LOGGER.warning("Timeout while waiting of FFmpeg")
self.kill()
finally:
self._clear()
|
async def close(self, timeout=5) -> None
|
Stop a ffmpeg instance.
| 5.692376
| 5.016955
| 1.134628
|
self._proc.kill()
self._loop.run_in_executor(None, self._proc.communicate)
|
def kill(self) -> None
|
Kill ffmpeg job.
| 5.193593
| 3.877258
| 1.339501
|
reader = asyncio.StreamReader(loop=self._loop)
reader_protocol = asyncio.StreamReaderProtocol(reader)
# Attach stream
if source == FFMPEG_STDOUT:
await self._loop.connect_read_pipe(
lambda: reader_protocol, self._proc.stdout
)
else:
await self._loop.connect_read_pipe(
lambda: reader_protocol, self._proc.stderr
)
# Start reader
return reader
|
async def get_reader(self, source=FFMPEG_STDOUT) -> asyncio.StreamReader
|
Create and return streamreader.
| 2.437556
| 2.312539
| 1.05406
|
if self._read_task is not None and not self._read_task.cancelled():
self._read_task.cancel()
return super().close(timeout)
|
def close(self, timeout: int = 5) -> None
|
Stop a ffmpeg instance.
Return a coroutine
| 4.076091
| 3.822864
| 1.06624
|
if pattern is not None:
cmp = re.compile(pattern)
_LOGGER.debug("Start working with pattern '%s'.", pattern)
# read lines
while self.is_running:
try:
line = await self._input.readline()
if not line:
break
line = line.decode()
except Exception: # pylint: disable=broad-except
break
match = True if pattern is None else cmp.search(line)
if match:
_LOGGER.debug("Process: %s", line)
await self._que.put(line)
try:
await self._loop.run_in_executor(None, self._proc.wait)
finally:
await self._que.put(None)
_LOGGER.debug("Close read ffmpeg output.")
|
async def _process_lines(self, pattern: Optional[str] = None) -> None
|
Read line from pipe they match with pattern.
| 3.637828
| 3.386178
| 1.074317
|
if self.is_running:
_LOGGER.warning("Can't start worker. It is allready running!")
return
if reading == FFMPEG_STDERR:
stdout = False
stderr = True
else:
stdout = True
stderr = False
# start ffmpeg and reading to queue
await self.open(
cmd=cmd,
input_source=input_source,
output=output,
extra_cmd=extra_cmd,
stdout_pipe=stdout,
stderr_pipe=stderr,
)
self._input = await self.get_reader(reading)
# start background processing
self._read_task = self._loop.create_task(self._process_lines(pattern))
self._loop.create_task(self._worker_process())
|
async def start_worker(
self,
cmd: List[str],
input_source: str,
output: Optional[str] = None,
extra_cmd: Optional[str] = None,
pattern: Optional[str] = None,
reading: str = FFMPEG_STDERR,
) -> None
|
Start ffmpeg do process data from output.
| 3.683087
| 3.494306
| 1.054025
|
try:
self._interface.nvrtcCompileProgram(self._program, options)
ptx = self._interface.nvrtcGetPTX(self._program)
return ptx
except NVRTCException as e:
log = self._interface.nvrtcGetProgramLog(self._program)
raise ProgramException(log)
|
def compile(self, options=[])
|
Compiles the program object to PTX using the compiler options
specified in `options`.
| 4.249146
| 3.877127
| 1.095952
|
self._time_duration = time_duration
self._time_reset = time_reset
self._peak = peak
|
def set_options(
self, time_duration: int = 1, time_reset: int = 2, peak: int = -30
) -> None
|
Set option parameter for noise sensor.
| 2.458785
| 1.980357
| 1.241587
|
command = ["-vn", "-filter:a", "silencedetect=n={}dB:d=1".format(self._peak)]
# run ffmpeg, read output
return self.start_worker(
cmd=command,
input_source=input_source,
output=output_dest,
extra_cmd=extra_cmd,
pattern="silence",
)
|
def open_sensor(
self,
input_source: str,
output_dest: Optional[str] = None,
extra_cmd: Optional[str] = None,
) -> Coroutine
|
Open FFmpeg process for read autio stream.
Return a coroutine.
| 6.62171
| 5.446999
| 1.215662
|
state = self.STATE_DETECT
timeout = self._time_duration
self._loop.call_soon(self._callback, False)
re_start = re.compile("silence_start")
re_end = re.compile("silence_end")
# process queue data
while True:
try:
_LOGGER.debug("Reading State: %d, timeout: %s", state, timeout)
with async_timeout.timeout(timeout, loop=self._loop):
data = await self._que.get()
timeout = None
if data is None:
self._loop.call_soon(self._callback, None)
return
except asyncio.TimeoutError:
_LOGGER.debug("Blocking timeout")
# noise
if state == self.STATE_DETECT:
# noise detected
self._loop.call_soon(self._callback, True)
state = self.STATE_NOISE
elif state == self.STATE_END:
# no noise
self._loop.call_soon(self._callback, False)
state = self.STATE_NONE
timeout = None
continue
if re_start.search(data):
if state == self.STATE_NOISE:
# stop noise detection
state = self.STATE_END
timeout = self._time_reset
elif state == self.STATE_DETECT:
# reset if only a peak
state = self.STATE_NONE
continue
if re_end.search(data):
if state == self.STATE_NONE:
# detect noise begin
state = self.STATE_DETECT
timeout = self._time_duration
elif state == self.STATE_END:
# back to noise status
state = self.STATE_NOISE
continue
_LOGGER.warning("Unknown data from queue!")
|
async def _worker_process(self) -> None
|
This function processing data.
| 3.260449
| 3.163691
| 1.030584
|
self._time_reset = time_reset
self._time_repeat = time_repeat
self._repeat = repeat
self._changes = changes
|
def set_options(
self,
time_reset: int = 60,
time_repeat: int = 0,
repeat: int = 0,
changes: int = 10,
) -> None
|
Set option parameter for noise sensor.
| 2.159485
| 1.806343
| 1.195501
|
command = [
"-an",
"-filter:v",
"select=gt(scene\\,{0})".format(self._changes / 100),
]
# run ffmpeg, read output
return self.start_worker(
cmd=command,
input_source=input_source,
output="-f framemd5 -",
extra_cmd=extra_cmd,
pattern=self.MATCH,
reading=FFMPEG_STDOUT,
)
|
def open_sensor(
self, input_source: str, extra_cmd: Optional[str] = None
) -> Coroutine
|
Open FFmpeg process a video stream for motion detection.
Return a coroutine.
| 10.126534
| 8.723669
| 1.160811
|
state = self.STATE_NONE
timeout = None
self._loop.call_soon(self._callback, False)
# for repeat feature
re_frame = 0
re_time = 0
re_data = re.compile(self.MATCH)
# process queue data
while True:
try:
_LOGGER.debug("Reading State: %d, timeout: %s", state, timeout)
with async_timeout.timeout(timeout, loop=self._loop):
data = await self._que.get()
if data is None:
self._loop.call_soon(self._callback, None)
return
except asyncio.TimeoutError:
_LOGGER.debug("Blocking timeout")
# reset motion detection
if state == self.STATE_MOTION:
state = self.STATE_NONE
self._loop.call_soon(self._callback, False)
timeout = None
# reset repeate state
if state == self.STATE_REPEAT:
state = self.STATE_NONE
timeout = None
continue
frames = re_data.search(data)
if frames:
# repeat not used
if self._repeat == 0 and state == self.STATE_NONE:
state = self.STATE_MOTION
self._loop.call_soon(self._callback, True)
timeout = self._time_reset
# repeat feature is on / first motion
if state == self.STATE_NONE:
state = self.STATE_REPEAT
timeout = self._time_repeat
re_frame = 0
re_time = time()
elif state == self.STATE_REPEAT:
re_frame += 1
# REPEAT ready?
if re_frame >= self._repeat:
state = self.STATE_MOTION
self._loop.call_soon(self._callback, True)
timeout = self._time_reset
else:
past = time() - re_time
timeout -= past
# REPEAT time down
if timeout <= 0:
_LOGGER.debug("Reset repeat to none")
state = self.STATE_NONE
timeout = None
continue
_LOGGER.warning("Unknown data from queue!")
|
async def _worker_process(self) -> None
|
This function processing data.
| 3.280765
| 3.20629
| 1.023228
|
if _gateway_is_running():
gateway = java_gateway.JavaGateway()
else:
driver_args = [driver_args] if isinstance(driver_args, str) else driver_args
if jars:
classpath = os.pathsep.join(jars) if isinstance(jars, list) else jars
else:
classpath = None
if libs:
javaopts = libs if isinstance(libs, list) else [libs]
else:
javaopts = []
gateway = java_gateway.JavaGateway.launch_gateway(
port=25333, classpath=classpath, javaopts=javaopts, die_on_exit=True)
java_gateway.java_import(gateway.jvm, 'java.sql.DriverManager')
gateway.jvm.Class.forName(jclassname)
connection = gateway.jvm.DriverManager.getConnection(*driver_args)
if _converters is None:
types_map = {}
for type in gateway.jvm.Class.forName("java.sql.Types").getFields():
types_map[type.getName()] = type.getInt(None)
_init_converters(types_map)
return Connection(connection, _converters)
|
def connect(jclassname, driver_args, jars=None, libs=None)
|
Open a connection to a database using a JDBC driver and return
a Connection instance.
jclassname: Full qualified Java class name of the JDBC driver.
driver_args: Argument or sequence of arguments to be passed to the
Java DriverManager.getConnection method. Usually the
database URL. See
http://docs.oracle.com/javase/6/docs/api/java/sql/DriverManager.html
for more details
jars: Jar filename or sequence of filenames for the JDBC driver
libs: Dll/so filenames or sequence of dlls/sos used as shared
library by the JDBC driver
| 2.871216
| 2.935676
| 0.978042
|
return self.add_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501
else:
(data) = self.add_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501
return data
|
def add_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Subscribe to a resource path # noqa: E501
The Device Management Connect eventing model consists of observable resources. This means that endpoints can deliver updated resource content, periodically or with a more sophisticated solution-dependent logic. The OMA LwM2M resource model including objects, object instances, resources and resource instances is also supported. Applications can subscribe to objects, object instances or individual resources to make the device to provide value change notifications to Device Management Connect service. An application needs to call a `/notification/callback` method to get Device Management Connect to push notifications of the resource changes. **Notification rules** A web application can place dynamic observation rules for individual Object Instances and Resources to define when the device sends observations. More information in [Notification rules](/docs/current/connecting/resource-change-webapp.html). All manual subscriptions are removed during a full device registration and applications need to re-subscribe at that point. To avoid this, you can use `/subscriptions` to set a pre-subscription. **Example usage:** curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.add_resource_subscription(device_id, _resource_path, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required)
:param str _resource_path: The URL of the resource. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.460582
| 1.960025
| 0.745185
|
return self.check_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501
else:
(data) = self.check_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501
return data
|
def check_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Read subscription status # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.check_resource_subscription(device_id, _resource_path, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required)
:param str _resource_path: The URL of the resource. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.456354
| 1.832163
| 0.794883
|
return self.delete_endpoint_subscriptions_with_http_info(device_id, **kwargs) # noqa: E501
else:
(data) = self.delete_endpoint_subscriptions_with_http_info(device_id, **kwargs) # noqa: E501
return data
|
def delete_endpoint_subscriptions(self, device_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Delete subscriptions from an endpoint # noqa: E501
Deletes all resource subscriptions in a single endpoint. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id} \\ -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.delete_endpoint_subscriptions(device_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.546765
| 1.976128
| 0.782725
|
return self.delete_pre_subscriptions_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.delete_pre_subscriptions_with_http_info(**kwargs) # noqa: E501
return data
|
def delete_pre_subscriptions(self, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Remove pre-subscriptions # noqa: E501
Removes pre-subscriptions. **Example usage:** curl -X DELETE https://api.us-east-1.mbedcloud.com/v2/subscriptions -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.delete_pre_subscriptions(asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.620253
| 2.134918
| 0.75893
|
return self.delete_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501
else:
(data) = self.delete_resource_subscription_with_http_info(device_id, _resource_path, **kwargs) # noqa: E501
return data
|
def delete_resource_subscription(self, device_id, _resource_path, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Remove a subscription # noqa: E501
To remove an existing subscription from a resource path. **Example usage:** curl -X DELETE \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id}/{resourcePath} \\ -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.delete_resource_subscription(device_id, _resource_path, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_id: A unique Device Management device ID for the endpoint. Note that the ID must be an exact match. You cannot use wildcards here. (required)
:param str _resource_path: The URL of the resource. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.44845
| 1.92682
| 0.751731
|
return self.get_endpoint_subscriptions_with_http_info(device_id, **kwargs) # noqa: E501
else:
(data) = self.get_endpoint_subscriptions_with_http_info(device_id, **kwargs) # noqa: E501
return data
|
def get_endpoint_subscriptions(self, device_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Read endpoints subscriptions # noqa: E501
Lists all subscribed resources from a single endpoint. **Example usage:** curl -X GET \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions/{device-id} \\ -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_endpoint_subscriptions(device_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_id: A unique Device Management device ID for the endpoint. Note that ID must be an exact match. You cannot use wildcards here. (required)
:return: str
If the method is called asynchronously,
returns the request thread.
| 1.536851
| 1.896107
| 0.81053
|
return self.get_pre_subscriptions_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_pre_subscriptions_with_http_info(**kwargs) # noqa: E501
return data
|
def get_pre_subscriptions(self, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Get pre-subscriptions # noqa: E501
You can retrieve the pre-subscription data with the GET operation. The server returns with the same JSON structure as described above. If there are no pre-subscribed resources, it returns with an empty array. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/subscriptions -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_pre_subscriptions(asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:return: PresubscriptionArray
If the method is called asynchronously,
returns the request thread.
| 1.611551
| 2.08336
| 0.773535
|
return self.update_pre_subscriptions_with_http_info(presubsription, **kwargs) # noqa: E501
else:
(data) = self.update_pre_subscriptions_with_http_info(presubsription, **kwargs) # noqa: E501
return data
|
def update_pre_subscriptions(self, presubsription, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Set pre-subscriptions # noqa: E501
Pre-subscription is a set of rules and patterns put by the application. When an endpoint registers and its ID, type and registered resources match the pre-subscription data, Device Management Connect sends subscription requests to the device automatically. The pattern may include the endpoint ID (optionally having an `*` character at the end), endpoint type, a list of resources or expressions with an `*` character at the end. Subscriptions based on pre-subscriptions are done when device registers or does register update. To remove the pre-subscription data, put an empty array as a rule. **Notification rules** A web application can place dynamic observation rules for individual Object Instances and Resources to define when the device sends observations. More information in [Notification rules](/docs/current/connecting/resource-change-webapp.html). **Limits**: - The maximum length of the endpoint name and endpoint type is 64 characters. - The maximum length of the resource path is 128 characters. - You can listen to 256 separate resource paths. - The maximum number of pre-subscription entries is 1024. **Example request:** ``` curl -X PUT \\ https://api.us-east-1.mbedcloud.com/v2/subscriptions \\ -H 'authorization: Bearer {api-key}' \\ -H 'content-type: application/json' \\ -d '[ { \"endpoint-name\": \"node-001\", \"resource-path\": [\"/dev\"] }, { \"endpoint-type\": \"Light\", \"resource-path\": [\"/sen/*\"] }, { \"endpoint-name\": \"node*\" }, { \"endpoint-type\": \"Sensor\" }, { \"resource-path\": [\"/dev/temp\",\"/dev/hum\"] } ]' ``` - Subscribe to `/dev` resource of endpoint named `node-001`. - Subscribe to `Light` type of endpoints and their resources prefixed with `/sen/`. - Subscribe to all observable resources of endpoint names prefixed with `node`. - Subscribe to all observable resources of `Sensor` type endpoints. - Subscribe to `/dev/temp` and `/dev/hum` resources of all endpoints. **Note**: For efficiency reasons, you should use resource path patterns in the pre-subscription data. This prevents the notification flow from unwanted resources. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.update_pre_subscriptions(presubsription, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param PresubscriptionArray presubsription: Array of pre-subscriptions. (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.502579
| 1.991391
| 0.754538
|
api = self._get_api(bootstrap.PreSharedKeysApi)
item = PreSharedKey._create_request_map(kwargs)
item = models.PreSharedKey(**item)
api.upload_pre_shared_key(item)
return PreSharedKey(item)
|
def add_psk(self, **kwargs)
|
Add
| 8.351789
| 8.421246
| 0.991752
|
api = self._get_api(bootstrap.PreSharedKeysApi)
return PreSharedKey(api.get_pre_shared_key(endpoint_name=endpoint_name))
|
def get_psk(self, endpoint_name, **kwargs)
|
Get
| 7.778069
| 8.587912
| 0.9057
|
api = self._get_api(bootstrap.PreSharedKeysApi)
return PaginatedResponse(api.list_pre_shared_keys, lwrap_type=PreSharedKey, **kwargs)
|
def list_psks(self, **kwargs)
|
List
| 9.399859
| 10.413176
| 0.902689
|
api = self._get_api(bootstrap.PreSharedKeysApi)
return api.delete_pre_shared_key(endpoint_name=endpoint_name)
|
def delete_psk(self, endpoint_name, **kwargs)
|
Delete
| 6.544183
| 6.879574
| 0.951248
|
if ca_id is not None and len(ca_id) > 500:
raise ValueError("Invalid value for `ca_id`, length must be less than or equal to `500`")
self._ca_id = ca_id
|
def ca_id(self, ca_id)
|
Sets the ca_id of this DeviceData.
The certificate issuer's ID.
:param ca_id: The ca_id of this DeviceData.
:type: str
| 2.018457
| 2.453876
| 0.822559
|
allowed_values = ["development", "production"]
if deployed_state not in allowed_values:
raise ValueError(
"Invalid value for `deployed_state` ({0}), must be one of {1}"
.format(deployed_state, allowed_values)
)
self._deployed_state = deployed_state
|
def deployed_state(self, deployed_state)
|
Sets the deployed_state of this DeviceData.
DEPRECATED: The state of the device's deployment.
:param deployed_state: The deployed_state of this DeviceData.
:type: str
| 1.836834
| 1.93758
| 0.948004
|
if device_class is not None and len(device_class) > 32:
raise ValueError("Invalid value for `device_class`, length must be less than or equal to `32`")
self._device_class = device_class
|
def device_class(self, device_class)
|
Sets the device_class of this DeviceData.
An ID representing the model and hardware revision of the device.
:param device_class: The device_class of this DeviceData.
:type: str
| 2.229433
| 1.970717
| 1.13128
|
if device_key is not None and len(device_key) > 512:
raise ValueError("Invalid value for `device_key`, length must be less than or equal to `512`")
self._device_key = device_key
|
def device_key(self, device_key)
|
Sets the device_key of this DeviceData.
The fingerprint of the device certificate.
:param device_key: The device_key of this DeviceData.
:type: str
| 1.97436
| 2.153408
| 0.916854
|
if endpoint_type is not None and len(endpoint_type) > 64:
raise ValueError("Invalid value for `endpoint_type`, length must be less than or equal to `64`")
self._endpoint_type = endpoint_type
|
def endpoint_type(self, endpoint_type)
|
Sets the endpoint_type of this DeviceData.
The endpoint type of the device. For example, the device is a gateway.
:param endpoint_type: The endpoint_type of this DeviceData.
:type: str
| 1.987363
| 2.158544
| 0.920696
|
allowed_values = ["connector", "direct"]
if mechanism not in allowed_values:
raise ValueError(
"Invalid value for `mechanism` ({0}), must be one of {1}"
.format(mechanism, allowed_values)
)
self._mechanism = mechanism
|
def mechanism(self, mechanism)
|
Sets the mechanism of this DeviceData.
The ID of the channel used to communicate with the device.
:param mechanism: The mechanism of this DeviceData.
:type: str
| 2.23584
| 2.648117
| 0.844313
|
clients = ([self.api_clients[api_parent_class]]
if api_parent_class else self.api_clients.values())
for api_client in clients:
api_client.configuration.host = (self.config.get('host') or
api_client.configuration.host)
api_client.configuration.api_key['Authorization'] = self.config['api_key']
|
def _update_api_client(self, api_parent_class=None)
|
Updates the ApiClient object of specified parent api (or all of them)
| 2.759841
| 2.498293
| 1.104691
|
return (filters.legacy_filter_formatter if encode else filters.filter_formatter)(
kwargs,
obj._get_attributes_map()
)
|
def _verify_filters(self, kwargs, obj, encode=False)
|
Legacy entrypoint with 'encode' flag
| 12.496416
| 9.9257
| 1.258996
|
last_metadata = None
for key, api in iteritems(self.apis):
api_client = api.api_client
if api_client is not None:
metadata = api_client.get_last_metadata()
if metadata is not None and metadata.get('timestamp', None) is not None:
if last_metadata is None:
last_metadata = metadata
elif metadata["timestamp"] >= last_metadata["timestamp"]:
last_metadata = metadata
if last_metadata is not None:
last_metadata = ApiMetadata(last_metadata.get("url"),
last_metadata.get("method"),
last_metadata.get("response", None),
last_metadata.get("return_data", None),
last_metadata.get("exception", None))
return last_metadata
|
def get_last_api_metadata(self)
|
Get meta data for the last Mbed Cloud API call.
:returns: meta data of the last Mbed Cloud API call
:rtype: ApiMetadata
| 2.327457
| 2.424361
| 0.960029
|
response = {'success': True}
# check dates can be manipulated
response.update(kwargs)
response.update(self.kwargs)
response['test_argument3'] = datetime.timedelta(days=1) + response['test_argument3']
return response
|
def success(self, **kwargs)
|
Returns all arguments received in init and this method call
| 9.145823
| 8.244319
| 1.109349
|
if not isinstance(updates, dict):
updates = updates.to_dict()
for sdk_key, spec_key in self._get_attributes_map().items():
attr = '_%s' % sdk_key
if spec_key in updates and not hasattr(self, attr):
setattr(self, attr, updates[spec_key])
|
def update_attributes(self, updates)
|
Update attributes.
| 3.58541
| 3.4142
| 1.050146
|
field_map = cls._get_attributes_map()
return {field_map[k]: v for k, v in input_map.items() if k in field_map}
|
def _create_request_map(cls, input_map)
|
Create request map.
| 3.387391
| 2.891784
| 1.171384
|
dictionary = {}
for key, value in iteritems(self.__dict__):
property_name = key[1:]
if hasattr(self, property_name):
dictionary.update({property_name: getattr(self, property_name, None)})
return dictionary
|
def to_dict(self)
|
Return dictionary of object.
| 3.210835
| 2.794615
| 1.148936
|
if etag is None:
raise ValueError("Invalid value for `etag`, must not be `None`")
if etag is not None and not re.search('[A-Za-z0-9]{0,256}', etag):
raise ValueError("Invalid value for `etag`, must be a follow pattern or equal to `/[A-Za-z0-9]{0,256}/`")
self._etag = etag
|
def etag(self, etag)
|
Sets the etag of this BulkResponse.
etag
:param etag: The etag of this BulkResponse.
:type: str
| 1.839171
| 1.707212
| 1.077295
|
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
if id is not None and not re.search('^[A-Za-z0-9]{32}', id):
raise ValueError("Invalid value for `id`, must be a follow pattern or equal to `/^[A-Za-z0-9]{32}/`")
self._id = id
|
def id(self, id)
|
Sets the id of this BulkResponse.
Bulk ID
:param id: The id of this BulkResponse.
:type: str
| 1.861092
| 1.695915
| 1.097397
|
allowed_values = ["enforced", "optional"]
if mfa_status not in allowed_values:
raise ValueError(
"Invalid value for `mfa_status` ({0}), must be one of {1}"
.format(mfa_status, allowed_values)
)
self._mfa_status = mfa_status
|
def mfa_status(self, mfa_status)
|
Sets the mfa_status of this AccountInfo.
The enforcement status of the multi-factor authentication, either 'enforced' or 'optional'.
:param mfa_status: The mfa_status of this AccountInfo.
:type: str
| 1.797419
| 1.675755
| 1.072603
|
return self.device_create_with_http_info(device, **kwargs) # noqa: E501
else:
(data) = self.device_create_with_http_info(device, **kwargs) # noqa: E501
return data
|
def device_create(self, device, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Create a device # noqa: E501
Create a new device. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_create(device, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param DeviceDataPostRequest device: (required)
:return: DeviceData
If the method is called asynchronously,
returns the request thread.
| 1.587429
| 2.124882
| 0.747067
|
return self.device_destroy_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.device_destroy_with_http_info(id, **kwargs) # noqa: E501
return data
|
def device_destroy(self, id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Delete a device. # noqa: E501
Delete device. Only available for devices with a developer certificate. Attempts to delete a device with a production certicate will return a 400 response. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_destroy(id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.596116
| 2.151686
| 0.741798
|
return self.device_event_retrieve_with_http_info(device_event_id, **kwargs) # noqa: E501
else:
(data) = self.device_event_retrieve_with_http_info(device_event_id, **kwargs) # noqa: E501
return data
|
def device_event_retrieve(self, device_event_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Retrieve a device event. # noqa: E501
Retrieve a specific device event. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_event_retrieve(device_event_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_event_id: (required)
:return: DeviceEventData
If the method is called asynchronously,
returns the request thread.
| 1.500552
| 1.919329
| 0.781811
|
return self.device_log_retrieve_with_http_info(device_event_id, **kwargs) # noqa: E501
else:
(data) = self.device_log_retrieve_with_http_info(device_event_id, **kwargs) # noqa: E501
return data
|
def device_log_retrieve(self, device_event_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
DEPRECATED: Retrieve a device event. # noqa: E501
Retrieve device event (deprecated, use /v3/device-events/{device_event_id}/ instead) # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_log_retrieve(device_event_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_event_id: (required)
:return: DeviceEventData
If the method is called asynchronously,
returns the request thread.
| 1.504586
| 1.879228
| 0.80064
|
return self.device_query_create_with_http_info(device, **kwargs) # noqa: E501
else:
(data) = self.device_query_create_with_http_info(device, **kwargs) # noqa: E501
return data
|
def device_query_create(self, device, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Create a device query # noqa: E501
Create a new device query. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_query_create(device, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param DeviceQueryPostPutRequest device: (required)
:return: DeviceQuery
If the method is called asynchronously,
returns the request thread.
| 1.543363
| 2.075016
| 0.743783
|
return self.device_query_destroy_with_http_info(query_id, **kwargs) # noqa: E501
else:
(data) = self.device_query_destroy_with_http_info(query_id, **kwargs) # noqa: E501
return data
|
def device_query_destroy(self, query_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Delete a device query # noqa: E501
Delete a device query. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_query_destroy(query_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str query_id: (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.511951
| 1.985437
| 0.761521
|
return self.device_query_retrieve_with_http_info(query_id, **kwargs) # noqa: E501
else:
(data) = self.device_query_retrieve_with_http_info(query_id, **kwargs) # noqa: E501
return data
|
def device_query_retrieve(self, query_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Retrieve a device query. # noqa: E501
Retrieve a specific device query. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_query_retrieve(query_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str query_id: (required)
:return: DeviceQuery
If the method is called asynchronously,
returns the request thread.
| 1.507919
| 1.968684
| 0.765953
|
return self.device_query_update_with_http_info(query_id, body, **kwargs) # noqa: E501
else:
(data) = self.device_query_update_with_http_info(query_id, body, **kwargs) # noqa: E501
return data
|
def device_query_update(self, query_id, body, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Update a device query # noqa: E501
Update a specifc device query. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_query_update(query_id, body, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str query_id: (required)
:param DeviceQueryPostPutRequest body: Device query update object. (required)
:return: DeviceQuery
If the method is called asynchronously,
returns the request thread.
| 1.501358
| 1.926914
| 0.779151
|
return self.device_retrieve_with_http_info(id, **kwargs) # noqa: E501
else:
(data) = self.device_retrieve_with_http_info(id, **kwargs) # noqa: E501
return data
|
def device_retrieve(self, id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Get a devices # noqa: E501
Retrieve information about a specific device. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_retrieve(id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str id: (required)
:return: DeviceData
If the method is called asynchronously,
returns the request thread.
| 1.587704
| 2.19525
| 0.723245
|
return self.device_update_with_http_info(id, device, **kwargs) # noqa: E501
else:
(data) = self.device_update_with_http_info(id, device, **kwargs) # noqa: E501
return data
|
def device_update(self, id, device, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Update a device # noqa: E501
Update a specific device. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.device_update(id, device, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str id: The ID of the device. (required)
:param DeviceDataPutRequest device: (required)
:return: DeviceData
If the method is called asynchronously,
returns the request thread.
| 1.564773
| 2.097504
| 0.746017
|
return self.group_create_with_http_info(group, **kwargs) # noqa: E501
else:
(data) = self.group_create_with_http_info(group, **kwargs) # noqa: E501
return data
|
def group_create(self, group, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Create a group # noqa: E501
Create a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_create(group, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param Group group: Group (required)
:return: DeviceGroup
If the method is called asynchronously,
returns the request thread.
| 1.558465
| 2.17205
| 0.717509
|
return self.group_delete_with_http_info(device_group_id, **kwargs) # noqa: E501
else:
(data) = self.group_delete_with_http_info(device_group_id, **kwargs) # noqa: E501
return data
|
def group_delete(self, device_group_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Delete a group # noqa: E501
Delete a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_delete(device_group_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_group_id: The ID of the group (required)
:return: None
If the method is called asynchronously,
returns the request thread.
| 1.537524
| 2.016893
| 0.762323
|
return self.group_members_add_with_http_info(device_group_id, body, **kwargs) # noqa: E501
else:
(data) = self.group_members_add_with_http_info(device_group_id, body, **kwargs) # noqa: E501
return data
|
def group_members_add(self, device_group_id, body, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Add a device to a group # noqa: E501
Add one device to a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_members_add(device_group_id, body, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_group_id: The ID of the group (required)
:param DeviceGroupManipulation body: Body of the request (required)
:return: DevicePage
If the method is called asynchronously,
returns the request thread.
| 1.522326
| 1.92379
| 0.791316
|
return self.group_members_remove_with_http_info(device_group_id, body, **kwargs) # noqa: E501
else:
(data) = self.group_members_remove_with_http_info(device_group_id, body, **kwargs) # noqa: E501
return data
|
def group_members_remove(self, device_group_id, body, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Remove a device from a group # noqa: E501
Remove one device from a group # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_members_remove(device_group_id, body, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_group_id: The ID of the group (required)
:param DeviceGroupManipulation body: Body of the request (required)
:return: DevicePage
If the method is called asynchronously,
returns the request thread.
| 1.525161
| 1.900542
| 0.802487
|
return self.group_retrieve_with_http_info(device_group_id, **kwargs) # noqa: E501
else:
(data) = self.group_retrieve_with_http_info(device_group_id, **kwargs) # noqa: E501
return data
|
def group_retrieve(self, device_group_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Get a group. # noqa: E501
Get a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_retrieve(device_group_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_group_id: The group ID (required)
:return: DeviceGroup
If the method is called asynchronously,
returns the request thread.
| 1.519118
| 2.052698
| 0.740059
|
return self.group_update_with_http_info(device_group_id, group, **kwargs) # noqa: E501
else:
(data) = self.group_update_with_http_info(device_group_id, group, **kwargs) # noqa: E501
return data
|
def group_update(self, device_group_id, group, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
Modify the attributes of a group. # noqa: E501
Modify the attributes of a group. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.group_update(device_group_id, group, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_group_id: (required)
:param Group1 group: Group (required)
:return: DeviceGroup
If the method is called asynchronously,
returns the request thread.
| 1.496789
| 1.956899
| 0.764878
|
# observers for this channel only need to wait for one value
self._observer_params.update(dict(once=True))
super(CurrentResourceValue, self).start()
self._api.ensure_notifications_thread()
self._api._mds_rpc_post(
device_id=self.device_id,
method='GET',
uri=self.resource_path,
async_id=self.async_id,
_wrap_with_consumer=False,
)
|
def start(self)
|
Start the channel
| 12.674104
| 12.692767
| 0.99853
|
payload = tlv.decode(
payload=data.get('payload'),
content_type=data.get('ct'),
decode_b64=True
)
super(CurrentResourceValue, self)._notify(payload)
# after one response, close the channel
self.ensure_stopped()
|
def _notify(self, data)
|
Notify this channel of inbound data
| 13.103362
| 12.541371
| 1.044811
|
if account_id is None:
raise ValueError("Invalid value for `account_id`, must not be `None`")
if account_id is not None and len(account_id) > 250:
raise ValueError("Invalid value for `account_id`, length must be less than or equal to `250`")
if account_id is not None and len(account_id) < 1:
raise ValueError("Invalid value for `account_id`, length must be greater than or equal to `1`")
self._account_id = account_id
|
def account_id(self, account_id)
|
Sets the account_id of this ServicePackageQuotaHistoryReservation.
Account ID.
:param account_id: The account_id of this ServicePackageQuotaHistoryReservation.
:type: str
| 1.377008
| 1.408046
| 0.977957
|
if campaign_name is None:
raise ValueError("Invalid value for `campaign_name`, must not be `None`")
if campaign_name is not None and len(campaign_name) > 250:
raise ValueError("Invalid value for `campaign_name`, length must be less than or equal to `250`")
if campaign_name is not None and len(campaign_name) < 1:
raise ValueError("Invalid value for `campaign_name`, length must be greater than or equal to `1`")
self._campaign_name = campaign_name
|
def campaign_name(self, campaign_name)
|
Sets the campaign_name of this ServicePackageQuotaHistoryReservation.
Textual campaign name for this reservation.
:param campaign_name: The campaign_name of this ServicePackageQuotaHistoryReservation.
:type: str
| 1.381303
| 1.386858
| 0.995994
|
if id is None:
raise ValueError("Invalid value for `id`, must not be `None`")
if id is not None and len(id) > 250:
raise ValueError("Invalid value for `id`, length must be less than or equal to `250`")
if id is not None and len(id) < 1:
raise ValueError("Invalid value for `id`, length must be greater than or equal to `1`")
self._id = id
|
def id(self, id)
|
Sets the id of this ServicePackageQuotaHistoryReservation.
Reservation ID.
:param id: The id of this ServicePackageQuotaHistoryReservation.
:type: str
| 1.502738
| 1.447524
| 1.038144
|
string_channels = {
ChannelIdentifiers.de_registrations,
ChannelIdentifiers.registrations_expired
}
if data['channel'] in string_channels:
message = {'device_id': data["value"], 'channel': data["channel"]}
else:
message = DeviceStateChanges._map_endpoint_data(data)
return super(DeviceStateChanges, self).notify(message)
|
def notify(self, data)
|
Notify this channel of inbound data
| 8.84362
| 9.193442
| 0.961949
|
return self.get_connected_endpoints_with_http_info(**kwargs) # noqa: E501
else:
(data) = self.get_connected_endpoints_with_http_info(**kwargs) # noqa: E501
return data
|
def get_connected_endpoints(self, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
(DEPRECATED) List registered endpoints. The number of returned endpoints is currently limited to 200. # noqa: E501
Endpoints are physical devices having valid registration to Device Management. All devices regardless of registration status can be requested from Device Directory API ['/v3/devices/`](/docs/current/service-api-references/device-directory.html). **Note:** This endpoint is deprecated and will be removed 1Q/18. You should use the Device Directory API [`/v3/devices/`](/docs/current/service-api-references/device-directory.html). To list only the registered devices, use filter `/v3/devices/?filter=state%3Dregistered`. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/endpoints -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_connected_endpoints(asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str type: Filter endpoints by endpoint-type.
:return: list[Endpoint]
If the method is called asynchronously,
returns the request thread.
| 1.620596
| 2.197385
| 0.737511
|
return self.get_endpoint_resources_with_http_info(device_id, **kwargs) # noqa: E501
else:
(data) = self.get_endpoint_resources_with_http_info(device_id, **kwargs) # noqa: E501
return data
|
def get_endpoint_resources(self, device_id, **kwargs): # noqa: E501
kwargs['_return_http_data_only'] = True
if kwargs.get('asynchronous')
|
List the resources on an endpoint # noqa: E501
The list of resources is cached by Device Management Connect, so this call does not create a message to the device. **Example usage:** curl -X GET https://api.us-east-1.mbedcloud.com/v2/endpoints/{device-id} -H 'authorization: Bearer {api-key}' # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True
>>> thread = api.get_endpoint_resources(device_id, asynchronous=True)
>>> result = thread.get()
:param asynchronous bool
:param str device_id: A unique device ID for an endpoint. Note that the ID needs to be an exact match. You cannot use wildcards here. (required)
:return: list[Resource]
If the method is called asynchronously,
returns the request thread.
| 1.537122
| 1.855149
| 0.82857
|
@functools.wraps(fn)
def wrapped_f(self, *args, **kwargs):
self.last_metadata = {}
self.last_metadata["url"] = self.configuration.host + args[0]
self.last_metadata["method"] = args[1]
self.last_metadata["timestamp"] = time.time()
try:
return fn(self, *args, **kwargs)
except Exception as e:
self.last_metadata["exception"] = e
raise
return wrapped_f
|
def metadata_wrapper(fn)
|
Save metadata of last api call.
| 2.348583
| 2.159441
| 1.087588
|
if not asynchronous:
return self.__call_api(resource_path, method,
path_params, query_params, header_params,
body, post_params, files,
response_type, auth_settings,
_return_http_data_only, collection_formats, _preload_content, _request_timeout)
else:
thread = self.pool.apply_async(self.__call_api, (resource_path, method,
path_params, query_params,
header_params, body,
post_params, files,
response_type, auth_settings,
_return_http_data_only,
collection_formats, _preload_content, _request_timeout))
return thread
|
def call_api(self, resource_path, method,
path_params=None, query_params=None, header_params=None,
body=None, post_params=None, files=None,
response_type=None, auth_settings=None, asynchronous=None,
_return_http_data_only=None, collection_formats=None, _preload_content=True,
_request_timeout=None)
|
Makes the HTTP request (synchronous) and return the deserialized data.
To make an async request, set the asynchronous parameter.
:param resource_path: Path to method endpoint.
:param method: Method to call.
:param path_params: Path parameters in the url.
:param query_params: Query parameters in the url.
:param header_params: Header parameters to be
placed in the request header.
:param body: Request body.
:param post_params dict: Request post form parameters,
for `application/x-www-form-urlencoded`, `multipart/form-data`.
:param auth_settings list: Auth Settings names for the request.
:param response: Response data type.
:param files dict: key -> filename, value -> filepath,
for `multipart/form-data`.
:param asynchronous bool: execute request asynchronously
:param _return_http_data_only: response data without head status code and headers
:param collection_formats: dict of collection formats for path, query,
header, and post parameters.
:param _preload_content: if False, the urllib3.HTTPResponse object will be returned without
reading/decoding response data. Default is True.
:param _request_timeout: timeout setting for this request. If one number provided, it will be total request
timeout. It can also be a pair (tuple) of (connection, read) timeouts.
:return:
If asynchronous parameter is True,
the request will be called asynchronously.
The method will return the request thread.
If parameter asynchronous is False or missing,
then the method will return the response directly.
| 1.525878
| 1.590374
| 0.959446
|
params = post_params or []
for key, values in (files or {}).items():
for maybe_file_or_path in values if isinstance(values, list) else [values]:
try:
# use the parameter as if it was an open file object
data = maybe_file_or_path.read()
maybe_file_or_path = maybe_file_or_path.name
except AttributeError:
# then it is presumably a file path
with open(maybe_file_or_path, 'rb') as fh:
data = fh.read()
basepath = os.path.basename(maybe_file_or_path)
mimetype = mimetypes.guess_type(basepath)[0] or 'application/octet-stream'
params.append((key, (basepath, data, mimetype)))
return params
|
def prepare_post_parameters(self, post_params=None, files=None)
|
Builds form parameters.
:param post_params: Normal form parameters.
:param files: File parameters.
:return: Form parameters with files.
| 2.697558
| 2.899963
| 0.930205
|
new_filter = {}
for key, constraints in filter_obj.items():
aliased_key = key
if attr_map is not None:
aliased_key = attr_map.get(key)
if aliased_key is None:
raise CloudValueError(
'Invalid key %r for filter attribute; must be one of:\n%s' % (
key,
attr_map.keys()
)
)
if not isinstance(constraints, dict):
constraints = {'eq': constraints}
for operator, value in constraints.items():
# FIXME: deprecate this $ nonsense
canonical_operator = FILTER_OPERATOR_ALIASES.get(operator.lstrip('$'))
if canonical_operator is None:
raise CloudValueError(
'Invalid operator %r for filter key %s; must be one of:\n%s' % (
operator,
key,
FILTER_OPERATOR_ALIASES.keys()
)
)
canonical_key = str('%s__%s' % (aliased_key, canonical_operator))
new_filter[canonical_key] = _normalise_value(value)
return new_filter
|
def _normalise_key_values(filter_obj, attr_map=None)
|
Converts nested dictionary filters into django-style key value pairs
Map filter operators and aliases to operator-land
Additionally, perform replacements according to attribute map
Automatically assumes __eq if not explicitly defined
| 2.62259
| 2.622051
| 1.000205
|
if not isinstance(sdk_filter, dict):
raise CloudValueError('filter value must be a dictionary, was %r' % (sdk_filter,))
custom = sdk_filter.pop('custom_attributes', {})
new_filter = _normalise_key_values(filter_obj=sdk_filter, attr_map=attr_map)
new_filter.update({
'custom_attributes__%s' % k: v for k, v in _normalise_key_values(filter_obj=custom).items()
})
return new_filter
|
def _get_filter(sdk_filter, attr_map)
|
Common functionality for filter structures
:param sdk_filter: {field:constraint, field:{operator:constraint}, ...}
:return: {field__operator: constraint, ...}
| 3.446635
| 3.59058
| 0.95991
|
params = _depluralise_filters_key(copy.copy(kwargs))
new_filter = _get_filter(sdk_filter=params.pop('filter', {}), attr_map=attr_map)
if new_filter:
new_filter = sorted([(k.rsplit('__eq')[0], v) for k, v in new_filter.items()])
params['filter'] = urllib.parse.urlencode(new_filter)
return params
|
def legacy_filter_formatter(kwargs, attr_map)
|
Builds a filter for update and device apis
:param kwargs: expected to contain {'filter/filters': {filter dict}}
:returns: {'filter': 'url-encoded-validated-filter-string'}
| 4.886186
| 4.656833
| 1.049251
|
params = _depluralise_filters_key(copy.copy(kwargs))
params.update(_get_filter(sdk_filter=params.pop('filter', {}), attr_map=attr_map))
return params
|
def filter_formatter(kwargs, attr_map)
|
Builds a filter according to the cross-api specification
:param kwargs: expected to contain {'filter': {filter dict}}
:returns: {validated filter dict}
| 9.890545
| 11.094527
| 0.89148
|
if self._total_count is None:
self._total_count = self._get_total_count()
return self._total_count
|
def count(self)
|
Approximate number of results, according to the API
| 3.330496
| 2.951692
| 1.128335
|
all = list(self)
if self._results_cache:
return iter(self._results_cache)
return all
|
def all(self)
|
All results
| 8.501871
| 7.801351
| 1.089795
|
if self._results_cache:
return self._results_cache[0]
query = PaginatedResponse(func=self._func, lwrap_type=self._lwrap_type, **self._kwargs)
try:
return next(query)
except StopIteration:
return None
|
def first(self)
|
Returns the first item from the query, or None if there are no results
| 5.951494
| 5.153379
| 1.154872
|
return dict(
after=self._kwargs.get('after'),
data=list(self),
has_more=self._has_more,
limit=self._max_results,
order=self._kwargs.get('order', 'ASC'),
page_size=self._page_size,
total_count=self.count(),
)
|
def to_dict(self)
|
Internal state
| 4.377442
| 4.256392
| 1.02844
|
import warnings
warnings.warn(
'`data` attribute is deprecated and will be removed in a future release, '
'use %s as an iterable instead' % (PaginatedResponse,),
category=DeprecationWarning,
stacklevel=2 # log wherever '.data' is referenced, rather than this line
)
return list(self)
|
def data(self)
|
Deprecated. Returns the data as a `list`
| 9.114811
| 8.465303
| 1.076726
|
slack_token = os.environ.get('SLACK_API_TOKEN')
channel_id = os.environ.get('SLACK_CHANNEL', '#mbed-cloud-sdk')
message = os.environ.get('SLACK_MESSAGE', (
':checkered_flag: New version of :snake: Python SDK released: *{version}* '
'(<https://pypi.org/project/mbed-cloud-sdk/{version}/|PyPI>)'
))
if not slack_token:
print('no slack token')
return
version = os.environ.get('SLACK_NOTIFY_VERSION')
if not version:
try:
import mbed_cloud
except ImportError:
pass
else:
version = mbed_cloud.__version__
payload = message.format(version=version) if version else message
print('notifying slack channel %s with payload:\n%s' % (channel_id, payload))
sc = SlackClient(slack_token)
sc.api_call(
'chat.postMessage',
channel=channel_id,
text=payload,
)
|
def main()
|
Sends release notifications to interested parties
Currently this is an arm-internal slack channel.
1. assumes you've set a token for an authorised slack user/bot.
2. assumes said user/bot is already in channel.
otherwise: https://github.com/slackapi/python-slackclient#joining-a-channel
| 2.755089
| 2.693883
| 1.02272
|
if service is None:
raise ValueError("Invalid value for `service`, must not be `None`")
allowed_values = ["lwm2m", "bootstrap"]
if service not in allowed_values:
raise ValueError(
"Invalid value for `service` ({0}), must be one of {1}"
.format(service, allowed_values)
)
self._service = service
|
def service(self, service)
|
Sets the service of this TrustedCertificateInternalResp.
Service name where the certificate is to be used.
:param service: The service of this TrustedCertificateInternalResp.
:type: str
| 2.008453
| 2.019976
| 0.994295
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.