本文整理汇总了Python中pyndn.Name.getSubName方法的典型用法代码示例。如果您正苦于以下问题:Python Name.getSubName方法的具体用法?Python Name.getSubName怎么用?Python Name.getSubName使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pyndn.Name
的用法示例。
在下文中一共展示了Name.getSubName方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_subname
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def test_subname(self):
name = Name("/edu/cmu/andrew/user/3498478")
subName1 = name.getSubName(0)
self.assertTrue(subName1.equals(name), 'Subname from first component does not match original name')
subName2 = name.getSubName(3)
self.assertEqual(subName2.toUri(), "/user/3498478")
subName3 = name.getSubName(1,3)
self.assertEqual(subName3.toUri(), "/cmu/andrew/user")
subName4 = name.getSubName(0,100)
self.assertTrue(name.equals(subName4), 'Subname with more components than original should stop at end of original name')
subName5 = name.getSubName(7,9)
self.assertTrue(Name().equals(subName5), 'Subname beginning after end of name should be empty')
示例2: benchmarkDecodeDataSeconds
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def benchmarkDecodeDataSeconds(nIterations, useCrypto, encoding):
"""
Loop to decode a data packet nIterations times.
:param int nIterations: The number of iterations.
:param bool useCrypto: If true, verify the signature. If false, don't
verify.
:param Blob encoding: The wire encoding to decode.
"""
# Initialize the private key storage in case useCrypto is true.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
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))
start = getNowSeconds()
for i in range(nIterations):
data = Data()
data.wireDecode(encoding)
if useCrypto:
keyChain.verifyData(data, onVerified, onVerifyFailed)
finish = getNowSeconds()
return finish - start
示例3: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [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()
示例4: wrap_content
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def wrap_content(self, name, content, key=None, key_locator=None):
"""
@param name - name of the data
@param content - data to be wrapped
@param key - key used to sign the data
@return the content object created
wraps the given name and content into a content object
"""
co = Data(Name(name))
co.setContent(content)
co.getMetaInfo().setFreshnessPeriod(5000)
co.getMetaInfo().setFinalBlockID(Name("/%00%09")[0])
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
identityManager = IdentityManager(identityStorage, privateKeyStorage)
keyChain = KeyChain(identityManager, None)
# Initialize the storage.
keyName = Name("/ndn/bms/DSK-default")
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)
keyChain.sign(co, certificateName)
_data = co.wireEncode()
return _data.toRawStr()
示例5: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [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()
示例6: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def main():
interest = Interest()
interest.wireDecode(TlvInterest)
dump("Interest:")
dumpInterest(interest)
# Set the name again to clear the cached encoding so we encode again.
interest.setName(interest.getName())
encoding = interest.wireEncode()
dump("")
dump("Re-encoded interest", encoding.toHex())
reDecodedInterest = Interest()
reDecodedInterest.wireDecode(encoding)
dump("Re-decoded Interest:")
dumpInterest(reDecodedInterest)
freshInterest = Interest(Name("/ndn/abc"))
freshInterest.setMustBeFresh(False)
dump(freshInterest.toUri())
freshInterest.setMinSuffixComponents(4)
freshInterest.setMaxSuffixComponents(6)
freshInterest.getKeyLocator().setType(KeyLocatorType.KEY_LOCATOR_DIGEST)
freshInterest.getKeyLocator().setKeyData(bytearray(
[0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F,
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F]))
freshInterest.getExclude().appendComponent(Name("abc")[0]).appendAny()
freshInterest.setInterestLifetimeMilliseconds(30000)
freshInterest.setChildSelector(1)
freshInterest.setMustBeFresh(True);
freshInterest.setScope(2)
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
# 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)
# Make a Face just so that we can sign the interest.
face = Face("localhost")
face.setCommandSigningInfo(keyChain, certificateName)
face.makeCommandInterest(freshInterest)
reDecodedFreshInterest = Interest()
reDecodedFreshInterest.wireDecode(freshInterest.wireEncode())
dump("")
dump("Re-decoded fresh Interest:")
dumpInterest(reDecodedFreshInterest)
keyChain.verifyInterest(
reDecodedFreshInterest, makeOnVerified("Freshly-signed Interest"),
makeOnVerifyFailed("Freshly-signed Interest"))
示例7: __init__
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def __init__(self):
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keyChain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage),
SelfVerifyPolicyManager(self.identityStorage))
keyName = Name("/testname/DSK-123")
self.defaultCertName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName[-1]).append("ID-CERT").append("0")
self.identityStorage.addKey(keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER))
self.privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER, DEFAULT_RSA_PRIVATE_KEY_DER)
示例8: main
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def main():
data = Data()
data.wireDecode(TlvData)
dump("Decoded Data:")
dumpData(data)
# Set the content again to clear the cached encoding so we encode again.
data.setContent(data.getContent())
encoding = data.wireEncode()
reDecodedData = Data()
reDecodedData.wireDecode(encoding)
dump("")
dump("Re-decoded Data:")
dumpData(reDecodedData)
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
# 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)
keyChain.verifyData(reDecodedData, makeOnVerified("Re-decoded Data"),
makeOnVerifyFailed("Re-decoded Data"))
freshData = Data(Name("/ndn/abc"))
freshData.setContent("SUCCESS!")
freshData.getMetaInfo().setFreshnessPeriod(5000)
freshData.getMetaInfo().setFinalBlockId(Name("/%00%09")[0])
keyChain.sign(freshData, certificateName)
dump("")
dump("Freshly-signed Data:")
dumpData(freshData)
keyChain.verifyData(freshData, makeOnVerified("Freshly-signed Data"),
makeOnVerifyFailed("Freshly-signed Data"))
示例9: test_subname
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def test_subname(self):
name = Name("/edu/cmu/andrew/user/3498478")
subName1 = name.getSubName(0)
self.assertEqual(subName1, name, 'Subname from first component does not match original name')
subName2 = name.getSubName(3)
self.assertEqual(subName2, Name("/user/3498478"))
subName3 = name.getSubName(1,3)
self.assertEqual(subName3, Name("/cmu/andrew/user"))
subName4 = name.getSubName(0,100)
self.assertEqual(name, subName4, 'Subname with more components than original should stop at end of original name')
subName5 = name.getSubName(7,2)
self.assertEqual(Name(), subName5, 'Subname beginning after end of name should be empty')
subName6 = name.getSubName(-1,7)
self.assertEqual(subName6, Name("/3498478"), 'Negative subname with more components than original should stop at end of original name')
subName7 = name.getSubName(-5,5)
self.assertEqual(subName7, name, 'Subname from (-length) should match original name')
示例10: createKeyChain
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def createKeyChain():
"""
Create an in-memory KeyChain with default keys.
:return: A tuple with the new KeyChain and certificate name.
:rtype: (KeyChain,Name)
"""
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(
IdentityManager(identityStorage, privateKeyStorage),
NoVerifyPolicyManager())
# Initialize the storage.
keyName = Name("/testname/DSK-123")
certificateName = keyName.getSubName(0, keyName.size() - 1).append(
"KEY").append(keyName.get(-1)).append("ID-CERT").append("0")
identityStorage.addKey(
keyName, KeyType.RSA, Blob(DEFAULT_RSA_PUBLIC_KEY_DER, False))
privateKeyStorage.setKeyPairForKeyName(
keyName, KeyType.RSA, DEFAULT_RSA_PUBLIC_KEY_DER,
DEFAULT_RSA_PRIVATE_KEY_DER)
return keyChain, certificateName
示例11: benchmarkEncodeDataSeconds
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
def benchmarkEncodeDataSeconds(nIterations, useComplex, useCrypto):
"""
Loop to encode a data packet nIterations times.
:param int nIterations: The number of iterations.
:param bool useComplex: If true, use a large name, large content and all
fields. If false, use a small name, small content and only required
fields.
:param bool useCrypto: If true, sign the data packet. If false, use a blank
signature.
:return: A tuple (duration, encoding) where duration is the number of
seconds for all iterations and encoding is the wire encoding.
:rtype: (float, Blob)
"""
if useComplex:
# Use a large name and content.
name = Name(
"/ndn/ucla.edu/apps/lwndn-test/numbers.txt/%FD%05%05%E8%0C%CE%1D/%00")
contentString = ""
count = 1
contentString += "%d" % count
count += 1
while len(contentString) < 1115:
contentString += " %d" % count
count += 1
content = Name.fromEscapedString(contentString)
else:
# Use a small name and content.
name = Name("/test")
content = Name.fromEscapedString("abc")
finalBlockId = Name("/%00")[0]
# Initialize the private key storage in case useCrypto is true.
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
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)
# Set up signatureBits in case useCrypto is false.
signatureBits = Blob(bytearray(256))
emptyBlob = Blob([])
start = getNowSeconds()
for i in range(nIterations):
data = Data(name)
data.setContent(content)
if useComplex:
data.getMetaInfo().setFreshnessPeriod(1000)
data.getMetaInfo().setFinalBlockId(finalBlockId)
if useCrypto:
# This sets the signature fields.
keyChain.sign(data, certificateName)
else:
# Imitate IdentityManager.signByCertificate to set up the signature
# fields, but don't sign.
sha256Signature = data.getSignature()
keyLocator = sha256Signature.getKeyLocator()
keyLocator.setType(KeyLocatorType.KEYNAME)
keyLocator.setKeyName(certificateName)
sha256Signature.setSignature(signatureBits)
encoding = data.wireEncode()
finish = getNowSeconds()
return (finish - start, encoding)
示例12: RepoSocketPublisher
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
from utils import getKeyID
publisher = RepoSocketPublisher(12345)
data = Data(Name("/localhost/repo-ng/test/001"))
data.setContent("SUCCESS!")
data.getMetaInfo().setFreshnessPeriod(1000000)
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage), SelfVerifyPolicyManager(identityStorage))
keyfile = "../keychain/keys/pub_user.pem"
f = open(keyfile, "r")
key = RSA.importKey(f.read())
key_name = Name("/localhost/repo-ng/test/signer")
signer_name = Name(key_name).append(getKeyID(key))
key_pub_der = bytearray(key.publickey().exportKey(format="DER"))
key_pri_der = bytearray(key.exportKey(format="DER"))
identityStorage.addKey(signer_name, KeyType.RSA, Blob(key_pub_der))
privateKeyStorage.setKeyPairForKeyName(signer_name, key_pub_der, key_pri_der)
cert_name = (
signer_name.getSubName(0, signer_name.size() - 1)
.append("KEY")
.append(signer_name[-1])
.append("ID-CERT")
.append("0")
)
keyChain.sign(data, cert_name)
publisher.put(data)
示例13: BACnetAggregator
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
class BACnetAggregator(BIPSimpleApplication, Logging):
def __init__(self, config):
if _debug: BACnetAggregator._debug("__init__ %r", config)
# get local address from the config file
laddr = config.get('BACpypes', 'address')
# make a local device object
local_device = \
LocalDeviceObject( objectName=config.get('BACpypes','objectName')
, objectIdentifier=config.getint('BACpypes','objectIdentifier')
, maxApduLengthAccepted=config.getint('BACpypes','maxApduLengthAccepted')
, segmentationSupported=config.get('BACpypes','segmentationSupported')
, vendorIdentifier=config.getint('BACpypes','vendorIdentifier')
)
# build a bit string that knows about the bit names
pss = ServicesSupported()
pss['whoIs'] = 1
pss['iAm'] = 1
pss['readProperty'] = 1
pss['writeProperty'] = 1
# set the property value to be just the bits
local_device.protocolServicesSupported = pss.value
# make a simple application
BIPSimpleApplication.__init__(self, local_device, laddr)
# create logger
self.logger = BACnetDataLogger(self, config)
self.loadKey()
# keep track of requests to line up responses
self._request = None
# connect to local repo
self.publisher = RepoSocketPublisher(12345)
self.interval = 5 # in seconds
def loadKey(self):
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keychain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
f = open(key_file, "r")
self.key = RSA.importKey(f.read())
self.key_name = Name(bld_root).append(getKeyID(self.key))
key_pub_der = bytearray(self.key.publickey().exportKey(format="DER"))
key_pri_der = bytearray(self.key.exportKey(format="DER"))
self.identityStorage.addKey(self.key_name, KeyType.RSA, Blob(key_pub_der))
self.privateKeyStorage.setKeyPairForKeyName(self.key_name, key_pub_der, key_pri_der)
self.cert_name = self.key_name.getSubName(0, self.key_name.size() - 1).append(
"KEY").append(self.key_name[-1]).append("ID-CERT").append("0")
print 'KeyName = ' + self.key_name.toUri()
print 'CertName = ' + self.cert_name.toUri()
def publishData(self, name_str, payload, timestamp):
data = Data(Name(name_str).append(bytearray(timestamp)))
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC, iv)
data.setContent(bytearray(time_s + iv + encryptor.encrypt(pad(json.dumps(payload)))))
data.getMetaInfo().setFreshnessPeriod(10000)
self.keychain.sign(data, self.cert_name)
self.publisher.put(data)
#print payload
#print 'Publish ' + data.getName().toUri()
def request(self, apdu):
if _debug: BACnetAggregator._debug("request %r", apdu)
# save a copy of the request
self._request = apdu
# forward it along
BIPSimpleApplication.request(self, apdu)
def confirmation(self, apdu):
#print thread.get_ident()
global kds_count, key, time_s, point_count
if _debug: BACnetAggregator._debug("confirmation %r", apdu)
if isinstance(apdu, Error):
sys.stdout.write("error: %s\n" % (apdu.errorCode,))
sys.stdout.flush()
elif isinstance(apdu, AbortPDU):
apdu.debug_contents()
elif (isinstance(self._request, ReadPropertyRequest)) and (isinstance(apdu, ReadPropertyACK)):
# find the datatype
datatype = get_datatype(apdu.objectIdentifier[0], apdu.propertyIdentifier)
BACnetAggregator._debug(" - datatype: %r", datatype)
if not datatype:
raise TypeError, "unknown datatype"
# special case for array parts, others are managed by cast_out
#.........这里部分代码省略.........
示例14: RepoCommandParameter
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
rp = RepoCommandParameter()
dataPrefix = Name("/example/data/1/test/test1")
rp.setName(dataPrefix)
rp.setStartBlockId(0)
interest = Interest(Name("/example/repo/1").append("insert").append(rp.wireEncode()))
identityStorage = MemoryIdentityStorage()
privateKeyStorage = MemoryPrivateKeyStorage()
keyChain = KeyChain(IdentityManager(identityStorage, privateKeyStorage),
SelfVerifyPolicyManager(identityStorage))
# 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)
# Make a Face just so that we can sign the interest.
face = Face("localhost")
face.setCommandSigningInfo(keyChain, certificateName)
face.makeCommandInterest(interest)
callbacks = Callbacks()
print interest.getName().toUri()
face.expressInterest(interest, callbacks.onData, callbacks.onTimeout)
face.registerPrefix(dataPrefix, callbacks.onInterest, callbacks.onRegisterFailed)
示例15: __init__
# 需要导入模块: from pyndn import Name [as 别名]
# 或者: from pyndn.Name import getSubName [as 别名]
class SensorDataLogger:
def __init__(self, data_interval):
# connect to modbus
self.master = modbus_tcp.TcpMaster("172.17.66.246", 502)
# self.master.set_timeout(120) # in seconds
# connect to local repo
self.publisher = RepoSocketPublisher(12345)
self.prefix = "/ndn/ucla.edu/bms/strathmore/data/demand"
self.interval = data_interval # in seconds
self.loadKey()
def loadKey(self):
self.identityStorage = MemoryIdentityStorage()
self.privateKeyStorage = MemoryPrivateKeyStorage()
self.keychain = KeyChain(IdentityManager(self.identityStorage, self.privateKeyStorage))
f = open(key_file, "r")
self.key = RSA.importKey(f.read())
self.key_name = Name(bld_root).append(getKeyID(self.key))
key_pub_der = bytearray(self.key.publickey().exportKey(format="DER"))
key_pri_der = bytearray(self.key.exportKey(format="DER"))
self.identityStorage.addKey(self.key_name, KeyType.RSA, Blob(key_pub_der))
self.privateKeyStorage.setKeyPairForKeyName(self.key_name, key_pub_der, key_pri_der)
self.cert_name = self.key_name.getSubName(0, self.key_name.size() - 1).append(
"KEY").append(self.key_name[-1]).append("ID-CERT").append("0")
print 'KeyName = ' + self.key_name.toUri()
print 'CertName = ' + self.cert_name.toUri()
def publishData(self, key, key_ts, payload, timestamp):
data = Data(Name(self.prefix).append(bytearray(timestamp)))
iv = Random.new().read(AES.block_size)
encryptor = AES.new(key, AES.MODE_CBC, iv)
data.setContent(bytearray(key_ts + iv + encryptor.encrypt(pad(json.dumps(payload)))))
data.getMetaInfo().setFreshnessPeriod(5000)
self.keychain.sign(data, self.cert_name)
self.publisher.put(data)
#print payload
#print data.getName().toUri()
def run(self):
key_ts = struct.pack('!Q', int(time.time() * 1000))
key = Random.new().read(32)
kds_count = -1
while (True):
# KDS
kds_count = kds_count + 1
if kds_count % 120 == 0:
key_ts = struct.pack("!Q", int(time.time() * 1000))
key = Random.new().read(32)
kds_thread = kds.SimpleKDSPublisher(Name(bld_root), self.keychain, self.cert_name, key, key_ts)
kds_thread.start()
kds_count = 0
# Data
now = int(time.time() * 1000) # in milliseconds
a = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 166, 1)
b = self.master.execute(100, cst.READ_HOLDING_REGISTERS, 167, 1)
vln = (b[0] << 16) + a[0]
c = self.master.execute(1, cst.READ_HOLDING_REGISTERS, 150, 1)
la = c[0]
payload = {'ts': now, 'vlna': vln, 'la': la}
timestamp = struct.pack("!Q", now) # timestamp is in milliseconds
self.publishData(key, key_ts, payload, timestamp)
time.sleep(self.interval)