本文整理汇总了Python中xbee.ZigBee.tx方法的典型用法代码示例。如果您正苦于以下问题:Python ZigBee.tx方法的具体用法?Python ZigBee.tx怎么用?Python ZigBee.tx使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类xbee.ZigBee
的用法示例。
在下文中一共展示了ZigBee.tx方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: pack
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
long_daddr = pack('>Q',eval(config.get('node','long_addr'))) # set 64-bit address here
print "parsed short_daddr=%s\n" % repr(short_daddr)
print "parsed long_daddr=%s\n" % repr(long_daddr)
ser = serial.Serial(config.get('modem', 'port'), 57600)
xb = ZigBee(ser,callback=cb,escaped=True,start_callback=scb)
xb.start()
print xb.at(command='ND')
if 0:
while True:
print "one"
for x in range(0xFF):
data = pack('BBBB', 0, x,x,x)
xb.tx( dest_addr = short_daddr , dest_addr_long = long_daddr, data = data )
time.sleep(0.1)
if 0:
print "foo"
data = pack('BBBB', 0, 0xff,0xff,0xff)
xb.tx( dest_addr = short_daddr, dest_addr_long = long_daddr, data = data )
print "use inify('adress') to dump address in format suitable for the .ini file\n"
示例2: XBeeWrapper
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
class XBeeWrapper(object):
"""
Helper class for the python-xbee module.
It processes API packets into simple address/port/value groups.
See http://code.google.com/r/xoseperez-python-xbee/
"""
default_port_name = 'serial'
serial = None
xbee = None
logger = None
buffer = dict()
def log(self, level, message):
if self.logger:
self.logger.log(level, message)
def disconnect(self):
"""
Closes serial port
"""
self.xbee.halt()
self.serial.close()
return True
def connect(self):
"""
Creates an Xbee instance
"""
try:
self.log(logging.INFO, "Connecting to Xbee")
self.xbee = ZigBee(self.serial, callback=self.process)
except:
return False
return True
def process(self, packet):
"""
Processes an incoming packet, supported packet frame ids:
0x90: Zigbee Receive Packet
0x92: ZigBee IO Data Sample Rx Indicator
"""
self.log(logging.DEBUG, packet)
if 'source_addr_long' in packet:
address = binascii.hexlify(packet['source_addr_long'])
#frame_id = int(packet['frame_id'])
id = packet['id']
if(id == "rx_io_data_long_addr"):
frame_id = 92
elif(id == "rx"):
frame_id = 90
# Data sent through the serial connection of the remote radio
if (frame_id == 90):
# Some streams arrive split in different packets
# we buffer the data until we get an EOL
self.buffer[address] = self.buffer.get(address,'') + packet['rf_data']
count = self.buffer[address].count('\n')
if (count):
lines = self.buffer[address].splitlines()
try:
self.buffer[address] = lines[count:][0]
except:
self.buffer[address] = ''
for line in lines[:count]:
line = line.rstrip()
try:
port, value = line.split(':', 1)
except:
value = line
port = self.default_port_name
self.on_message(address, port, value)
# Data received from an IO data sample
if (frame_id == 92):
for sample in packet['samples']:
self.log(logging.DEBUG, sample)
for port in sample.keys():
value = sample[port]
sys.stderr.write("Port:Val %s:%d " % (port, value))
if port[:3] == 'dio':
value = 1 if value else 0
self.on_message(address, port, value)
def on_message(self, address, port, value):
"""
Hook for outgoing messages.
"""
None
def toggle_port(self, address, port):
"""
Sends a message to a remote radio to set a pin HIGH, pause for a moment, then set it LOW
"""
txt_addr = address
#.........这里部分代码省略.........
示例3:
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
print "run..."
print ""
print "current status:"
zb.send('at', command='ID')
zb.send('at', command='SH')
zb.send('at', command='SL')
zb.send('at', command='MY')
print ""
time.sleep(1)
print ""
if not IS_HUB:
print "edge node - send frame to %s" % HUB_ADDR
zb.tx(dest_addr_long=HUB_ADDR, dest_addr=BCAST_ADDR, data="PING")
else:
print "hub node - waiting for data"
while True:
try:
time.sleep(2)
except KeyboardInterrupt:
break
zb.halt()
# try:
# print "run..."
# dispatch.run()
# except KeyboardInterrupt:
示例4: monitorCasa
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
#.........这里部分代码省略.........
except:
print "error dweepy 4"
########## alarmas #########
## alertar por mensaje si alarma
if(globales['alarma_trip'] and not(globales['alarma_enviada'])):
encenderGrupo(luces['puerta'])
encenderGrupo(luces['estudiof'])
try:
po_client.send_message("Alarma disparada", title="Alarma entrada")
globales['alarma_enviada'] = True
except:
print "error envio"
globales['alarma_enviada'] = True
if(globales['alarma_gas'] and not(globales['alarma_gas_enviada'])):
po_client.send_message("Alarma de gas en "+lugar_gas+", lectura: " + lectura, title="Alarma gas")
globales['alarma_gas_enviada'] = True
try:
sonos.volume = 80
texto_voz('Alarma de gas en ' + lugar_gas)
#time.sleep(8)
#decir('Alarma de gas en ' + lugar_gas)
#sonos.volume = 40
except:
print "Error decir alarma de gas"
############ temperatura #########
# activar aire si temperatura en tv es alta y hay alguien presente
if(globales['activo'] and temperaturas['tv'] >= 24.5 and (not globales['ac_encendido']) and globales['auto_ac']):
if(movimiento_st['tv'] > 0.4):
xbee.tx(dest_addr_long='\x00\x13\xa2\x00\x40\xbf\x96\x2c',dest_addr='\x40\xb3', data=b'1')
globales['ac_encendido'] = True
actualizar_global('ac',int(globales['ac_encendido']), con2)
if(temperaturas['tv'] < 22 and globales['ac_encendido'] and globales['auto_ac']):
globales['ac_encendido'] = False
xbee.tx(dest_addr_long='\x00\x13\xa2\x00\x40\xbf\x96\x2c',dest_addr='\x40\xb3', data=b'1')
actualizar_global('ac',int(globales['ac_encendido']), con2)
##### chapa cerrar por seguridad #####
if(chapa_por_cerrar and time.time()-tiempo_cerrar_chapa > 60*3):
chapa(True, xbee=xbee)
chapa_por_cerrar = False
globales['chapa'] = True
# procesar comandos pendientes
if(time.time() - tiempo_comandos > 1.0):
tiempo_comandos = time.time()
concom = lite.connect('/Volumes/mmshared/bdatos/comandos.db')
actuales = {}
with concom:
c = concom.cursor()
c.execute('SELECT * FROM pendientes')
actuales = c.fetchall()
#print actuales
c.executemany('DELETE FROM pendientes WHERE comando=? AND params=?',actuales)
concom.close()
#print actuales
if(len(actuales)>0):
for comando in actuales:
示例5: LedRing
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
class LedRing():
COMMANDS = {
"full": b'\x00',
"color": b'\x01',
"pos": b'\x02',
"jump": b'\x03',
"level": b'\x04',
"level_red": b'\x05',
"level_green": b'\x06',
"level_blue": b'\x07',
"red": b'\x08',
"green": b'\x09',
"blue": b'\x0a',
"rot_left": b'\x0b',
"rot_right": b'\x0c',
"rot_off": b'\x0d',
"set_fade": b'\x0e',
"fade_off": b'\x0f',
"brightness": b'\x10',
"use_gamma": b'\x11',
"gamma_off": b'\x12',
}
REQUEST = b'\x01'
RECEIVED_COMMAND = b'\x02'
def __init__(self, serial, addr, addr_long):
self.frame_consumer = FrameConsumer()
self.xbee = ZigBee(serial, callback=self.frame_consumer.receive_frame, escaped=True)
self.addr = addr
self.addr_long = addr_long
self.frame_cycle = itertools.cycle(range(1, 255))
def _tx(self, command, data=None):
cmd = self.COMMANDS[command]
if not data is None:
cmd = cmd + data
frame_id = self.frame_cycle.next()
print "## sending " + binascii.hexlify(cmd) + " len: " + str(len(cmd)) + " to node " + binascii.hexlify(
self.addr_long)
wait_response = WaitForResponse(self.frame_consumer, 60, frame_id)
wait_confirm = WaitForConfirm(self.frame_consumer, 60, self.RECEIVED_COMMAND + self.COMMANDS[command])
wait_confirm.start()
wait_response.start()
self.xbee.tx(
frame_id=chr(frame_id),
dest_addr_long=self.addr_long,
dest_addr=self.addr,
data=cmd
)
wait_response.join(60)
print "response " + str(wait_response.result)
if wait_response.exception:
raise wait_response.exception
wait_confirm.join(60)
print "confirm " + str(wait_confirm.result)
if wait_confirm.exception:
raise wait_confirm.exception
def rotate_counter_clockwise(self):
self._tx("rot_right")
def rotate_clockwise(self):
self._tx("rot_left")
def rotate_off(self):
self._tx("rot_off")
def set_red(self):
self._tx("red")
def set_green(self):
self._tx("green")
def set_blue(self):
self._tx("blue")
def set_level_red(self, level):
self._tx("level_red", chr(level))
def set_level_green(self, level):
self._tx("level_green", chr(level))
def set_level_blue(self, level):
self._tx("level_blue", chr(level))
def set_level_color(self, color, level):
self._tx("level", binascii.unhexlify(binascii.hexlify(chr(level)) + color))
def set_color(self, r, g, b):
self._tx("color", chr(r) + chr(g) + chr(b))
def set_position(self, pos):
self._tx("pos", chr(pos))
#.........这里部分代码省略.........
示例6: __init__
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
class XbeeSerial:
XbeeModules = []
Cues = {}
fireQueue = Queue.Queue(1)
CuesLock = threading.Lock()
txEvent = threading.Event()
def __init__(self, XbeeFile, ser, cueFile):
self.txEvent.set()
f = open(cueFile, 'r')
for line in f:
line = line.strip().split(',')
if len(line) == 2:
self.Cues[int(line[1])] = {'name': line[0], 'adc': 0}
f = open(XbeeFile, 'r')
for line in f:
line = line.strip().split(',')
if len(line) == 2:
line[0] = struct.pack('>Q', int(line[0], 16))
line[1] = struct.pack('>H', int(line[1], 16))
self.XbeeModules.append((line[0], line[1]))
self.xbee = ZigBee(ser, callback=self.callback_data)
t = threading.Thread(target = self.loop)
t.start()
def loop(self):
moduleStatus = 0
while True:
self.txEvent.wait(3)
try:
fireCue = self.fireQueue.get(False)
except Queue.Empty:
fireCue = -1
if fireCue < 0:
if moduleStatus >= len(self.XbeeModules):
moduleStatus = 0
self.updateStatus(moduleStatus)
moduleStatus += 1
else:
self.fire(fireCue)
def addFire(self, cue):
self.fireQueue.put(cue)
def fire(self, cue):
num = cue % 20
module = cue / 20
if module >= len(self.XbeeModules):
return
print('%s - Fireing cue: %d' % (datetime.now(), cue))
self.tx(module, '[L%d]' % num)
def updateStatus(self, module):
self.tx(module, '[S]')
def getStatus(self):
with self.CuesLock:
return self.Cues
def tx(self, module, data):
self.txEvent.clear()
self.xbee.tx(dest_addr_long = self.XbeeModules[module][0], dest_addr=self.XbeeModules[module][1], data = data)
def callback_data(self, data):
if data['id'] == 'rx':
self.txEvent.set()
for (i, module) in enumerate(self.XbeeModules):
if data['source_addr_long'] == module[0] and data['source_addr'] == module[1]:
moduleNum = i
break;
else:
print('%s - unknown module' % datetime.today())
return
if data['rf_data'][0] != '[':
status = data['rf_data'].split(',')
with self.CuesLock:
for i in range(0, len(status), 2):
cue = int(status[i]) + 20 * moduleNum
if cue in self.Cues:
self.Cues[cue]['adc'] = status[i + 1]
print('%s - status from module %d' % (datetime.now(), moduleNum))
else:
print('%s - response from module %d' % (datetime.now(), moduleNum))
示例7: print_data
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
#!/usr/bin/env python
from xbee import ZigBee
import serial
import time
def print_data(data):
print data
ser = serial.Serial('/dev/tty.usbserial-AH0014VV', 9600)
xbee = ZigBee(ser, callback=print_data)
xbee.tx(
dest_addr_long='\x00\x13\xA2\x00\x40\x31\x56\x46',
dest_addr = b'\x10\x52',
data=b'\x01',
)
while True:
try:
time.sleep(0.001)
except KeyboardInterrupt:
break
xbee.halt()
ser.close()
示例8: float
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
dt = nowtime-starttime
result = dt.seconds + float(dt.microseconds)/1000000
#####################################################################################データ保存
buffer_co2 = [result,co2]
buffer_compass = [result,compass]
buffer_temperature = [result,temperature]
buffer_humidity = [result,humidity]
csvWriter = csv.writer(f1)
csvWriter.writerow(buffer_co2)
csvWriter = csv.writer(f2)
csvWriter.writerow(buffer_compass)
csvWriter = csv.writer(f3)
csvWriter.writerow(buffer_temperature)
csvWriter = csv.writer(f4)
csvWriter.writerow(buffer_humidity)
#####################################################################################データ送信
xbee.tx(dest_addr_long=COORDINATOR_ADRR,dest_addr = "\xFF\xFE",data=data)
pressed_keys = pygame.key.get_pressed()
for event in pygame.event.get():
if event.type == QUIT:
sys.exit()
if event.type == KEYDOWN: # キーを押したとき
# ESCキーならスクリプトを終了
if event.key == K_ESCAPE:
sys.exit()
示例9: int
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
simplex = int(round(centers[key][1]))
simpley = int(round(centers[key][0]))
# grab orientation and convert to radians.
orientation = fiducialDict[key][14] * (math.pi / 180)
print orientation
# log orientation to file for debugging.
testout.write("orientation: {0}\n".format(orientation))
# send information to the specified xbee in the following format:
# "-{targetx},{targety},{currentx},{currenty},{orientation} "
# the '-' at the beginning is to simplify parsing on the arduino side.
# orientation is multiplied by 10000 here and later divided by
# 10000 and cast by a float to work around problems with
# parsing floats from serial streams on the arudino.
xbee.tx(dest_addr_long=DEST_ADDR_LONG, dest_addr=DEST_ADDR,
data="-{0},{1},{2},{3},{4}".format(100,100,
simplex, simpley, (10000 * orientation)))
time.sleep(.1)
# this exception is generally triggered when no fiducials are tracked
except KeyError:
# on linux change the system call to 'clear'
os.system('cls')
print "no fiducial in vision"
time.sleep(1)
os.system('cls')
pass
# this exception is thrown when ctrl-c is pressed, and it ends the program
except KeyboardInterrupt:
print "all done"
break
示例10: ZigBee
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
# init xbee
ser = serial.Serial(commandLineArgs['usb'], 115200)
xbee = ZigBee(ser, escaped=True, callback=dumping)
# Go
logging.INFO('Queen active')
while True:
try:
while not comm.Iprobe(source = MPI.ANY_SOURCE, tag = MPI.ANY_TAG):
time.sleep(0.001)
data = comm.recv(source = MPI.ANY_SOURCE, tag = MPI.ANY_TAG, status = status)
tag = status.Get_tag()
xbee.tx(dest_addr_long=bytes(data[0]), dest_addr = bytes(data[1]), data=bytes([tag]))
ser.flush()
except KeyboardInterrupt:
break
# close it, otherwise you get errors when shutting down
xbee.halt()
ser.close()
logging.info('Stopped')
logging.info('====================================')
elif rank == 1:
from guard import guard
guard_bee = guard(commandLineArgs['url'], comm)
logging.debug('Guard running')
guard_bee.routine()
示例11: XBeeInterface
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
class XBeeInterface(object):
"""
Interfaces between an XBee connected through a serial port and messages
passed through stdin/stdout. Uses a simple JSON protocol to encode message
parameters.
"""
def __init__(self, port, baud, escaped):
self.serial_port = Serial(port, baud)
self.xbee = ZigBee(self.serial_port, escaped=escaped)
# Reopen stdin/stdout in line-buffered mode
self.stdin = os.fdopen(sys.stdin.fileno(), 'r', 1)
self.stdout = os.fdopen(sys.stdout.fileno(), 'w', 1)
# Associate each file descriptor with handler methods
self.handlers = {
self.serial_port.fileno(): (self.read_frame, self.on_frame),
self.stdin.fileno(): (self.read_message, self.on_message)
}
# Turn on non-blocking IO
for fd in self.handlers.keys():
fcntl.fcntl(fd, fcntl.F_SETFL, os.O_NONBLOCK)
def run(self):
# Send an AT command to trigger a response from the module
self.xbee.at(command='NI')
response = self.xbee.wait_read_frame()
log.info('Network identifier is "%s"', response['parameter'])
while True:
# do non-blocking reading from stdin and serial port
r, w, x = select.select(self.handlers.keys(), [], [])
for fd in r:
read_handler, data_handler = self.handlers[fd]
data = read_handler()
# read handlers return None if message is gimped
if data is not None:
data_handler(data)
def read_frame(self):
""" Read an entire frame from the serial connection and return it """
try:
return self.xbee.wait_read_frame()
except ValueError as e:
log.warning('error in packet data: %s', e)
return None
except SerialException as e:
log.error('error reading serial frame: %s', e)
raise IOError("Error reading from serial port")
def read_message(self):
""" Read a line from stdin and parse it as JSON """
try:
line = self.stdin.readline()
return json.loads(line)
except ValueError as e:
log.error('error decoding message: %s', e)
return None
def json_message(self, data):
""" Write a JSON string to stdout, using latin1 encoding to keep binary
data intact """
json_str = json.dumps(data, encoding='latin1')
self.stdout.write(json_str + '\n')
def on_message(self, message):
log.info('Message received from stdin: %s', message)
try:
# delegate to another method specified by action
action = '_'.join(('do', message['action']))
if not hasattr(self, action):
return log.error('Unknown action "%s"', message['action'])
getattr(self, action)(message)
except KeyError as e:
return log.error('Message is missing "%s"', e.message)
def do_send(self, message):
""" Sends a transmit request to the module """
# encode as latin1 to get back byte string
address, data, frame_id = (
message['address'].encode('latin1'),
message['data'].encode('latin1'),
message.get('frame_id', u'\x01').encode('latin1'))
try:
self.xbee.tx(data=data, frame_id=frame_id,
dest_addr_long=address, dest_addr='\xFF\xFE')
except Exception as e:
return log.error('Failed to send transmit request: %s', e)
def do_discover(self, message):
frame_id = message.get('frame_id', u'\x01').encode('latin1')
#.........这里部分代码省略.........
示例12: OrderedDict
# 需要导入模块: from xbee import ZigBee [as 别名]
# 或者: from xbee.ZigBee import tx [as 别名]
class XbeeSerial:
XbeeModules = OrderedDict()
#Cues = {}
#fireQueue = Queue.Queue(1)
ModulesLock = threading.Lock()
#CuesLock = threading.Lock()
#txEvent = threading.Event()
def __init__(self, ser):
#self.txEvent.set()
#f = open(cueFile, 'r')
#for line in f:
#line = line.strip().split(',')
#if len(line) == 2:
#self.Cues[int(line[1])] = {'name': line[0], 'adc': 0}
#f = open(XbeeFile, 'r')
#for line in f:
#line = line.strip().split(',')
#if len(line) == 2:
#line[0] = struct.pack('>Q', int(line[0], 16))
#line[1] = struct.pack('>H', int(line[1], 16))
#self.XbeeModules.append((line[0], line[1]))
self.xbee = ZigBee(ser, callback=self.callback_data)
#t = threading.Thread(target = self.loop)
#t.start()
#def loop(self):
#moduleStatus = 0
#while True:
#self.txEvent.wait(3)
#try:
#fireCue = self.fireQueue.get(False)
#except Queue.Empty:
#fireCue = -1
#if fireCue < 0:
#pass
#if moduleStatus >= len(self.XbeeModules):
# moduleStatus = 0
#self.updateStatus(moduleStatus)
#moduleStatus += 1
#else:
#self.fire(fireCue)
def initialize(self):
with self.ModulesLock:
self.XbeeModules = OrderedDict()
self.xbee.at(command = 'ND')
return {'message': 'Initializing...'}
def getBoardInfo(self, addr_long, addr):
#print('Getting board info {0} {1}'.format(addr_long, addr))
self.tx_addr(addr_long, addr, 'i')
#def addFire(self, cue):
# self.fireQueue.put(cue)
def fire(self, cue):
with self.ModulesLock:
for i, (board_id, (addr_long, addr, num_cues)) in enumerate(self.XbeeModules.iteritems()):
if cue < num_cues:
board = board_id
break
else:
cue -= num_cues
else:
return
print('%s - Fireing cue: %d on board: %d' % (datetime.now(), cue, board))
self.tx_board(board, 'f%c' % cue)
#def getStatus(self):
#with self.CuesLock:
#return self.Cues
def getStatus(self):
cues=[]
with self.ModulesLock:
for i, (board_id, (addr_long, addr, num_cues)) in enumerate(self.XbeeModules.iteritems()):
for cue in range(0, num_cues):
cues.append({'name': 'Board: %d, Cue: %d' % (board_id, cue), 'adc': 500});
return cues
def tx_board(self, board, data):
with self.ModulesLock:
self.tx_addr(self.XbeeModules[board][0], self.XbeeModules[board][1], data)
def tx_addr(self, addr_long, addr, data):
#self.txEvent.clear()
self.xbee.tx(dest_addr_long = addr_long, dest_addr = addr, data = data)
def callback_data(self, data):
if data['id'] == 'rx':
if len(data['rf_data']) > 0:
if data['rf_data'][0] == 'I' and len(data['rf_data']) == 3:
#print('board_id: {0} 64: {1} 16: {2} cues: {3}'.format(ord(data['rf_data'][1]), data['source_addr_long'], data['source_addr'], ord(data['rf_data'][2])))
with self.ModulesLock:
self.XbeeModules[ord(data['rf_data'][1])] = (data['source_addr_long'], data['source_addr'], ord(data['rf_data'][2]))
self.XbeeModules = OrderedDict(sorted(self.XbeeModules.items()))
#print(self.XbeeModules)
#else:
#.........这里部分代码省略.........