本文整理汇总了Python中pyndn.Face.shutdown方法的典型用法代码示例。如果您正苦于以下问题:Python Face.shutdown方法的具体用法?Python Face.shutdown怎么用?Python Face.shutdown使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.Face
的用法示例。
在下文中一共展示了Face.shutdown方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
# Silence the warning from Interest wire encode.
Interest.setDefaultCanBePrefix(True)
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
counter = Counter()
if sys.version_info[0] <= 2:
word = raw_input("Enter a word to echo: ")
else:
word = input("Enter a word to echo: ")
name = Name("/testecho")
name.append(word)
dump("Express name ", name.toUri())
face.expressInterest(name, counter.onData, counter.onTimeout)
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例2: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage), None)
keyChain.setFace(face)
# Initialize the storage.
keyName = Name("/testname/DSK-123")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
echo = Echo(keyChain, certificateName)
prefix = Name("/testecho")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while echo._responseCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例3: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
face = Face("localhost")
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage), None)
keyChain.setFace(face)
# Initialize the storage.
keyName = Name("/testname/DSK-reposerver")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_PUBLIC_KEY_DER))
privateKeyStorage.setKeyPairForKeyName(
keyName, DEFAULT_PUBLIC_KEY_DER, DEFAULT_PRIVATE_KEY_DER)
echo = RepoServer(keyChain, certificateName)
prefix = Name("/ndn/ucla.edu/bms")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while True:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例4: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
dataPrefix = "/home/test1/data"
repoDataPrefix = "/home/test1/data"
# Set up repo-ng, register prefix for repo-ng's fetch prefix
# Per configuration file in /usr/local/etc/ndn/repo-ng.conf
# memCache is not used for now; repo is hoping that the piece of data in question is still being held at nfd
#memCache = MemoryContentCache(face, 100000)
#memCache.registerPrefix(Name(repoDataPrefix), onRegisterFailed, onDataNotFound)
counter = Counter(face, repoDataPrefix)
interest = Interest(Name(dataPrefix))
interest.setChildSelector(1)
interest.setInterestLifetimeMilliseconds(defaultInterestLifetime)
face.expressInterest(interest, counter.onData, counter.onTimeout)
while True:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(1)
face.shutdown()
示例5: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
if len(sys.argv) < 2:
print("argv error: please input turnOn, turnOff or status")
exit(1)
else:
cmd = sys.argv[1]
loop = asyncio.get_event_loop()
#face = ThreadsafeFace(loop, "localhost")
face = Face("localhost")
# Counter will stop the ioService after callbacks for all expressInterest.
counter = Counter(loop, 3)
seed = HMACKey(0,0,"seed","seedName")
# Try to fetch anything.
name1 = Name("/home/sensor/LED/0/"+cmd+"/0/0")
commandTokenName = '/home/sensor/LED/0/'+cmd+'/token/0'
commandTokenKey = hmac.new(seed.getKey(), commandTokenName, sha256).digest()
accessTokenName = '/home/sensor/LED/0/'+cmd+'/token/0/user/Tom/token/0'
accessTokenKey = hmac.new(commandTokenKey, accessTokenName, sha256).digest()
accessToken = HMACKey(0,0,accessTokenKey,accessTokenName)
dump("seed.getKey() :",seed.getKey())
dump("commandTokenName :",commandTokenName)
dump("commandTokenKey :",base64.b64encode(commandTokenKey))
dump("accessTokenName :",accessTokenName)
dump("accessTokenKey :",base64.b64encode(accessTokenKey))
interest = Interest(name1)
interest.setInterestLifetimeMilliseconds(3000)
a = AccessControlManager()
a.signInterestWithHMACKey(interest,accessToken)
dump("Express name ", interest.toUri())
face.expressInterest(interest, counter.onData, counter.onTimeout)
"""
name2 = Name("/home/sensor/LED/T0829374723/turnOff")
dump("Express name ", name2.toUri())
face.expressInterest(name2, counter.onData, counter.onTimeout)
"""
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(2)
face.shutdown()
示例6: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
"""
Call requestInsert and register a prefix so that ProduceSegments will answer
interests from the repo to send the data packets. This assumes that repo-ng
is already running (e.g. `sudo ndn-repo-ng`).
"""
repoCommandPrefix = Name("/example/repo/1")
repoDataPrefix = Name("/example/data/1")
nowMilliseconds = int(time.time() * 1000.0)
fetchPrefix = Name(repoDataPrefix).append("testinsert").appendVersion(nowMilliseconds)
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
# Use the system default key chain and certificate name to sign commands.
keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
# Register the prefix and send the repo insert command at the same time.
startBlockId = 0
endBlockId = 1
enabled = [True]
def onFinished():
dump("All data was inserted.")
enabled[0] = False
produceSegments = ProduceSegments(
keyChain, keyChain.getDefaultCertificateName(), startBlockId, endBlockId,
onFinished)
dump("Register prefix", fetchPrefix.toUri())
def onRegisterFailed(prefix):
dump("Register failed for prefix", prefix.toUri())
enabled[0] = False
face.registerPrefix(
fetchPrefix, produceSegments.onInterest, onRegisterFailed)
def onInsertStarted():
dump("Insert started for", fetchPrefix.toUri())
def onFailed():
enabled[0] = False
requestInsert(
face, repoCommandPrefix, fetchPrefix, onInsertStarted, onFailed,
startBlockId, endBlockId)
# Run until all the data is sent.
while enabled[0]:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例7: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
"""
Call startRepoWatch and register a prefix so that SendSegments will answer
interests from the repo to send data packets for the watched prefix. When
all the data is sent (or an error), call stopRepoWatch. This assumes that
repo-ng is already running (e.g. `sudo ndn-repo-ng`).
"""
repoCommandPrefix = Name("/example/repo/1")
repoDataPrefix = Name("/example/data/1")
nowMilliseconds = int(time.time() * 1000.0)
watchPrefix = Name(repoDataPrefix).append("testwatch").appendVersion(
nowMilliseconds)
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
# Use the system default key chain and certificate name to sign commands.
keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
# Register the prefix and start the repo watch at the same time.
enabled = [True]
def onFinishedSending():
stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
sendSegments = SendSegments(
keyChain, keyChain.getDefaultCertificateName(), onFinishedSending)
def onRegisterFailed(prefix):
dump("Register failed for prefix", prefix.toUri())
enabled[0] = False
dump("Register prefix", watchPrefix.toUri())
face.registerPrefix(watchPrefix, sendSegments.onInterest, onRegisterFailed)
def onRepoWatchStarted():
dump("Watch started for", watchPrefix.toUri())
def onStartFailed():
dump("startRepoWatch failed.")
stopRepoWatchAndQuit(face, repoCommandPrefix, watchPrefix, enabled)
startRepoWatch(
face, repoCommandPrefix, watchPrefix, onRepoWatchStarted, onStartFailed)
# Run until someone sets enabled[0] = False.
enabled[0] = True
while enabled[0]:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例8: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
face = Face()
# Use the system default key chain and certificate name to sign commands.
keyChain = KeyChain()
certificateName = keyChain.getDefaultCertificateName()
face.setCommandSigningInfo(keyChain, certificateName)
test = DiscoveryTest(face, keyChain, certificateName)
test.start()
while True:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例9: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
face = Face("localhost")
counter = Counter()
ignored, name = argv
name = "/ndn/ucla.edu/bms/" + name
name1 = Name(name)
dump("Express name ", name1.toUri())
face.expressInterest(name1, counter.onData, counter.onTimeout)
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例10: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
seg = 0
if len(sys.argv) < 3:
print("argv error: please input capture or capture with #seg")
exit(1)
elif len(sys.argv) == 2:
cmd = sys.argv[1]
else:
cmd = sys.argv[1]
seg = sys.argv[2]
loop = asyncio.get_event_loop()
#face = ThreadsafeFace(loop, "localhost")
face = Face("localhost")
# Counter will stop the ioService after callbacks for all expressInterest.
counter = Counter(loop, 3)
seed = HMACKey(0,0,"seed","seedName")
# Try to fetch anything.
import time
r = time.time()
name1 = Name("/home/security/camera/0/"+cmd)
name1.appendTimestamp(int(r))
name1.appendSegment(int(seg))
interest = Interest(name1)
interest.setInterestLifetimeMilliseconds(3000)
dump("Express name ", interest.toUri())
face.expressInterest(interest, counter.onData, counter.onTimeout)
"""
name2 = Name("/home/sensor/LED/T0829374723/turnOff")
dump("Express name ", name2.toUri())
face.expressInterest(name2, counter.onData, counter.onTimeout)
"""
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(2)
face.shutdown()
示例11: main
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def main():
# The default Face will connect using a Unix socket, or to "localhost".
face = Face()
# Use the system default key chain and certificate name to sign commands.
keyChain = KeyChain()
face.setCommandSigningInfo(keyChain, keyChain.getDefaultCertificateName())
# Also use the default certificate name to sign data packets.
echo = Echo(keyChain, keyChain.getDefaultCertificateName())
prefix = Name("/testecho")
dump("Register prefix", prefix.toUri())
face.registerPrefix(prefix, echo.onInterest, echo.onRegisterFailed)
while echo._responseCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(0.01)
face.shutdown()
示例12: deviceListRequest
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
def deviceListRequest():
loop = asyncio.get_event_loop()
#face = ThreadsafeFace(loop, "localhost")
face = Face("localhost")
# Counter will stop the ioService after callbacks for all expressInterest.
counter = Counter(loop, 3)
while True:
username = raw_input('Login username: ')
if not len(username)>0:
print("Username can't be blank")
continue
else:
break
while True:
password = raw_input("Login password: ")
if not len(password)>0:
print("Username can't be blank")
continue
else:
break
userHMACKey = HMACKey(0,0,password,"userHMACKey")
interestName = Name("/home/controller/deviceList/user/"+username)
interest = Interest(interestName)
a = AccessControlManager()
a.signInterestWithHMACKey(interest,userHMACKey)
dump("Express interst :",interest.toUri())
face.expressInterest(interest,counter.onData,counter.onTimeout)
while counter._callbackCount < 1:
face.processEvents()
# We need to sleep for a few milliseconds so we don't use 100% of the CPU.
time.sleep(2)
face.shutdown()
示例13: LightController
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
class LightController():
shouldSign = False
COLORS_PER_LIGHT = 3
STRAND_SIZE = 50
def __init__(self, nStrands=1, myIP="192.168.1.1", lightIP="192.168.1.50", prefix="/testlight"):
self.log = logging.getLogger("LightController")
self.log.setLevel(logging.DEBUG)
sh = logging.StreamHandler()
sh.setLevel(logging.WARNING)
self.log.addHandler(sh)
fh = logging.FileHandler("LightController.log")
fh.setLevel(logging.INFO)
self.log.addHandler(fh)
self.payloadBuffer = [[0]*self.STRAND_SIZE*self.COLORS_PER_LIGHT for n in range(nStrands)]
self.kinetsender = KinetSender(myIP, lightIP, nStrands, self.STRAND_SIZE*self.COLORS_PER_LIGHT)
self.registerFailed = False
self.done = False
self.prefix = Name(prefix)
self.keychain = KeyChain()
self.certificateName = self.keychain.getDefaultCertificateName()
# XXX: we should get a thread for this or something!
def start(self):
self.face = Face()
self.face.setCommandSigningInfo(self.keychain, self.certificateName)
self.face.registerPrefix(self.prefix, self.onLightingCommand, self.onRegisterFailed)
while self.face is not None:
self.face.processEvents()
if self.registerFailed:
self.stop()
break
#time.sleep(0.001)
def stop(self):
self.kinetsender.stop = True
self.kinetsender.complete.wait()
self.face.shutdown()
self.face = None
def signData(self, data):
if LightController.shouldSign:
self.keychain.sign(data, self.certificateName)
else:
data.setSignature(Sha256WithRsaSignature())
def setPayloadColor(self, strand, color):
# will expand this to allow the repeats, etc
self.payloadBuffer[strand] = [int(color.r)&0xff, int(color.g)&0xff, int(color.b)&0xff]*self.STRAND_SIZE
def onLightingCommand(self, prefix, interest, transport, prefixId):
interestName = Name(interest.getName())
#d = Data(interest.getName().getPrefix(prefix.size()+1))
d = Data(interest.getName())
# get the command parameters from the name
try:
commandComponent = interest.getName().get(prefix.size())
commandParams = interest.getName().get(prefix.size()+1)
lightingCommand = LightCommandMessage()
ProtobufTlv.decode(lightingCommand, commandParams.getValue())
self.log.info("Command: " + commandComponent.toEscapedString())
requestedColor = lightingCommand.command.pattern.colors[0]
colorStr = str((requestedColor.r, requestedColor.g, requestedColor.b))
self.log.info("Requested color: " + colorStr)
self.setPayloadColor(0, requestedColor)
self.sendLightPayload(1)
d.setContent("Gotcha: " + colorStr+ "\n")
except Exception as e:
print e
d.setContent("Bad command\n")
finally:
d.getMetaInfo().setFinalBlockID(0)
self.signData(d)
encodedData = d.wireEncode()
transport.send(encodedData.toBuffer())
def onRegisterFailed(self, prefix):
self.log.error("Could not register " + prefix.toUri())
print "Register failed!"
self.registerFailed = True
def sendLightPayload(self, port):
self.kinetsender.setPayload(port, self.payloadBuffer[port-1])
示例14: Face
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
else:
timing.append(done-start)
if __name__ == '__main__':
face = Face()
if shouldSign:
face.setCommandSigningInfo(keychain, certName)
input = None
N = 0
try:
while True:
byteVal = (N)&0xff
color = (0,0,0)
selector = (N/256)%0x3
if selector == 1:
color = (byteVal, 0, 0)
elif selector == 2:
color = (0, byteVal, 0)
elif selector == 0:
color = (0, 0, byteVal)
interest = createCommandInterest(color=color)
waitForResponse(face, interest, None)
N += 10
except KeyboardInterrupt:
pass
face.shutdown()
print "Response time: {:3.2f}/{:3.2f}/{:3.2f}s min/mean/max".format(min(timing), mean(timing), max(timing))
print str(timeouts) + " timeouts"
示例15: TestFaceInterestMethods
# 需要导入模块: from pyndn import Face [as 别名]
# 或者: from pyndn.Face import shutdown [as 别名]
class TestFaceInterestMethods(ut.TestCase):
def setUp(self):
self.face = Face("localhost")
def tearDown(self):
self.face.shutdown()
def run_express_name_test(self, interestName, timeout=12):
# returns the dataCallback and timeoutCallback mock objects so we can test timeout behavior
# as well as a bool for if we timed out without timeoutCallback being called
name = Name(interestName)
dataCallback = Mock()
timeoutCallback = Mock()
self.face.expressInterest(name, dataCallback, timeoutCallback)
while True:
self.face.processEvents()
time.sleep(0.01)
if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
break
return dataCallback, timeoutCallback
def test_any_interest(self):
uri = "/"
(dataCallback, timeoutCallback) = self.run_express_name_test(uri)
self.assertTrue(timeoutCallback.call_count == 0 , 'Timeout on expressed interest')
# check that the callback was correct
self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))
onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])
#just check that the interest was returned correctly?
callbackInterest = onDataArgs[0]
self.assertTrue(callbackInterest.getName() == (Name(uri)), 'Interest returned on callback had different name')
# TODO: Replace this with a test that connects to a Face on localhost
#def test_specific_interest(self):
# uri = "/ndn/edu/ucla/remap/ndn-js-test/howdy.txt/%FD%052%A1%DF%5E%A4"
# (dataCallback, timeoutCallback) = self.run_express_name_test(uri)
# self.assertTrue(timeoutCallback.call_count == 0, 'Unexpected timeout on expressed interest')
#
# # check that the callback was correct
# self.assertEqual(dataCallback.call_count, 1, 'Expected 1 onData callback, got '+str(dataCallback.call_count))
# onDataArgs = dataCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])
# #just check that the interest was returned correctly?
# callbackInterest = onDataArgs[0]
# self.assertTrue(callbackInterest.getName() == Name(uri), 'Interest returned on callback had different name')
def test_timeout(self):
uri = "/test/timeout"
(dataCallback, timeoutCallback) = self.run_express_name_test(uri)
# we're expecting a timeout callback, and only 1
self.assertTrue(dataCallback.call_count == 0, 'Data callback called for invalid interest')
self.assertTrue(timeoutCallback.call_count == 1, 'Expected 1 timeout call, got ' + str(timeoutCallback.call_count))
#check that the interest was returned correctly
onTimeoutArgs = timeoutCallback.call_args[0] # the args are returned as ([ordered arguments], [keyword arguments])
#just check that the interest was returned correctly?
callbackInterest = onTimeoutArgs[0]
self.assertTrue(callbackInterest.getName() == (Name(uri)), 'Interest returned on callback had different name')
def test_remove_pending(self):
name = Name("/ndn/edu/ucla/remap/")
dataCallback = Mock()
timeoutCallback = Mock()
interestID = self.face.expressInterest(name, dataCallback, timeoutCallback)
self.face.removePendingInterest(interestID)
timeout = 10000
startTime = getNowMilliseconds()
while True:
self.face.processEvents()
time.sleep(0.01)
if getNowMilliseconds() - startTime >= timeout:
break
if (dataCallback.call_count > 0 or timeoutCallback.call_count > 0):
break
self.assertEqual(dataCallback.call_count, 0, 'Should not have called data callback after interest was removed')
self.assertEqual(timeoutCallback.call_count, 0, 'Should not have called timeout callback after interest was removed')
def test_max_ndn_packet_size(self):
# Construct an interest whose encoding is one byte larger than getMaxNdnPacketSize.
targetSize = Face.getMaxNdnPacketSize() + 1
# Start with an interest which is almost the right size.
interest = Interest()
interest.getName().append(bytearray(targetSize))
initialSize = interest.wireEncode().size()
# Now replace the component with the desired size which trims off the extra encoding.
interest.setName(
(Name().append(bytearray(targetSize - (initialSize - targetSize)))))
#.........这里部分代码省略.........