本文整理汇总了Python中SmartMeshSDK.utils.FormatUtils类的典型用法代码示例。如果您正苦于以下问题:Python FormatUtils类的具体用法?Python FormatUtils怎么用?Python FormatUtils使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了FormatUtils类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _notifDataCallback
def _notifDataCallback(self, notifName, notifParams):
assert notifName == NOTIFDATA
try:
# log
log.debug(
"notifClient._notifDataCallback {0}:\n{1}".format(NOTIFDATA, FormatUtils.formatNamedTuple(notifParams))
)
# read MAC address from notification
mac = tuple(notifParams.macAddress)
# update role
self._changeDeviceRole(mac, ROLE_DATA)
# update counters
self._incrementCounter(mac, COL_NOTIF_DATA)
# parse packet
if notifParams.srcPort == 0xF0B9:
self.oap_dispatch.dispatch_pkt(NOTIFDATA, notifParams)
else:
raise SystemError("expected srcPort {0}".format(notifParams.srcPort))
except Exception as err:
output = []
output += [type(err)]
output += [err]
output += [traceback.format_exc()]
output = "\n".join([str(o) for o in output])
log.error(output)
print output
示例2: log
def log(self,event_type,mac=None,temperature='',generationTime=None):
assert event_type in self.EVENT_ALL
if mac:
macString = FormatUtils.formatMacString(mac)
else:
macString = ''
if generationTime!=None and self.timeOffset!=None:
timestamp = self.timeOffset+generationTime
else:
timestamp = time.time()
timestampString = '{0}.{1:03d}'.format(
time.strftime("%Y-%m-%d %H:%M:%S",time.localtime(timestamp)),
int(1000*(timestamp-int(timestamp))),
)
logline = '{TIMESTAMP},{EVENT_TYPE},{MAC},{TEMPERATURE}\n'.format(
TIMESTAMP = timestampString,
EVENT_TYPE = event_type,
MAC = macString,
TEMPERATURE = temperature,
)
print logline,
self.datalogfile.write(logline)
self.datalogfile.flush()
示例3: _moteListFrameCb_toggleLed
def _moteListFrameCb_toggleLed(self, mac, button):
if isinstance(self.apiDef, IpMgrDefinition.IpMgrDefinition):
# find out whether to switch LED on of off
if button.cget("text") == "ON":
val = 1
button.configure(text="OFF")
else:
val = 0
button.configure(text="ON")
# send the OAP message
try:
self.oap_clients[mac].send(
OAPMessage.CmdType.PUT, # command
[3, 2], # address
data_tags=[OAPMessage.TLVByte(t=0, v=val)], # parameters
cb=None, # callback
)
except APIError as err:
self.statusFrame.write("[WARNING] {0}".format(err))
else:
# update status
self.statusFrame.write(
"Toggle LED command sent successfully to mote {0}.".format(FormatUtils.formatMacString(mac))
)
else:
button.configure(text="N.A.")
# update status
self.statusFrame.write("This feature is only present in SmartMesh IP")
示例4: _print_allMoteInfo
def _print_allMoteInfo(self):
columnNames = []
for (mac,v) in self.allMoteInfo.items():
for n in v:
if n in ['macAddress','RC','reserved']:
continue
columnNames += [n]
columnNames = sorted(list(set(columnNames)))
data_matrix = []
data_matrix += [['mac']+columnNames]
for (mac,v) in self.allMoteInfo.items():
thisline = []
thisline += [FormatUtils.formatMacString(mac)]
for n in columnNames:
if n in v:
thisline += [v[n]]
else:
thisline += ['']
data_matrix += [thisline]
table = plotly.tools.FigureFactory.create_table(data_matrix)
plotly.offline.plot(table,filename='allMoteInfo.html',)
示例5: oapinfo_response
def oapinfo_response(mac, oap_resp):
output = []
output += ["GET /info response from {0}:".format(FormatUtils.formatMacString(mac))]
output = '\n'.join(output)
print output
print (mac, oap_resp)
示例6: publish
def publish(self,mac,datastream,value):
# log
if log.isEnabledFor(logging.DEBUG):
output = []
output += ['publish() called with:']
output += ['- mac {0}'.format(FormatUtils.formatMacString(mac))]
output += ['- datastream {0}'.format(datastream)]
output += ['- value {0}'.format(value)]
output = '\n'.join(output)
log.debug(output)
# verify subscriber alive, if exists
if self.subscriber:
if not self.subscriber.isAlive():
self.subscriber = None
raise SystemError("subscriber is not alive during publish()")
# create the datastream (or retrieve feed_id if exists)
feed_id = self.createDatastream(mac,datastream)
# publish to datastream
self.client.put(
url = 'feeds/{0}.json'.format(
feed_id,
),
body = {
'version': '1.0.0',
'datastreams': [
{
'id' : datastream,
'current_value': value,
},
]
},
)
# log
if log.isEnabledFor(logging.DEBUG):
output = []
output += ['published to Xively:']
output += ['- mac {0}'.format(FormatUtils.formatMacString(mac))]
output += ['- datastream {0}'.format(datastream)]
output += ['- value {0}'.format(value)]
output = '\n'.join(output)
log.debug(output)
示例7: handle_oap_data
def handle_oap_data(mac,notif):
if isinstance(notif,OAPNotif.OAPTempSample):
print 't={TEMP:.2f}C at {MAC}'.format(
TEMP = float(notif.samples[0])/100,
MAC = FormatUtils.formatMacString(mac),
)
示例8: printOperationalMotes
def printOperationalMotes():
output = []
output += ["{0} operational motes:".format(len(AppData().get('operationalmotes')))]
for (i,m) in enumerate(AppData().get('operationalmotes')):
output += ['{0}: {1}'.format(i,FormatUtils.formatMacString(m))]
output = '\n'.join(output)
print output
示例9: _moteListFrameCb_clearTemp
def _moteListFrameCb_clearTemp(self,mac,button):
# clear the temperature data
self.notifClientHandler.clearTemp(mac)
# update status
self.statusFrame.write(
"Temperature data for mote {0} cleared successfully.".format(
FormatUtils.formatMacString(mac),
)
)
示例10: _moteListFrameCb_clearCtrs
def _moteListFrameCb_clearCtrs(self,mac,button):
# clear the counters
self.notifClientHandler.clearNotifCounters(mac)
# update status
self.statusFrame.write(
"Counters for mote {0} cleared successfully.".format(
FormatUtils.formatMacString(mac),
)
)
示例11: _handle_oap_notif
def _handle_oap_notif(self,mac,notif):
receive_time = float(time.time()) - self.mapmgrtime.pctomgr_time_offset
output = "OAP notification from {0} (receive time {1}):\n{2}".format(
FormatUtils.formatMacString(mac),
receive_time,
notif
)
if AppData().get('printNotifs'):
print output
if AppData().get('logNotifs'):
self.log_file.write('{0}\n'.format(output))
示例12: mac2feedId
def mac2feedId(self,mac):
if type(mac) in [tuple,list]:
mac = FormatUtils.formatMacString(mac)
returnVal = None
with self.dataLock:
for d in self.xivelyDevices:
if d['serial']==mac:
returnVal = d['feed_id']
break
return returnVal
示例13: _moteListFrameCb_clearPkGen
def _moteListFrameCb_clearPkGen(self,mac,button):
# log
log.debug("_moteListFrameCb_clearPkGen")
# clear the PkGen counters
self.notifClientHandler.clearPkGenCounters(mac)
# update status
self.statusFrame.write(
"pkGen counters for mote {0} cleared successfully.".format(
FormatUtils.formatMacString(mac),
)
)
示例14: _notifCallback
def _notifCallback(self, notifName, notifParams):
try:
assert notifName==IpMgrSubscribe.IpMgrSubscribe.NOTIFHEALTHREPORT
mac = FormatUtils.formatMacString(notifParams.macAddress)
hr = self.hrParser.parseHr(notifParams.payload)
# log
hrlog.info('from {0}:\n{1}'.format(
mac,
self.hrParser.formatHr(hr),
),
)
with self.dataLock:
# format of data:
# [
# ['' , 'Device', 'Neighbors', 'Discovered', 'RSSI'],
# ['11-11-11-11-11-11-11-11' , 0, 3, 2, 4],
# ['22-22-22-22-22-22-22-22' , 0, 3, 2, 5],
# ]
# find notifName row
found=False
for row in self.data:
if row[0]==mac:
found=True
break
# create row if needed
if not found:
self.data.append([mac,0,0,0,0])
row = self.data[-1]
# increment counters
if 'Device' in hr:
row[1] += 1
if 'Neighbors' in hr:
row[2] += 1
if 'Discovered' in hr:
row[3] += 1
if 'Extended' in hr:
row[4] += 1
except Exception as err:
print type(err)
print err
raise
示例15: _parseData
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