本文整理汇总了Python中xbee.ZigBee.halt方法的典型用法代码示例。如果您正苦于以下问题:Python ZigBee.halt方法的具体用法?Python ZigBee.halt怎么用?Python ZigBee.halt使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xbee.ZigBee
的用法示例。
在下文中一共展示了ZigBee.halt方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: node_discovery
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def node_discovery():
comPortList = getActiveComPort()
if comPortList:
comPort = comPortList[0].get('name')
timeOut = int(comPortList[0].get('timeout'))
baudRate = int(comPortList[0].get('baudrate'))
count = 0
try:
ser = serial.Serial(comPort, baudRate, timeout=timeOut)
xbee = ZigBee(ser,escaped=True)
node_list=[]
xbee.at(command='ND')
response = {'':''}
while response <> {}:
response = xbee.wait_read_frame()
if response:
print response
node_list.append(response)
else:
text = "Xbee: Timeout during node discovery operation!"
print "Spisak: ", node_list # return []
return node_list
except serial.SerialException as ex:
text = "Exception: " + ex.__str__()
return text
else:
xbee.halt()
ser.close()
示例2: xbee_tp
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def xbee_tp(xbeeRemAddr):
"""
XBee TP command implementation. Input: xbeeRemAddr. Ex: xbee_is('0013A200406B5174')
"""
comPortList = getActiveComPort()
if comPortList:
comPort = comPortList[0].get('name')
timeOut = int(comPortList[0].get('timeout'))
baudRate = int(comPortList[0].get('baudrate'))
count = 0
try:
ser = serial.Serial(comPort, baudRate, timeout=timeOut)
xbee = ZigBee(ser,escaped=True)
xbee.remote_at(dest_addr_long=xbeeRemAddr,command="TP",frame_id="C")
response = xbee.wait_read_frame()
return response
except serial.SerialException as ex:
text = "Exception is: " + ex.__str__()
return 0
else:
xbee.halt()
ser.close()
示例3: hiddenXbeePin
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def hiddenXbeePin(xbeeRemAddr, xbeePin, xbeePinState):
"Manipulate XBee pins. Input: xbeeRemAddr, xbeePin, xbeePinState. Ex: xbee_pin('0013A200406B5174'.decode('hex'),'D0','ON')"
comPortList = getActiveComPort()
if comPortList:
comPort = comPortList[0].get('name')
timeOut = int(comPortList[0].get('timeout'))
baudRate = int(comPortList[0].get('baudrate'))
count = 0
try:
ser = serial.Serial(comPort, baudRate, timeout=timeOut)
xbee = ZigBee(ser,escaped=True)
if xbeePinState == 'ON':
xbeePinStateHex = '\x05'
if xbeePinState == 'OFF':
xbeePinStateHex = '\x04'
try:
xbee.remote_at(dest_addr_long=xbeeRemAddr,command=xbeePin,parameter=xbeePinStateHex)
finally:
return 1
except serial.SerialException as ex:
text = "Exception is: " + ex.__str__()
return 0
else:
xbee.halt()
ser.close()
示例4: test_read_timeout
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def test_read_timeout(self):
port = serial.Serial('/dev/ttyUSB0', 9600)
xbee_device = ZigBee(port)
self.settings.bind(xbee_device)
self.assertRaises(ReadException,
self.settings.read_all)
xbee_device.halt()
port.close()
示例5: start
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def start(self):
#-------------------------------------------------------------------------------
# Open serial port
ser = serial.Serial('/dev/ttyAMA0', 9600)
# Create API object
xbee = ZigBee(ser,callback = self.print_data ,escaped=True)
# Continuously read and print packets
print "Starting"
#print '\n *****************************'
#print xbee.api_commands
#print '\n *****************************'
#print xbee.api_responses
#print '\n *****************************'
MY = self.HexToByte('0B41')
ADR = self.HexToByte('0013A2004092D86A')
once = 1
while True:
try:
#xbee.tx(dest_addr=pan,dest_addr_long=Destination, data='Hello World')
#xbee.remote_at(dest_addr=MY,dest_addr_long=ADR, command='MY',parameter=None)
#time.sleep(5) \x
#xbee.send("remote_at",frame_id='A', command='MY')
#
#xbee.tx(dest_addr='\xbf\x0c',dest_addr_long='\x00\x13\xa2\x00\x40\x92\xd8\x6a', data='Hello World')
if once == 1:
print 'Discovering Nodes'
#xbee.at(frame_id='A', command='MY')
#xbee.at(frame_id='A', command='ID')
xbee.at(frame_id='D', command='ND')
#xbee.remote_at(dest_addr='\xbf\x0c',command='IR',parameter='\xff')
#xbee.remote_at(dest_addr='\xbf\x0c',command='V+',parameter='\xff')
#xbee.remote_at(dest_addr='\xbf\x0c',command='MY',parameter=None)
once = 0
time.sleep(5)
print 'Sending RAT'
#xbee.tx(dest_addr=MY2,dest_addr_long=ADR2, data='Hello World')
xbee.remote_at(dest_addr=MY,dest_addr_long=ADR,command='IS')
#time.sleep(1)
xbee.remote_at(dest_addr=MY,dest_addr_long=ADR,command='IR',parameter='\xFF')
#time.sleep(1)
xbee.remote_at(dest_addr=MY,dest_addr_long=ADR,command='IR',parameter='\x00')
print 'Done'
time.sleep(3)
except KeyboardInterrupt:
break
xbee.halt()
ser.close()
示例6: test_readall
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def test_readall(self):
port = serial.Serial('/dev/ttyUSB0', 38400)
xbee_device = ZigBee(port)
self.settings.bind(xbee_device)
read_settings = self.settings.read_all()
#TODO: clearly we need to allow for other versions, etc.
self.assertEqual(read_settings['Version'], '21A7 Coord(API)')
#TODO: and this needs to be configurable
self.assertEqual(read_settings['PAN ID'], '000000000BADFACE')
xbee_device.halt()
port.close()
示例7: main
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def main():
'''After parsing arguments , it instantiates an
asynchronous dispatcher which creates a new thread
for every packet that arrives.
'''
# Argument parsing
parser = ArgumentParser(description='Receives data from any number or XBee routers in API mode using Direct I/O and then uploads this information to Cosm.')
parser.add_argument('--debug', help='prints everything that the coordinator receives', action='store_true', default=False)
parser.add_argument('device_file', help='where the zigbee cordinator is connected', action='store')
parser.add_argument('baud_rate', action='store', type=int)
args = vars(parser.parse_args())
# Serial connection with the XBee
try:
ser = Serial(args['device_file'], args['baud_rate'])
except SerialException as s:
print 'Connection with the XBee could not be established... Exiting.'
exit()
print 'Listening on', args['device_file'], '...\n'
# Asynchronous dispatcher
dispatch = ZBDispatch(ser)
dispatch.register(
'direct_io',
direct_io_handler,
lambda packet: packet['id']=='rx_io_data_long_addr',
args['debug']
)
dispatch.register(
'io_data',
xbee_arduino_handler,
lambda packet: packet['id']=='rx',
args['debug']
)
zb = ZigBee(ser, callback=dispatch.dispatch, escaped=True)
# Main loop
while True:
try:
sleep(.1)
except KeyboardInterrupt as k:
print '\nCTRL+C received. Exiting.'
break
# Close XBee connection
zb.halt()
ser.close()
示例8: ReceiverProcess
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
class ReceiverProcess(\
process.BaseProcess,
xbeeparser.XBeeApiFrameBaseParser):
'''
Base class of process to receive data from XBee ZB.
There should be only one instance against one XBee coordinator.
'''
def __init__(self, port='/dev/ttyAMA0', baurate=9600, log_level=logging.INFO):
'''Initialize XBee instance with serial port and baurate.
The baurate should be set to same value with XBee module.
'''
self._logger = logging.getLogger(type(self).__name__)
self._logger.setLevel(log_level)
process.BaseProcess.__init__(self, log_level=log_level)
xbeeparser.XBeeApiFrameBaseParser.__init__(self, log_level=log_level)
self._port = port
self._baurate = baurate
def _init_xbee(self):
'''
_init_xbee: None -> None
This method should be called in run() of child process.
'''
def receive_frame(api_frame):
for monitor in self._monitors:
addr = self.get_source_addr_long(api_frame)
if addr == monitor.get_monitoring_address():
monitor.post_data_to_service(api_frame)
self._ser = serial.Serial(self._port, self._baurate)
self._xbee = ZigBee(self._ser, escaped=True, callback=receive_frame)
def _terminate(self):
'''
_terminate: None -> None
Wait and join all thread and process.
'''
# halt() must be called before closing the serial
# port in order to ensure proper thread shutdown
self._xbee.halt()
self._ser.close()
process.BaseProcess._terminate(self)
示例9: XbeeAPIWatcher
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
class XbeeAPIWatcher(object):
def __init__(self):
self.FILE = open(settings.LOG_FILE_NAME, 'a')
self.ser = None
self.xbee = None
self.last_message = None
self.last_signal = None
self._setup_serial()
def _setup_serial(self):
self.ser = serial.Serial(settings.SERIAL_PORT, 9600, timeout=0)
self.xbee = ZigBee(self.ser, escaped=True)
def _process_message(self, message):
if message['id'] == 'rx':
self.last_message = message
logger.info(time.strftime('%Y-%m-%d %H:%M:%S')) # TODO: use a higher resolution timestamp
self.xbee.send('at', command='DB')
# wait for signal strength response
elif message['id'] == 'at_response' and message['command'] == 'DB':
logger.info('Signal Strength: -%ddBm' % ord(message['parameter']))
self.last_signal = ord(message['parameter'])
data_string = '%s,%s,%s' % (time.strftime('%Y-%m-%d %H:%M:%S'),
'-%d' % self.last_signal,
self.last_message['rf_data'].strip('\r\n'))
self.FILE.write('%s\r\n' % data_string)
self.FILE.flush()
try:
ChickenAPI.add_data(data_string)
except ConnectionError as e:
logger.error(e)
def start(self):
while True:
try:
response = self.xbee.wait_read_frame()
self._process_message(response)
except KeyboardInterrupt:
break
def stop(self):
self.xbee.halt()
self.ser.close()
示例10: main
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def main():
"""
After parsing arguments (-h flag for help), it instantiates an asynchronous dispatcher which creates a new thread for every packet that arrives.
"""
# Argument parsing
parser = ArgumentParser(description='Receives data from any number or XBee routers in API mode using Direct I/O and then uploads this information to Cosm.')
parser.add_argument('--debug', help='prints everything that the coordinator receives', action='store_true', default=False)
parser.add_argument('device_file', help='where the zigbee cordinator is connected', action='store')
parser.add_argument('baud_rate', action='store', type=int)
args = vars(parser.parse_args())
# Serial connection with the XBee
try:
ser = Serial(args['device_file'], args['baud_rate'])
except SerialException as s:
print s
exit()
print "Listening on", args['device_file'], "...\n"
# Asynchronous dispatcher
dispatch = ZBDispatch(ser)
dispatch.register(
"io_data",
io_sample_handler,
lambda packet: packet['id']=='rx_io_data_long_addr',
args['debug']
)
zb = ZigBee(ser, callback=dispatch.dispatch)
# Main loop
while True:
try:
sleep(.1)
except KeyboardInterrupt as k:
print k
break
# Close XBee connection
zb.halt()
ser.close()
示例11: listener
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def listener():
global xbee
ser = serial.Serial(DEVICE, 9600)
xbee = ZigBee(ser, callback=print_data)
rospy.loginfo("xbee started")
# in ROS, nodes are unique named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'talker' node so that multiple talkers can
# run simultaenously.
rospy.init_node('cmd_vel_listener', anonymous=True)
rospy.Subscriber("/sociobots/cmd_vel", Twist, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
xbee.halt()
ser.close()
示例12: listener
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
def listener():
global xbee
ser = serial.Serial(DEVICE, 57600)
xbee = ZigBee(ser)
# in ROS, nodes are uniquely named. If two nodes with the same
# node are launched, the previous one is kicked off. The
# anonymous=True flag means that rospy will choose a unique
# name for our 'talker' node so that multiple talkers can
# run simultaenously.
print "Ready to receive commands."
rospy.init_node('cmd_vel_listener', anonymous=True)
rospy.Subscriber("/cmd_hex", Command, callback)
# spin() simply keeps python from exiting until this node is stopped
rospy.spin()
xbee.halt()
ser.close()
示例13: __init__
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
class AlertMe:
def __init__(self, ser, upload_queue, logging):
# Create XBee library API object, which spawns a new thread
logging.debug( 'XBee setup')
self.zb = ZigBee(ser, callback=self.messageReceived)
self.ser = ser
self.queue = upload_queue
self.logging = logging
self.switchLongAddr = '12'
self.switchShortAddr = '12'
def close(self):
# halt() must be called before closing the serial
# port in order to ensure proper thread shutdown
self.zb.halt()
self.ser.close()
# this is a call back function. When a message
# comes in this function will get the data
def messageReceived(self, data):
self.logging.debug( ":".join("{:02x}".format(ord(c)) for c in data['rf_data']))
self.switchLongAddr = data['source_addr_long']
self.switchShortAddr = data['source_addr']
clusterId = (ord(data['cluster'][0])*256) + ord(data['cluster'][1])
if (clusterId == 0x13):
# This is the device announce message.
self.logging.info( 'Device Announce Message')
# First the Active Endpoint Request
payload1 = '\x00\x00'
self.zb.send('tx_explicit',
dest_addr_long = self.switchLongAddr,
dest_addr = self.switchShortAddr,
src_endpoint = '\x00',
dest_endpoint = '\x00',
cluster = '\x00\x05',
profile = '\x00\x00',
data = payload1
)
self.logging.info( 'sent Active Endpoint')
elif (clusterId == 0x8005):
# this is the Active Endpoint Response This message tells you
# what the device can do, but it isn't constructed correctly to match
# what the switch can do according to the spec.
self.logging.info( 'Active Endpoint Response')
# Now there are two messages directed at the hardware
# code (rather than the network code. The switch has to
# receive both of these to stay joined.
payload3 = '\x11\x01\xfc'
self.zb.send('tx_explicit',
dest_addr_long = self.switchLongAddr,
dest_addr = self.switchShortAddr,
src_endpoint = '\x00',
dest_endpoint = '\x02',
cluster = '\x00\xf6',
profile = '\xc2\x16',
data = payload3
)
payload4 = '\x19\x01\xfa\x00\x01'
self.zb.send('tx_explicit',
dest_addr_long = self.switchLongAddr,
dest_addr = self.switchShortAddr,
src_endpoint = '\x00',
dest_endpoint = '\x02',
cluster = '\x00\xf0',
profile = '\xc2\x16',
data = payload4
)
self.logging.info( 'Sent hardware join messages')
elif (clusterId == 0x0006):
# Match Descriptor Request;
# Now the Match Descriptor Response
payload2 = '\x00\x00\x00\x00\x01\x02'
self.zb.send('tx_explicit',
dest_addr_long = self.switchLongAddr,
dest_addr = self.switchShortAddr,
src_endpoint = '\x00',
dest_endpoint = '\x00',
cluster = '\x80\x06',
profile = '\x00\x00',
data = payload2
)
self.logging.info( 'Sent Match Descriptor')
elif (clusterId == 0xef):
clusterCmd = ord(data['rf_data'][2])
if (clusterCmd == 0x86):
power=ord(data['rf_data'][3]) + (ord(data['rf_data'][4]) * 256)
self.logging.debug("instantaneous power use: %dW" % power)
#push data to upload queue
q = QueueObject()
q.type = QueueObject.Power
q.data = power
q.timestamp = datetime.datetime.utcnow()
#.........这里部分代码省略.........
示例14: float
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
# Do other stuff in the main thread
while True:
try:
if not updated:
updated = 1
#ymin = float(min(ydata))-1
#ymax = float(max(ydata))+1
#plt.ylim([ymin,ymax])
line1.set_xdata(range(WINDOW_LEN))
line1.set_ydata(ydata1) # update the data
#fftdata = np.abs(np.fft.rfft(ydata))[1:]
#ymin = float(min(fftdata))-1
#ymax = float(max(fftdata))+1
#ax2.set_ylim([ymin,ymax])
line2.set_xdata(range(WINDOW_LEN))
line2.set_ydata(ydata2)
plt.draw() # update the plot
else: time.sleep(0.01)
except KeyboardInterrupt:
break
# halt() must be called before closing the serial
# port in order to ensure proper thread shutdown
zb.halt()
ser.close()
示例15: GNBot
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import halt [as 别名]
class GNBot(object):
valueTypes = { 0 : "reserved",
1 : "ledR_PWM",
2 : "ledG_PWM",
3 : "ledB_PWM",
4 : "motorL",
5 : "motorR",
6 : "tone",
7 : "noseHeater_PWM",
8 : "noseMax",# to be read
9 : "noseMin",# to be read
10 : "distMax",# to be read
11 : "distMin",# to be read
12 : "batteryMax",# to be read
13 : "batteryMin",# to be read
14 : "notone",
15 : "delay",
16 : "toneMs",
17 : "humidity",# to be read
18 : "temperature",# to be read
19 : "magnetometerX",# to be read
20 : "magnetometerY",# to be read
21 : "magnetometerZ",# to be read
22 : "button",# to be read
23 : "sampletime",
24 : "IMUyaw",# to be read
25 : "IMUpitch",# to be read
26 : "IMUroll",# to be read
27 : "avgSpeed",# to be read
28 : "avgLmotorInput",# to be read
29 : "avgRmotorInput",# to be read
30 : "IRdistanceCM",# to be read
31 : "targetAngle",
32 : "targetDistance"
}
valueTypesLookup = {}
gnbot_addresses = []
# Constructor
def __init__(self, callback_function, port='/dev/ttyUSB0', baud_rate=9600):
self._callback = callback_function
self._port = port
self._baud_rate = baud_rate
# Create reverse lookup table for value types
print("\nGNBot value types:")
print("CODE\t: VALUE")
print("-----------------")
for key in self.valueTypes.keys():
value = self.valueTypes[key]
self.valueTypesLookup[value] = key
print(str(key)+"\t: "+str(value))
print("")
# Open serial port
self._ser = serial.Serial(self._port, self._baud_rate)
self._zb = ZigBee(self._ser, escaped = True, callback=self._processCallback)
# Destructor
def halt(self):
self._zb.halt()
self._ser.close()
def createValue(self, valueTypeStr, val):
if val < 0: val += 2**16
char1 = chr(val >> 8)
char2 = chr(val & 0x00ff)
valTypeID = chr(self.valueTypesLookup[valueTypeStr])
return valTypeID+char1+char2
def sendPUTcommand(self, address, values):
rf_data = chr(0) # PUT command
rf_data += values# [struct.pack('b', v) for v in values]
self._zb.send("tx", dest_addr='\xFF\xFE', dest_addr_long=address, data=rf_data)
# Callback processing function
def _processCallback(self, datain):
if not ('source_addr_long' in datain.keys()) or not ('rf_data' in datain.keys()): return
data = datain['rf_data']
packetType = ord(data[0])
address = datain['source_addr_long']
if packetType == 0: # PUT
#print("Received: PUT")
raw_values_string = data[1:]
N_values = int(len(raw_values_string)/3)
values = {}
for i in range(N_values):
istart = i*3
valType = ord(raw_values_string[istart])
#value = ord(raw_values_string[istart+1])*256+ord(raw_values_string[istart+2])
#value = int(ord(raw_values_string[istart+1])<<8|ord(raw_values_string[istart+2]),16)
value = struct.unpack('H', raw_values_string[istart+2]+raw_values_string[istart+1])[0]
if not valType in self.valueTypes.keys():
print("WARNING! Unknown value type received: " + str(valType))
continue
#.........这里部分代码省略.........