def main(): print(" +----------------------------------------------+") print(" | XBee Python Library Handle IO Samples Sample |") print(" +----------------------------------------------+\n") device = XBeeDevice(PORT, BAUD_RATE) try: device.open() # Obtain the remote XBee device from the XBee network. xbee_network = device.get_network() remote_device = xbee_network.discover_device(REMOTE_NODE_ID) if remote_device is None: print("Could not find the remote device") exit(1) # Set the local device as destination address of the remote. remote_device.set_dest_address(device.get_64bit_addr()) remote_device.set_io_configuration(DIGITAL_LINE, IOMode.DIGITAL_IN) remote_device.set_io_configuration(ANALOG_LINE, IOMode.ADC) # Enable periodic sampling every IO_SAMPLING_RATE seconds in the remote device. remote_device.set_io_sampling_rate(IO_SAMPLING_RATE) # Enable DIO change detection in the remote device. remote_device.set_dio_change_detection({DIGITAL_LINE}) # Register a listener to handle the samples received by the local device. def io_samples_callback(sample, remote, time): print("New sample received from %s - %s" % (remote.get_64bit_addr(), sample)) device.add_io_sample_received_callback(io_samples_callback) input() finally: if device is not None and device.is_open(): device.close()
if (io_sample.get_digital_value(x) == IOValue.HIGH): IOData[faultMap[x]] = 'true' any_fault = 'true' else: IOData[faultMap[x]] = 'false' IOData['any_fault'] = any_fault print('IOData: ', IOData) #finally, put everything together and publish the data to thingsboard turbineName = addr2name[str(remote_xbee.get_64bit_addr( ))] #find the name of the turbine that sent this message print(turbineName) message = {turbineName: IOData} print(message) MQTT.publish(topicAttr, json.dumps(message), qos=1, retain=True) xbee = XBeeDevice(localXBeePort, 9600) xbee.open() try: xbee.add_data_received_callback( data_receive_callback ) # Subscribe to data message reception (for power pulse count data). xbee.add_io_sample_received_callback( io_sample_callback) # Subscribe to IO samples reception. print("Waiting for data...\n") input() finally: if xbee is not None and xbee.is_open(): xbee.close()
def main(): print("Power Up Timer! Looking for coordinator XBee on port " + PORT) localDevice = XBeeDevice(PORT, BAUD_RATE) print("localDevice = %s", localDevice) try: localDevice.open() print("Opened localDevice = ", localDevice) # Obtain the remote XBee localDevice from the XBee network. xbee_network = localDevice.get_network() print("Found network: ", xbee_network) print("Looking for remoteDevice named ", REMOTE_NODE_ID) remoteDevice = xbee_network.discover_device(REMOTE_NODE_ID) if remoteDevice is None: print("Could not find the remote device named " + REMOTE_NODE_ID) exit(1) print("Found remoteDevice = ", remoteDevice) # Set the local localDevice as destination address of the remote. remoteDevice.set_dest_address(localDevice.get_64bit_addr()) remoteDevice.set_io_configuration(LEFT, IOMode.DIGITAL_IN) remoteDevice.set_io_configuration(RIGHT, IOMode.DIGITAL_IN) # Enable periodic sampling every IO_SAMPLING_RATE seconds in the remote device. remoteDevice.set_io_sampling_rate(IO_SAMPLING_RATE) # Enable DIO change detection in the remote device. remoteDevice.set_dio_change_detection({LEFT}) remoteDevice.set_dio_change_detection({RIGHT}) scaleLeft = Scale() scaleRight = Scale() # Register a listener to handle the samples received by the local device. def io_samples_callback(sample, remote, time): try: #print("New sample from %s - %s at %s" % (remote.get_node_id(), sample, str(time))) newState = sample.get_digital_value(LEFT) if (scaleLeft.state == TIMER_STOPPED): # timer is stopped if (sample.get_digital_value(LEFT) == SWITCH_CLOSED): #print("Timer was stopped, switch is now closed.") scaleLeft.start = time scaleLeft.state = TIMER_RUNNING else: # timer is running if (sample.get_digital_value(LEFT) == SWITCH_OPEN): #print("Timer was running, switch is now open.") scaleLeft.state = TIMER_STOPPED elapsedSec = time - scaleLeft.start scaleLeft.total += elapsedSec print( "Left side was closed for %.1f, total time is %.1f sec" % (elapsedSec, scaleLeft.total)) newState = sample.get_digital_value(RIGHT) if (scaleRight.state == TIMER_STOPPED): # timer is stopped if (sample.get_digital_value(RIGHT) == SWITCH_CLOSED): #print("Timer was stopped, switch is now closed.") scaleRight.start = time scaleRight.state = TIMER_RUNNING else: # timer is running if (sample.get_digital_value(RIGHT) == SWITCH_OPEN): #print("Timer was running, switch is now open.") scaleRight.state = TIMER_STOPPED elapsedSec = time - scaleRight.start scaleRight.total += elapsedSec print( "Right side was closed for %.1f, total time is %.1f sec" % (elapsedSec, scaleRight.total)) except Exception as ex: print("caught in callback: ", ex) print("sys.exc_info(): ", sys.exc_info()) print("Registering callback on ", remoteDevice) localDevice.add_io_sample_received_callback(io_samples_callback) # Wait for an input line to exit print("Press enter to exit") input() except BaseException as ex: print("Caught something: ", ex) finally: if localDevice is not None and localDevice.is_open(): localDevice.close()
class RFHandler: def __init__(self, PORT, BAUD_RATE): self.baseXbee = XBeeDevice(PORT, BAUD_RATE) self.baseXbee.open() self.remoteAccessories = {} self.accessoryCallbacks = {} self.baseXbee.add_io_sample_received_callback(self.ioSampleCallback) def stop(self): logger.info("Stopping RFHandler") self.baseXbee.close() def addAccessoryCallback(self, accessoryName, callbackFct): self.accessoryCallbacks[accessoryName] = callbackFct def addRemoteAccessory(self, accessoryName, xbeeAddressString): self.remoteAccessories[accessoryName] = RemoteXBeeDevice( self.baseXbee, XBee64BitAddress.from_hex_string(xbeeAddressString)) def removeRemoteAccessory(self, accessoryName): del self.remoteAccessories[accessoryName] def getAccessoriesNames(self): return remoteAccessories.keys() def getAccessoryNameFromXbeeDevice(self, remoteXbee): for key, value in self.remoteAccessories.items(): if remoteXbee == value: return key return None def setDigitalConfigurationOfAccessoryPin( self, accessoryName, pin, config): #TODO : CATCH TIMEOUT ERRORS sent = 0 retry = 0 while not sent and retry < 5: try: self.remoteAccessories[accessoryName].set_io_configuration( pin, config) sent = 1 except TimeoutException: logger.debug( "TimeOutException in setDigitalConfigurationOfAccessoryPin" ) retry += 1 def getInputStateOfAccessoryPin(self, accessoryName, pin): #TODO : CATCH TIMEOUT ERRORS retry = 0 while retry < 5: try: return self.remoteAccessories[accessoryName].get_dio_value(pin) except TimeoutException: retry += 1 logger.debug("TimeOutException in getInputStateOfAccessoryPin") def getDigitalConfigurationOfAccessoryPin( self, accessoryName, pin): #TODO : CATCH TIMEOUT ERRORS retry = 0 while retry < 5: try: return self.remoteAccessories[ accessoryName].get_io_configuration(pin) except TimeoutException: retry += 1 logger.debug("TimeOutException in getInputStateOfAccessoryPin") def ioSampleCallback(self, ioSample, remoteXbee, sendTime): currentAccessoryName = self.getAccessoryNameFromXbeeDevice(remoteXbee) if currentAccessoryName in self.accessoryCallbacks: self.accessoryCallbacks[currentAccessoryName](ioSample, sendTime)
def main(): print(" +----------------------------------------------+") print(" | XBee Python Library Handle IO Samples Sample |") print(" +----------------------------------------------+\n") device = XBeeDevice(port, baud_rate) try: device.open() # Obtain the remote XBee device from the XBee network. xbee_network = device.get_network() remote_device = xbee_network.discover_device('REMOTO_2') if remote_device is None: print("Could not find the remote device") exit(1) # Set the local device as destination address of the remote. remote_device.set_dest_address(device.get_64bit_addr()) remote_device.set_io_configuration(IOLINE_IN_3 , IOMode.ADC) remote_device.set_io_configuration(IOLINE_IN_2 , IOMode.ADC) remote_device.set_io_configuration(IOLINE_IN_1, IOMode.ADC) remote_device.set_io_configuration(IOLINE_IN_0, IOMode.ADC) # Enable periodic sampling every IO_SAMPLING_RATE seconds in the remote device. remote_device.set_io_sampling_rate(IO_SAMPLING_RATE) def parse_sample(sample): for i in range (0,4): sample=str(sample).replace('IOLine.DIO'+str(i)+'_AD'+str(i)+':',"") sample = sample.replace('[','') sample = sample.replace (']','') sample = sample.replace('{','') sample = sample.replace('}','') sample=sample.split(',') for i in range (0,len(sample)): sample[i]=int(sample[i]) return sample def get_voltaje(remote): vcc= remote.get_parameter("%V") vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16) return vcc # Register a listener to handle the samples received by the local device. def io_samples_callback(sample, remote, time): print("New sample received from %s - %s" % (remote.get_64bit_addr(), sample)) vcc = remote.get_parameter("%V") vcc = int(utils.hex_to_string(vcc).replace(' ', ''), 16) print(vcc) raw_values = parse_sample (sample) temp_1= ntc10k_calculate_temp(raw_values[0],3300) print(temp_1) device.add_io_sample_received_callback(io_samples_callback) input() finally: if device is not None and device.is_open(): device.del_io_sample_received_callback(io_samples_callback) device.close()
print("IO sample:") print("IO sample received at time %s." % str(send_time)) print("IO sample:") print(str(io_sample)) print(str(remote_xbee)) print(type(remote_xbee)) print(remote_xbee.get_64bit_addr()) print(type(remote_xbee.get_64bit_addr())) print(remote_xbee.get_node_id()) b = io_sample.get_digital_value(IOLine.DIO1_AD1) print(b) print(type(b)) if (b == IOValue.LOW): print('Hi!') xbee.add_data_received_callback(data_receive_callback) # Subscribe to IO samples reception. xbee.add_io_sample_received_callback(io_sample_callback) print("Waiting for data...\n") input() finally: print('finally') stop = True if xbee is not None and xbee.is_open(): print('closing xbee') xbee.close() print('xbee closed')
class masterXBee: ''' Class for the local XBee device, containing all connected devices and their pins in a dictionary port = used COM/tty port baud = used baud rate callback_handler: function you want to handle callbacks! callback_handler should take two arguments: sensor(str) = name of sensor value(str) = value of sensor (HIGH or LOW) ''' # functional devices dictionary devices = {} # sensor polling state polling = False # flask readable device data dictionary devicedata = {} # flask readable sensor data dictionary sensordata = {} def __init__(self, port, baud, callback_handler=None): # Semaphore for XBee action, limits acces to single user at a time. # This is needed for alternating between polling values from sensors and receiving callbacks self.sema = Semaphore() # instantiate local XBee device print("Opening local device", port, baud) self.localXB = XBeeDevice(port,baud) self.localXB.open() # find devices in network, store in devices dictionary. Keys are device 64bit addresses devices = self.getNetworkDevices() # write flask readable device dict self.devicedata = self.get_device_data() # create sensor data dict self.sensordata = self.get_sensor_data() # set local device to receive IO callbacks self.localXB.set_dest_address(self.localXB.get_64bit_addr()) self.localXB.add_io_sample_received_callback(self.io_sample_callback) self.callback_function = callback_handler #clear previous monitored IO lines: for dev in self.devices: self.devices[dev].xbee.set_dio_change_detection(None) def getNetworkDevices(self): """ Returns devices in the network of given local xBee device, including the local device: devices = dict of all the devices in locals network and their sensors! devices : { "device ID" : <XBeeDev object> sensors = { "NAME/TYPE" : { "line" : IOLine, "mode" : IOMode, } } } """ print("Getting a list of network devices...", end="") # Get devices in local xbee's network! self.localXB.send_data_broadcast("Getting a list of everyone :D") network = self.localXB.get_network() network.start_discovery_process() # wait for network discovery to finish... while network.is_discovery_running(): time.sleep(.5) print(".",end="") networkDevices = network.get_devices() networkDevices.insert(0, self.localXB) # loop through found network devices and create a XBeeDev object for each # containing device type and connected sensors print("\nFound devices and sensors:") for device in networkDevices: print(device) # new xbee device with its pins n stuff XBeeDevobj = XBeeDev(device) # add it to master class's device dict self.devices.update({XBeeDevobj.dvcID : XBeeDevobj}) return networkDevices
class Commander: def __init__(self, comPort): self.device = XBeeDevice(comPort, BAUD_RATE) self.network = None self.peers = [] self.lock = Lock() self.run = True self.device.open() self.code = CODE self.on_success = None self.on_error = None logging.info("Commander address: {}".format( self.device.get_64bit_addr())) def set_on_error(self, callback): self.on_error = callback def set_on_success(self, callback): self.on_success = callback @asyncio.coroutine def discover_peer(self): """ Search other connected device to the same Zigbee network """ def push_peer(conn): peer = Peer(conn) if peer not in self.peers: logging.info("New peer: {}".format(peer)) self.lock.acquire() self.peers.append(peer) self.lock.release() if self.network is None: self.network = self.device.get_network() self.network.set_discovery_timeout(25.5) self.network.clear() self.network.add_device_discovered_callback(push_peer) while self.run: logging.info("running network scan...") try: self.network.start_discovery_process() while self.network.is_discovery_running(): yield from asyncio.sleep(1) except: pass yield from asyncio.sleep(60) def light_red(self): self.lock.acquire() for peer in self.peers: peer.light_red() self.lock.release() def light_blue(self): self.lock.acquire() for peer in self.peers: peer.light_blue() self.lock.release() def light_green(self): self.lock.acquire() for peer in self.peers: peer.light_green() self.lock.release() def listen_remote(self): def data_recv_callback(msg): logging.info("[{}] {}".format(msg.remote_device.get_64bit_addr(), msg.data.decode())) def samples_recv_callback(sample, remote, time): remote = Peer(remote) def check(btn): if len(self.code) > 0 and self.code[0] == btn: self.code.pop() else: self.code = CODE remote.light_red() self.on_error() logging.info("[{}] {}".format(remote.get_addr(), sample)) if sample.get_digital_value(BTN_ONE) == IOValue.HIGH: check(BTN_ONE) elif sample.get_digital_value(BTN_TWO) == IOValue.HIGH: check(BTN_TWO) elif sample.get_digital_value(BTN_THREE) == IOValue.HIGH: check(BTN_THREE) if len(self.code) == 0: self.code = CODE remote.light_green() self.on_success() self.device.add_data_received_callback(data_recv_callback) self.device.add_io_sample_received_callback(samples_recv_callback) def __del__(self): for peer in self.peers: peer.stop_all_task() if self.device.is_open(): self.device.close()
def main(): def publish_callback(result, status): pass pubnub.publish().channel('myocarta_ui').message( ["> Launching myocarta Beta Version"]). async (publish_callback) time.sleep(0.7) all_connected = True device = XBeeDevice(PORT, BAUD_RATE) try: pubnub.publish().channel('myocarta_ui').message( [">> Launching home receiver module..."]). async (publish_callback) time.sleep(0.7) device.open() pubnub.publish().channel('myocarta_ui').message( [">>> Connecting to sensors..."]). async (publish_callback) time.sleep(0.7) xbee_network = device.get_network() for device_id in REMOTE_NODE_IDS: remote_device = xbee_network.discover_device(device_id) if remote_device is None: print("ERROR: Could not find remote devices with ID " + device_id) all_connected = False else: REMOTE_DEVICES.append(remote_device) while (not all_connected): response_1 = input( "Not all selected remote devices were connected; enter 'proceed' or 'abort' to continue." ) if response_1 == "proceed": print("Proceeding with connected devices.") all_connected = True if response_1 == "abort": print("ERROR: Aborting") exit(1) else: print("Input unrecognized. Please enter proceed or abort.") pubnub.publish().channel('myocarta_ui').message( [">>>> Configuring remote sensors..."]). async (publish_callback) i = 0 for rem in REMOTE_DEVICES: rem.set_dest_address(device.get_64bit_addr()) rem.set_io_configuration(ANALOG_LINES[i], IOMode.ADC) rem.set_io_sampling_rate(IO_SAMPLING_RATE) i += 1 MOVING_AVERAGES.append([]) print("Home module " + str(device.get_64bit_addr()) + " is connected to the following addresses:") for rem in REMOTE_DEVICES: print(str(rem.get_64bit_addr()) + " ") pubnub.publish().channel('myocarta_ui').message([ ">>>>> Launch successful. Starting data collection." ]). async (publish_callback) time.sleep(0.7) pubnub.publish().channel('myocarta_ui').message( ["| myocarta |"]). async (publish_callback) device.add_io_sample_received_callback(io_samples_callback) input() print(" | Closing MyoCarta V2 07/25/18 |") finally: if device is not None and device.is_open(): device.close()