本文整理汇总了Python中SmartMeshSDK.utils.FormatUtils.formatBuffer方法的典型用法代码示例。如果您正苦于以下问题:Python FormatUtils.formatBuffer方法的具体用法?Python FormatUtils.formatBuffer怎么用?Python FormatUtils.formatBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类SmartMeshSDK.utils.FormatUtils
的用法示例。
在下文中一共展示了FormatUtils.formatBuffer方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _parseData
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def _parseData(self,byteArray):
returnVal = {}
# log
log.debug("_parseData with byteArray {0}".format(FormatUtils.formatBuffer(byteArray)))
# command ID
try:
(returnVal['cmdId'],) = struct.unpack('>H', self._toString(byteArray[:2]))
except struct.error as err:
raise ValueError(err)
if returnVal['cmdId']==CMDID_CONFIGURATION:
try:
(
returnVal['reportPeriod'],
returnVal['bridgeSettlingTime'],
returnVal['ldoOnTime'],
) = struct.unpack('>III', self._toString(byteArray[2:]))
except struct.error as err:
raise ValueError(err)
elif returnVal['cmdId']==CMDID_REPORT:
try:
(
returnVal['temperature'],
returnVal['adcValue'],
) = struct.unpack('>IH', self._toString(byteArray[2:]))
except struct.error as err:
raise ValueError(err)
elif returnVal['cmdId']==ERR_NO_SERVICE:
pass
elif returnVal['cmdId'] in [ERR_NOT_ENOUGH_BW,ERR_INVALID]:
try:
(
returnVal['val'],
) = struct.unpack('>I', self._toString(byteArray[2:]))
except struct.error as err:
raise ValueError(err)
else:
raise ValueError("unexpected command ID {0}".format(returnVal['cmdId']))
return returnVal
示例2: calculate
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def calculate(self,data):
if log.isEnabledFor(logging.DEBUG):
log.debug('calculating for data={0}'.format(FormatUtils.formatBuffer(data)))
ptr = 0
tempfcs = 0xffff
while ptr<len(data):
tempfcs = (tempfcs >> 8) ^ self._fcstab[(tempfcs ^ data[ptr]) & 0xff];
ptr += 1
tempfcs ^= 0xffff
fcs = []
fcs.append( (tempfcs>>0) & 0xff )
fcs.append( (tempfcs>>8) & 0xff )
if log.isEnabledFor(logging.DEBUG):
log.debug('fcs=0x%2x%2x',fcs[0],fcs[1])
return fcs
#======================== private =========================================
示例3: _whmt_notif
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def _whmt_notif(self,cmdId,subcmdId):
'''
\brief Called by C library when a notification is received.
'''
log.debug(
'_whmt_notif cmdId={0} subcmdId={1} notifBuf={2}'.format(
cmdId,
subcmdId,
FormatUtils.formatBuffer([ord(b) for b in self.notifBuf]),
)
)
#===== cast notification buffer to correct type
# find apiNotif
apiNotifFields = []
nameArray = []
for notif in HartMoteDefinition.HartMoteDefinition.notifications:
if notif['id']==cmdId:
nameArray += [notif['name']]
for f in notif['response']['FIELDS']:
if f[0] not in [SUBID1,SUBID2]:
apiNotifFields += [f]
# create returned fields on the fly
theseFields = []
lengthField = None
for [name,type,length,_] in apiNotifFields:
if length==None:
theseFields += [('{0}Len'.format(name), c_uint8)]
theseFields += [(name, c_uint8*self.MAX_FRAME_LENGTH)]
lengthField = name
else:
theseFields += [(name, _getResponseType(type,length))]
# Structure to hold the response
class reply_t(Structure):
_fields_ = theseFields
# cast response to that structure
c_notif = cast(self.notifBuf, POINTER(reply_t))
#===== convert C notification to Python dictionary
# convert structure to dictionary
py_notif = {}
for (f,_) in theseFields:
rawVal = getattr(c_notif.contents,f)
if isinstance(rawVal,int):
py_notif[f] = rawVal
elif isinstance(rawVal,long):
py_notif[f] = int(rawVal)
else:
py_notif[f] = [int(b) for b in rawVal]
# trim lengthField
if lengthField!=None:
py_notif[lengthField] = py_notif[lengthField][:py_notif['{0}Len'.format(lengthField)]]
del py_notif['{0}Len'.format(lengthField)]
#===== put received packet in notification buffer
self.putNotification((nameArray, py_notif))
示例4: serialize
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def serialize(self,commandArray,fieldsToFill):
# log
if log.isEnabledFor(logging.DEBUG):
output = []
output += ["serialize ..."]
output += ["- commandArray: {0}".format(commandArray)]
output += ["- fieldsToFill: {0}".format(fieldsToFill)]
output = '\n'.join(output)
log.debug(output)
# validate input
if type(commandArray)!=types.ListType and type(commandArray)!=types.TupleType:
raise TypeError("First parameter should be a list or tuple, not "+str(type(commandArray)))
# initialize the output
byteArray = []
for cmdCounter in range(len(commandArray)):
# packet payload
definition = self.ApiDef.getDefinition(
ApiDefinition.ApiDefinition.COMMAND,
commandArray[:cmdCounter+1]
)
fields = [ApiDefinition.Field(fieldRaw,self.ApiDef.fieldOptions)
for fieldRaw in definition['request']]
for field in fields:
thisFieldByteArray = []
if field.name in ApiDefinition.ApiDefinition.RESERVED:
thisFieldByteArray.append(
self.ApiDef.subcommandNameToId(
ApiDefinition.ApiDefinition.COMMAND,
commandArray[:cmdCounter+1],
commandArray[cmdCounter+1]
)
)
else:
val = fieldsToFill[field.name]
if field.format==ApiDefinition.FieldFormats.STRING:
thisFieldByteArray += [ord(car) for car in val]
elif field.format==ApiDefinition.FieldFormats.BOOL:
thisFieldByteArray.append(val)
elif field.format==ApiDefinition.FieldFormats.INT:
thisFieldByteArray += [operator.mod(int(val>>(8*i)), 0x100) for i in xrange(field.length-1, -1, -1)]
elif field.format==ApiDefinition.FieldFormats.INTS:
if field.length==1:
temp = struct.pack('>b',int(val))
elif field.length==2:
temp = struct.pack('>h',int(val))
elif field.length==4:
temp = struct.pack('>i',int(val))
else:
raise SystemError('field with format='+field.format+' and length='+str(field.length)+' unsupported.')
for i in range(len(temp)):
thisFieldByteArray.append(ord(temp[i]))
elif field.format==ApiDefinition.FieldFormats.HEXDATA:
thisFieldByteArray += val
else:
raise SystemError('unknown field format='+field.format)
# padding
while len(thisFieldByteArray)<field.length:
thisFieldByteArray = [0x00]+thisFieldByteArray
byteArray = byteArray+thisFieldByteArray
cmdId = self.ApiDef.nameToId(ApiDefinition.ApiDefinition.COMMAND,commandArray)
if log.isEnabledFor(logging.DEBUG):
output = []
output += ["... serialize into"]
output += ["- cmdId: {0}".format(cmdId)]
output += ["- byteArray: {0}".format(FormatUtils.formatBuffer(byteArray))]
output = '\n'.join(output)
log.debug(output)
return cmdId,byteArray
示例5: deserialize
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def deserialize(self,type,id,byteArray):
notRcOk = False
returnFields = {}
nameArray = [self.ApiDef.idToName(type,id)]
index = 0
# log
if log.isEnabledFor(logging.DEBUG):
output = []
output += ["deserialize ..."]
output += ["- type: {0}".format(type)]
output += ["- id: {0}".format(id)]
output += ["- byteArray: {0}".format(FormatUtils.formatBuffer(byteArray))]
output = '\n'.join(output)
log.debug(output)
continueParsing = True
while continueParsing:
fieldDefs = self.ApiDef.getResponseFields(type,nameArray)
for fieldDef in fieldDefs:
fieldMissing = False
# isolate the piece of the byteArray corresponding to this field
if fieldDef.length:
# this field has an expected length
thisFieldArray = byteArray[index:index+fieldDef.length]
index += fieldDef.length
if len(thisFieldArray)==0:
# field missing: allowed
fieldMissing = True
elif len(thisFieldArray)<fieldDef.length:
# incomplete field: not allowed
raise CommandError(
CommandError.TOO_FEW_BYTES,
"incomplete field {0}".format(fieldDef.name),
)
else:
thisFieldArray = byteArray[index:]
index = len(byteArray)
if len(thisFieldArray)<1:
# too few bytes
fieldMissing = True
# find thisFieldValue
if fieldMissing:
thisFieldValue = None
else:
if fieldDef.format==ApiDefinition.FieldFormats.STRING:
thisFieldValue = ''
for byte in thisFieldArray:
thisFieldValue += chr(byte)
elif fieldDef.format==ApiDefinition.FieldFormats.BOOL:
if len(thisFieldArray)==1 and thisFieldArray[0]==0x00:
thisFieldValue = False
elif len(thisFieldArray)==1 and thisFieldArray[0]==0x01:
thisFieldValue = True
else:
raise CommandError(CommandError.VALUE_NOT_IN_OPTIONS,
"field="+fieldDef.name+" value="+str(thisFieldValue))
elif fieldDef.format==ApiDefinition.FieldFormats.INT:
thisFieldValue = 0
for i in range(len(thisFieldArray)):
thisFieldValue += thisFieldArray[i]*pow(2,8*(len(thisFieldArray)-i-1))
elif fieldDef.format==ApiDefinition.FieldFormats.INTS:
tempList = [chr(i) for i in thisFieldArray]
tempString = ''.join(tempList)
if len(thisFieldArray)==1:
(thisFieldValue,) = struct.unpack_from('>b',tempString)
elif len(thisFieldArray)==2:
(thisFieldValue,) = struct.unpack_from('>h',tempString)
elif len(thisFieldArray)==4:
(thisFieldValue,) = struct.unpack_from('>i',tempString)
else:
raise SystemError('field with format='+fieldDef.format+' and length='+str(fieldDef.length)+' unsupported.')
elif fieldDef.format==ApiDefinition.FieldFormats.HEXDATA:
thisFieldValue = thisFieldArray
else:
raise SystemError('unknown field format='+fieldDef.format)
# make sure thisFieldValue in fieldDef.options
if fieldDef.options.validOptions:
if thisFieldValue not in fieldDef.options.validOptions:
raise CommandError(CommandError.VALUE_NOT_IN_OPTIONS,
"field="+fieldDef.name+" value="+str(thisFieldValue))
if fieldDef.name in ApiDefinition.ApiDefinition.RESERVED:
# the subcommand specifier cannot be missing
if thisFieldValue==None:
#.........这里部分代码省略.........
示例6: _notifDataCallback
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def _notifDataCallback(self,notifName,notifParams):
# only accept data from mote selected in the optionbox
selectedMote = dc2126aData().get('selectedMote')
if not selectedMote:
return
if tuple(notifParams.macAddress) != tuple(selectedMote):
return
if notifParams.dstPort!=WKP_DC2126A:
return
# parse data
try:
parsedData = self._parseData(notifParams.data)
except ValueError as err:
output = []
output += ["Could not parse received data {0}".format(
FormatUtils.formatBuffer(notifParams.data)
)]
output += ['Error: {0}'.format(type(err))]
output += ['{0}'.format(err)]
output = '\n'.join(output)
print output
log.error(output)
return
# log
output = []
output += ["Received data:"]
for (k,v) in parsedData.items():
output += ["- {0:<15}: 0x{1:x} ({1})".format(k,v)]
output = '\n'.join(output)
log.debug(output)
# handle data
if parsedData['cmdId']==CMDID_REPORT:
# record temperature
temperature = self.converters.convertTemperature(parsedData['temperature'])
dc2126aData().set('temperature',temperature)
# record adcValue
adcValue = self.converters.convertAdcValue(parsedData['adcValue'])
dc2126aData().set('adcValue',adcValue)
# record energysource
energysource = self.converters.convertEnergySource(notifParams.macAddress,adcValue)
dc2126aData().set('energysource',energysource)
elif parsedData['cmdId']==CMDID_CONFIGURATION:
# show new CFG values
self.displayConfigurationCB(parsedData)
elif parsedData['cmdId']==ERR_NO_SERVICE:
# display message
output = []
output += ['This configuration was NOT accepted by the mote.']
output += ['The mote indicated it cannot change its configuration']
output += ['at this point since no network service has been']
output += ['installed yet. Retry sending this command later.']
output = '\n'.join(output)
self.displayErrorCB(output)
elif parsedData['cmdId']==ERR_NOT_ENOUGH_BW:
# display message
output = []
output += ['This configuration was NOT accepted by the mote.']
output += ['The mote indicated its current service is {}ms,'.format(parsedData['val'])]
output += ['which is not sufficient for this configuration.']
output = '\n'.join(output)
self.displayErrorCB(output)
elif parsedData['cmdId']==ERR_INVALID:
# display message
output = []
output += ['This configuration was NOT accepted by the mote.']
output += ['The mote indicated value {0} is invalid.'.format(parsedData['val'])]
output = '\n'.join(output)
self.displayErrorCB(output)
else:
# display error
self.displayErrorCB("received unexpected cmdId {0}".format(parsedData['cmdId']))
示例7: write
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def write(self,stringToWrite):
self.hdlcBytes = [ord(b) for b in stringToWrite]
print 'HdlcConverter.write {0}'.format(FormatUtils.formatBuffer(self.hdlcBytes))
self.doneSem.release()
return len(stringToWrite)
示例8: json_to_influxdb
# 需要导入模块: from SmartMeshSDK.utils import FormatUtils [as 别名]
# 或者: from SmartMeshSDK.utils.FormatUtils import formatBuffer [as 别名]
def json_to_influxdb(self,sol_json,tags):
"""
Convert a JSON SOL object into a InfluxDB point
:param list sol_json: JSON SOL object
:return: InfluxDB point
:rtpe: list
"""
# tags
obj_tags = copy.deepcopy(tags)
# fields
if sol_json['type']==SolDefines.SOL_TYPE_DUST_NOTIF_HRNEIGHBORS:
fields = {}
for n in sol_json["value"]['neighbors']:
fields["neighbors:" + str(n['neighborId'])] = n
fields['numItems'] = sol_json["value"]['numItems']
elif sol_json['type']==SolDefines.SOL_TYPE_DUST_NOTIF_HRDISCOVERED:
fields = sol_json["value"]
elif sol_json['type']==SolDefines.SOL_TYPE_DUST_SNAPSHOT:
fields = {}
fields["mote"] = []
for mote in sol_json["value"]:
mote["macAddress"] = FormatUtils.formatBuffer(mote["macAddress"])
for path in mote["paths"]:
path["macAddress"] = FormatUtils.formatBuffer(path["macAddress"])
fields["mote"].append(mote)
elif sol_json['type']==SolDefines.SOL_TYPE_DUST_EVENTNETWORKRESET:
fields = {'value':'dummy'}
else:
fields = sol_json["value"]
for (k,v) in fields.items():
if type(v)==list: # mac
if k in ['macAddress','source','dest']:
fields[k] = FormatUtils.formatBuffer(v)
elif k in ['sol_version','sdk_version','solmanager_version']:
fields[k] = ".".join(str(i) for i in v)
f = flatdict.FlatDict(fields)
fields = {}
for (k,v) in f.items():
fields[k] = v
# add additionnal field or tag if apply_function exists
try:
obj_struct = SolDefines.solStructure(sol_json['type'])
if 'apply' in obj_struct:
for ap in obj_struct['apply']:
arg_list = [fields[arg] for arg in ap["args"]]
if "field" in ap:
fields[ap["field"]] = ap["function"](*arg_list)
if "tag" in ap:
obj_tags[ap["tag"]] = ap["function"](*arg_list)
except ValueError:
pass
# get SOL type
measurement = SolDefines.solTypeToTypeName(SolDefines,sol_json['type'])
# convert SOL timestamp to UTC
utc_time = sol_json["timestamp"]*1000000000
sol_influxdb = {
"time" : utc_time,
"tags" : obj_tags,
"measurement" : measurement,
"fields" : fields,
}
return sol_influxdb