def get_command_name(self, to, requested_command_id):
"""
Sends a messge down the serial line requesting the property name of a given property ID,
used in discovery protocol
:param to: destination ID
:param requested_command_id: command ID that we want to know the name of
:return: name from Embedded Core
"""
try:
response = yield self.send_command(to, command_id=GET_COMMAND_NAME, params=["command_id"],
data=[requested_command_id])
except Exception as e:
logger.error("[PCOM] Unable to find command name for command {0} in item {1} because of exception:"
"{2}".format(requested_command_id, to, e))
defer.returnValue(None)
# The data in the response message will be a list,
# the command name should be in the 0th position
try:
defer.returnValue(response.data[0])
except IndexError:
logger.error("Response from embedded board during discovery sequence did not return data in expect format."
" Expected at least one data field, received: {0}".format(response.data))
defer.returnValue(None)
python类returnValue()的实例源码
def get_command_input_param_format(self, to, requested_command_id):
"""
Given a command ID and item ID, sends a message to the item ID requesting
the format of its input parameters. This functions should return a string
that describes each parameter. NOTE: variable arrays are indicated with a *.
Eg. A list of ints would be "*i". See format string details for character->byte
translation.
:param to: destination item ID
:param requested_command_id: command ID that we want the parameter format of
:return: format string describing input parameters
"""
try:
response = yield self.send_command(to, command_id=GET_COMMAND_INPUT_PARAM_FORMAT, params=["command_id"],
data=[requested_command_id])
except Exception as e:
logger.error("[PCOM] Unable to find command input format for command {0} in item {1} because of exception:"
"{2}".format(requested_command_id, to, e))
defer.returnValue(None)
r_val = '' if len(response.data) == 0 else response.data[0]
defer.returnValue(r_val)
def get_command_input_param_names(self, to, requested_command_id):
"""
Given an item ID and a command ID, requests the parameter names of the command from the item.
Returns a list of names (comma delimited) that represent the parameter names.
TODO: change return value to string?
Eg. "frequency,duty cycle"
:param to: destination item ID
:param requested_command_id: command id to find the parameter names of
:return: a list of parameter names
"""
try:
response = yield self.send_command(to, command_id=GET_COMMAND_INPUT_PARAM_NAMES, params=["command_id"],
data=[requested_command_id])
except Exception as e:
logger.error("[PCOM] Unable to find command input parameter names for command {0} in item {1} because of "
"exception: {2}".format(requested_command_id, to, e))
defer.returnValue(None)
param_names = [] if len(response.data) == 0 else [x.strip() for x in response.data[0].split(',')]
defer.returnValue(param_names)
def get_property_type(self, to, requested_property_id):
"""
Given a property ID, requests the property's type from the item ID.
Gets back a format string.
:param to: destination item ID
:param requested_property_id: property ID that we want the type of
:return: format string describing the type
"""
try:
response = yield self.send_command(to, command_id=GET_PROPERTY_TYPE, params=["property_id"],
data=[requested_property_id])
except Exception as e:
logger.error("[PCOM] Unable to find property type for property {0} in item {1} because of exception: "
"{2}".format(requested_property_id, to, e))
defer.returnValue(None)
r_val = '' if len(response.data) == 0 else response.data[0]
defer.returnValue(r_val)
def start(cls, net, factory, bitcoind, peer_ports, merged_urls):
self = cls()
self.n = node.Node(factory, bitcoind, [], [], net)
yield self.n.start()
self.n.p2p_node = node.P2PNode(self.n, port=0, max_incoming_conns=1000000, addr_store={}, connect_addrs=[('127.0.0.1', peer_port) for peer_port in peer_ports])
self.n.p2p_node.start()
wb = work.WorkerBridge(node=self.n, my_pubkey_hash=random.randrange(2**160), donation_percentage=random.uniform(0, 10), merged_urls=merged_urls, worker_fee=3, args=math.Object(donation_percentage=random.uniform(0, 10), address='foo', worker_fee=3, timeaddresses=1000), pubkeys=main.keypool(), bitcoind=bitcoind)
self.wb = wb
web_root = resource.Resource()
worker_interface.WorkerInterface(wb).attach_to(web_root)
self.web_port = reactor.listenTCP(0, server.Site(web_root))
defer.returnValue(self)
def get_height_rel_highest_func(bitcoind, factory, best_block_func, net):
if '\ngetblock ' in (yield deferral.retry()(bitcoind.rpc_help)()):
@deferral.DeferredCacher
@defer.inlineCallbacks
def height_cacher(block_hash):
try:
x = yield bitcoind.rpc_getblock('%x' % (block_hash,))
except jsonrpc.Error_for_code(-5): # Block not found
if not p2pool.DEBUG:
raise deferral.RetrySilentlyException()
else:
raise
defer.returnValue(x['blockcount'] if 'blockcount' in x else x['height'])
best_height_cached = variable.Variable((yield deferral.retry()(height_cacher)(best_block_func())))
def get_height_rel_highest(block_hash):
this_height = height_cacher.call_now(block_hash, 0)
best_height = height_cacher.call_now(best_block_func(), 0)
best_height_cached.set(max(best_height_cached.value, this_height, best_height))
return this_height - best_height_cached.value
else:
get_height_rel_highest = HeightTracker(best_block_func, factory, 5*net.SHARE_PERIOD*net.CHAIN_LENGTH/net.PARENT.BLOCK_PERIOD).get_height_rel_highest
defer.returnValue(get_height_rel_highest)
def start(cls, net, factory, bitcoind, peer_ports, merged_urls):
self = cls()
self.n = node.Node(factory, bitcoind, [], [], net)
yield self.n.start()
self.n.p2p_node = node.P2PNode(self.n, port=0, max_incoming_conns=1000000, addr_store={}, connect_addrs=[('127.0.0.1', peer_port) for peer_port in peer_ports])
self.n.p2p_node.start()
wb = work.WorkerBridge(node=self.n, my_pubkey_hash=random.randrange(2**160), donation_percentage=random.uniform(0, 10), merged_urls=merged_urls, worker_fee=3)
self.wb = wb
web_root = resource.Resource()
worker_interface.WorkerInterface(wb).attach_to(web_root)
self.web_port = reactor.listenTCP(0, server.Site(web_root))
defer.returnValue(self)
def get_height_rel_highest_func(bitcoind, factory, best_block_func, net):
if '\ngetblock ' in (yield deferral.retry()(bitcoind.rpc_help)()):
@deferral.DeferredCacher
@defer.inlineCallbacks
def height_cacher(block_hash):
try:
x = yield bitcoind.rpc_getblock('%x' % (block_hash,))
except jsonrpc.Error_for_code(-5): # Block not found
if not p2pool.DEBUG:
raise deferral.RetrySilentlyException()
else:
raise
defer.returnValue(x['blockcount'] if 'blockcount' in x else x['height'])
best_height_cached = variable.Variable((yield deferral.retry()(height_cacher)(best_block_func())))
def get_height_rel_highest(block_hash):
this_height = height_cacher.call_now(block_hash, 0)
best_height = height_cacher.call_now(best_block_func(), 0)
best_height_cached.set(max(best_height_cached.value, this_height, best_height))
return this_height - best_height_cached.value
else:
get_height_rel_highest = HeightTracker(best_block_func, factory, 5*net.SHARE_PERIOD*net.CHAIN_LENGTH/net.PARENT.BLOCK_PERIOD).get_height_rel_highest
defer.returnValue(get_height_rel_highest)
def deferred_render_PUT(self, request):
"""
Update values of a set of tags (values and tags are given in a JSON
payload) on objects that match a query (query is given in the URI).
@param request: The incoming C{twisted.web.server.Request} request.
@return: A L{Deferred} which will fire with C{None} when the
request has completed. The deferred may errback for a variety of
reasons, for example an invalid query, the mention of a
non-existent tag or a tag that the caller does not have CREATE
permission for.
"""
usage = registry.findUsage(httpValueCategoryName, 'PUT',
ValuesResource)
requestObject = ValuesQuerySchema.createFromRequest(request, usage)
yield self.facadeClient.updateValuesForQueries(
self.session, requestObject)
request.setResponseCode(usage.successCode)
defer.returnValue(None)
def deferred_render_DELETE(self, request):
"""
Handle a DELETE request for /values with a query and a list of
wanted tags.
@param request: The incoming C{twisted.web.server.Request} request.
@return: A C{Deferred} which will fire when the request has
completed. The deferred may errback for a variety of reasons,
for example an invalid query, the mention of a non-existent tag
or a tag that the caller does not have DELETE permission for.
"""
usage = registry.findUsage(httpValueCategoryName, 'DELETE',
ValuesResource)
registry.checkRequest(usage, request)
query = request.args[queryArg][0]
tags = request.args[tagArg]
if tags == ['*']:
tags = None
yield self.facadeClient.deleteValuesForQuery(self.session, query, tags)
request.setResponseCode(usage.successCode)
defer.returnValue(None)
# ------------------------------ Values GET -----------------------------
def deferred_render_GET(self, request):
usage = registry.findUsage(httpObjectCategoryName, 'GET',
ObjectsResource)
registry.checkRequest(usage, request)
responseType = usage.getResponsePayloadTypeFromAcceptHeader(request)
query = request.args['query'][0]
results = yield self.facadeClient.resolveQuery(self.session, query)
responseDict = {'ids': list(results)}
registry.checkResponse(responseType, responseDict, usage, request)
body = payloads.buildPayload(responseType, responseDict)
request.setHeader('Content-length', str(len(body)))
request.setHeader('Content-type', responseType)
request.setResponseCode(usage.successCode)
defer.returnValue(body)
# ------------------------------ Objects POST -----------------------------
def deferred_render_DELETE(self, request):
"""
Delete a tag from an object. Return a Deferred that fires with None
once the facade has done the deletion.
The following code, apart from the yield self._setObjectId(), is
taken verbatim from deferred_render_DELETE in objects.py. So if
you change this code, you'll likely need to change that, and vice
versa.
@param request: The HTTP request.
@return: A C{Deferred} that fires with C{None} once the request has
completed.
"""
usage = registry.findUsage(httpAboutCategoryName, 'DELETE',
AboutTagInstanceResource)
registry.checkRequest(usage, request)
yield self._setObjectId()
yield self.facadeClient.deleteTagInstance(
self.session, self.path, self.objectId)
request.setResponseCode(usage.successCode)
defer.returnValue(None)
def requestAvatarId(self, credentials):
"""
Return the avatar id of the avatar which can be accessed using the
given credentials.
credentials will be an object with username and password tags. We
need to raise an error to indicate failure or return a username to
indicate success. requestAvatar will then be called with the
avatar id we returned.
"""
try:
session = yield self.facadeClient.authenticateUserWithPassword(
credentials.username, credentials.password)
except (TPasswordIncorrect, TNoSuchUser):
unauthorizedLogin = error.UnauthorizedLogin('Invalid credentials')
log.msg('Bad credentials: %r:%r' %
(credentials.username, '<sanitized>'))
raise unauthorizedLogin
except Exception, e:
log.msg('requestAvatarId exception authenticating %r/%r.' %
(credentials.username, '<sanitized>'))
log.err(e)
raise
else:
defer.returnValue(session)
def requestAvatarId(self, credentials):
"""
Return the avatar id of the avatar which can be accessed using the
given OAuth credentials.
@param credentials: A L{IOAuthCredentials} that contains OAuth
credentials.
@raise UnauthorizedLogin: if the OAuth credentials don't match the
L{User}'s.
"""
try:
session = yield self.facadeClient.authenticateUserWithOAuth(
credentials)
except TPasswordIncorrect:
logging.info('Bad OAuth credentials: %r:%r' %
(credentials.consumerKey, '<sanitized>'))
raise error.UnauthorizedLogin('Invalid credentials')
except Exception:
logging.info('requestAvatarId exception authenticating %r/%r.' %
(credentials.consumerKey, '<sanitized>'))
raise
else:
defer.returnValue(session)
def requestAvatarId(self, credentials):
"""
Return the avatar ID of the avatar which can be accessed using the
given OAuth credentials.
@param credentials: A L{IOAuth2Credentials} that contains OAuth
credentials.
@raise UnauthorizedLogin: Raised if the OAuth credentials don't match
the L{User}'s.
"""
try:
session = yield self.facadeClient.authenticateUserWithOAuth2(
credentials)
except TPasswordIncorrect:
logging.info('Bad OAuth credentials: %r:%r' %
(credentials.consumerKey, '<sanitized>'))
raise error.UnauthorizedLogin('Invalid credentials')
except Exception:
logging.info('requestAvatarId exception authenticating %r/%r.' %
(credentials.consumerKey, '<sanitized>'))
raise
else:
defer.returnValue(session)
def getPermissions(self, path, action,
requesterUsername=None, requesterPassword=None):
headers = {
'accept': 'application/json',
}
self.addBasicAuthHeader(headers, requesterUsername, requesterPassword)
d = http.getPage(
'%s/%s/%s?action=%s' % (self.endpoint,
defaults.httpPermissionCategoryName,
urllib.quote(path.encode('utf-8')),
urllib.quote_plus(action)),
headers=headers, method='GET')
d.addCallback(self.checkStatus, txHttp.OK)
d.addCallback(self.checkPayloadHas,
dict.fromkeys(['policy', 'exceptions']))
result = yield d
payload = result[2]
dictionary = json.loads(payload)
defer.returnValue((dictionary['policy'], dictionary['exceptions']))
def getPolicy(self, username, category, action,
requesterUsername=None, requesterPassword=None):
headers = {
'accept': 'application/json',
}
self.addBasicAuthHeader(headers, requesterUsername, requesterPassword)
path = '%s/%s/%s/%s/%s' % (
self.endpoint,
defaults.httpPolicyCategoryName,
urllib.quote(username.encode('utf-8')),
urllib.quote(category.encode('utf-8')),
urllib.quote(action.encode('utf-8')))
d = http.getPage(path, headers=headers, method='GET')
d.addCallback(self.checkStatus, txHttp.OK)
d.addCallback(self.checkPayloadHas, dict.fromkeys(['policy',
'exceptions']))
result = yield d
payload = result[2]
dictionary = json.loads(payload)
defer.returnValue((dictionary['policy'], dictionary['exceptions']))
def query(self, query, requesterUsername=None, requesterPassword=None):
headers = {
'accept': 'application/json',
}
self.addBasicAuthHeader(headers, requesterUsername, requesterPassword)
d = http.getPage(
'%s/%s?query=%s' % (self.endpoint,
defaults.httpObjectCategoryName,
urllib.quote(query.encode('utf-8'))),
headers=headers, method='GET')
d.addCallback(self.checkStatus, txHttp.OK)
d.addCallback(self.checkPayloadHas, dict.fromkeys(['ids']))
result = yield d
payload = result[2]
dictionary = json.loads(payload)
defer.returnValue(dictionary['ids'])
def start(cls, net, factory, bitcoind, peer_ports, merged_urls):
self = cls()
self.n = node.Node(factory, bitcoind, [], [], net)
yield self.n.start()
self.n.p2p_node = node.P2PNode(self.n, port=0, max_incoming_conns=1000000, addr_store={}, connect_addrs=[('127.0.0.1', peer_port) for peer_port in peer_ports])
self.n.p2p_node.start()
wb = work.WorkerBridge(node=self.n, my_pubkey_hash=random.randrange(2**160), donation_percentage=random.uniform(0, 10), merged_urls=merged_urls, worker_fee=3)
self.wb = wb
web_root = resource.Resource()
worker_interface.WorkerInterface(wb).attach_to(web_root)
self.web_port = reactor.listenTCP(0, server.Site(web_root))
defer.returnValue(self)
def get_height_rel_highest_func(bitcoind, factory, best_block_func, net):
if '\ngetblock ' in (yield deferral.retry()(bitcoind.rpc_help)()):
@deferral.DeferredCacher
@defer.inlineCallbacks
def height_cacher(block_hash):
try:
x = yield bitcoind.rpc_getblock('%x' % (block_hash,))
except jsonrpc.Error_for_code(-5): # Block not found
if not p2pool.DEBUG:
raise deferral.RetrySilentlyException()
else:
raise
defer.returnValue(x['blockcount'] if 'blockcount' in x else x['height'])
best_height_cached = variable.Variable((yield deferral.retry()(height_cacher)(best_block_func())))
def get_height_rel_highest(block_hash):
this_height = height_cacher.call_now(block_hash, 0)
best_height = height_cacher.call_now(best_block_func(), 0)
best_height_cached.set(max(best_height_cached.value, this_height, best_height))
return this_height - best_height_cached.value
else:
get_height_rel_highest = HeightTracker(best_block_func, factory, 5*net.SHARE_PERIOD*net.CHAIN_LENGTH/net.PARENT.BLOCK_PERIOD).get_height_rel_highest
defer.returnValue(get_height_rel_highest)