def handle_zha_message(message): frc, tsn, command_id, args, data = zha.deserialize_frame( message['cluster'], message['payload']) # print(frc, tsn, command_id, args, data) if message['cluster'] == 6: # on off switch relay_id = message['dest_ep'] - 0xc0 if frc.frame_type == zha.FrameType.CLUSTER_COMMAND: cmd_string = zha.on_off_server_commands[command_id] global relay_state if command_id == 0: relay_state &= ~(1 << relay_id) elif command_id == 1: relay_state |= (1 << relay_id) set_relays() print('executing {} against relay_id {}'.format( cmd_string, relay_id)) publish_relay_state(relay_id) elif frc.frame_type == zha.FrameType.GLOBAL_COMMAND: if command_id == 0: response_frame = zha.serialize_attribute_response( tsn, relay_id, args[0]) xbee.transmit(message['sender_eui64'], response_frame, source_ep=message['source_ep'], dest_ep=message['dest_ep'], cluster=zdo.ZDOCmd.Simple_Desc_rsp, profile=message['profile']) elif command_id == 0x0b: # default response to report attributes print('Attribute report resulted in response status {}'.format( args[1]))
def transmit_data(dest, msg, retries=3): for i in range(1, retries + 1): try: xbee.transmit(dest, msg) break except OSError as e: print("Could not transmit data (%d/%d): %s" % (i, retries, str(e)))
def handle_zdo_message(message): tsn, args = zdo.deserialize_frame(message['cluster'], message['payload']) print("ZDO request cluster {:04X}, args: ".format(message['cluster']), args) if message['cluster'] == zdo.ZDOCmd.Active_EP_req: if args[0] == xbee.atcmd('MY'): response_frame = zdo.serialize_frame( tsn, zdo.ZDOCmd.Active_EP_rsp, (zdo.Status.SUCCESS, ), (args[0], ), ([base_ep + r for r in range(relay_count)], )) xbee.transmit(message['sender_eui64'], response_frame, source_ep=message['source_ep'], dest_ep=message['dest_ep'], cluster=zdo.ZDOCmd.Active_EP_rsp, profile=message['profile']) elif message['cluster'] == zdo.ZDOCmd.Simple_Desc_req: if args[0] == xbee.atcmd('MY'): # n, t = param_schema(ZDOCmd.Simple_Desc_rsp, 2) # print(n, t) response_frame = zdo.serialize_frame( tsn, zdo.ZDOCmd.Simple_Desc_rsp, (zdo.Status.SUCCESS, ), (args[0], ), (args[1], 260, 0x0, 0x0, [0x6], [])) xbee.transmit(message['sender_eui64'], response_frame, source_ep=message['source_ep'], dest_ep=message['dest_ep'], cluster=zdo.ZDOCmd.Simple_Desc_rsp, profile=message['profile']) else: print("No handler for ZDO message:") print_message(message)
def _process_report(self, report_id, report_bytes): if report_id >= 0xF0: self._handle_control_report(report_id, report_bytes) return self._dbg("\tProcessing report:", reports[report_id]) if self._debug: outstr = "" idx = 0 for packet_byte in report_bytes: packet_index = idx if (packet_index % 4) == 0: outstr += "\nDBG::\t\t[0x{:02X}] ".format(packet_index) outstr += "0x{:02X} ".format(packet_byte) idx += 1 self._dbg(outstr) self._dbg("") if report_id in self._enabled_transmissions: try: xbee.transmit(self._target_64bit_address, report_bytes) except Exception as e: print("error sending") if report_id == BNO_REPORT_STEP_COUNTER: self._readings[report_id] = _parse_step_couter_report(report_bytes) return if report_id == BNO_REPORT_SHAKE_DETECTOR: shake_detected = _parse_shake_report(report_bytes) # shake not previously detected - auto cleared by 'shake' property try: if not self._readings[BNO_REPORT_SHAKE_DETECTOR]: self._readings[BNO_REPORT_SHAKE_DETECTOR] = shake_detected except KeyError: pass return if report_id == BNO_REPORT_STABILITY_CLASSIFIER: stability_classification = _parse_stability_classifier_report( report_bytes) self._readings[ BNO_REPORT_STABILITY_CLASSIFIER] = stability_classification return if report_id == BNO_REPORT_ACTIVITY_CLASSIFIER: activity_classification = _parse_activity_classifier_report( report_bytes) self._readings[ BNO_REPORT_ACTIVITY_CLASSIFIER] = activity_classification return sensor_data, accuracy = _parse_sensor_report_data(report_bytes) if report_id == BNO_REPORT_MAGNETOMETER: self._magnetometer_accuracy = accuracy if report_id == BNO_REPORT_ROTATION_VECTOR: self._readings[report_id] = report_bytes else: self._readings[report_id] = sensor_data
def main(): module = xbee.XBee() # Idle the radio. While the radio is idled, the radio cannot receive # transmissions and current draw is reduced. xbee.idle_radio(True) # register handle_rx_packet to be called whenever a packet is received. xbee.receive_callback(handle_rx_packet) # Send transmissions to the address configured by DH/DL dest_addr = xbee.atcmd("DH") + xbee.atcmd("DL") samples = [] # Since this application spends most of its time asleep, stopping # the application through the UART can be difficult. To make the # example easier to work with, it will only run for about a minute # instead of indefinitely. for _ in range(12): # Sleep for 5 seconds module.sleep_now(5000) # Upon waking, take a sample sample = read_sensor() samples.append(sample) print(" Sample: {}".format(sample)) if len(samples) == 4: # Once we have four samples, Send the samples to # the coordinator. Note that we don't have to call # xbee.idle_radio(True) to be able to do this--the radio is # enabled just long enough to send the transmission. print("Transmit samples: {}".format(samples)) xbee.transmit(dest_addr, str(samples)) # Clear the stored samples samples.clear() # If the server is ever going to send transmissions to the # end device, the end device needs to enable the radio at # some point, and the server needs to know when that is. For # this example, that is achieved by leaving the radio on for # 1 second after transmitting a sample. If this end device # never needs to receive transmissions, this can be left # out. print("Enable the radio for a bit to receive transmissions...") xbee.idle_radio(False) # Wait 1 second with the radio enabled. This is the only # time the radio can receive transmissions. time.sleep(1) print("Disable the radio again") xbee.idle_radio(True) print("Example complete, re-enabling radio") xbee.idle_radio(False)
def main(): module = xbee.XBee() # Wait until the module has joined a network before starting ai = xbee.atcmd("AI") while ai != 0: print("Waiting to join a network, AI=%x" % ai) time.sleep(1) ai = xbee.atcmd("AI") # Put the radio to sleep. Note that by doing so the MicroPython # application assumes the responsibility of fequently calling poll_now() # or data sent to this device may be lost. xbee.idle_radio(True) # register handle_rx_packet to be called whenever a packet is received. xbee.receive_callback(handle_rx_packet) samples = [] # Since this application spends most of its time asleep, stopping # the application through the UART can be difficult. To make the # example easier to work with, it will only run for about a minute # instead of indefinitely. for _ in range(12): # Sleep for 5 seconds module.sleep_now(5000) # Upon waking, take a sample sample = read_sensor() samples.append(sample) print(" Sample: {}".format(sample)) if len(samples) == 4: # Once we have four samples, Send the samples to # the coordinator. Note that we don't have to call # xbee.idle_radio(True) to be able to do this--the radio is # enabled just long enough to send the transmission. print("Transmit samples: {}".format(samples)) xbee.transmit(xbee.ADDR_COORDINATOR, str(samples)) # Clear the stored samples samples.clear() # We need to call poll_now() periodically to check for incoming # messages, so do that now. xbee.poll_now() # handle_rx_packet() is registered as the receive callback, so # it will be called automatically if the poll comes back with # any data. print("Example complete, re-enabling radio") xbee.idle_radio(False)
def read_twelvevr(): try: twelvevr_voltage = str(twelvevr_ina.voltage()) twelvevr_current = str(twelvevr_ina.current()) print_twelvevr = "12V_Rail:" + time_snapshot + ":BusVolt:" + twelvevr_voltage + "V:Current:" + twelvevr_current + "mA:#" except: print_twelvevr = "12V_Rail:" + time_snapshot + ":BusVolt:INVALID:Current:INVALID:#" print("INA219:0x41: 12V Rail read failed...") try: xbee.transmit(TARGET_64BIT_ADDR, print_twelvevr) except: print("XBee: 12V Rail TX Failed...")
def read_battery(): try: battery_voltage = str(battery_ina.voltage()) battery_current = str(battery_ina.current()) print_battery = "Battery:" + time_snapshot + ":BusVolt:" + battery_voltage + "V:Current:" + battery_current + "mA:#" except: print_battery = "Battery:" + time_snapshot + ":BusVolt:INVALID:Current:INVALID:#" print("INA219:0x44: Battery read failed...") try: xbee.transmit(TARGET_64BIT_ADDR, print_battery) except: print("XBee: Battery TX Failed...")
def read_solar(): try: solar_voltage = str(solar_ina.voltage()) solar_current = str(solar_ina.current()) print_solar = "Solar:" + time_snapshot + ":BusVolt:" + solar_voltage + "V:Current:" + solar_current + "mA:#" except: print_solar = "Solar:" + time_snapshot + ":BusVolt:INVALID:Current:INVALID:#" print("INA219:0x45: Solar read failed...") try: xbee.transmit(TARGET_64BIT_ADDR, print_solar) except: print("XBee: TX Solar Failed...")
def ble_callback(relay_frame): if relay_frame is not None: raw_data = relay_frame["message"] start_byte,data_length,addr0,addr1,addr2,addr3,addr4,addr5,addr6,addr7,xmit_data = unpack('<bhbbbbbbbbs', raw_data) if(start_byte != 0x7e) return dest_addr = bytes([addr0,addr1,addr2,addr3,addr4,addr5,addr6,addr7]) try: xbee.transmit(dest_addr, bytes(xmit_data, 'utf-8')) # TODO 06/21/21: create a response frame relay.send(relay.BLUETOOTH, "success") except Exception as e: # TODO 06/21/21: create a response frame relay.send(relay.BLUETOOTH, "error")
def transmision(bl, msj): global dispositivos, existe if bl is "0": try: xbee.transmit(xbee.ADDR_BROADCAST, msj) except Exception as e: pass else: try: xbee.transmit(dispositivos[bl]["addr"], msj) except Exception as e: if existe: existe = False descubrir_red() transmision(bl, msj)
def log(msg): """ log transmits the given message via the network in a Log Packet. If the message is too big to fit into a single packet, this chunks it up. """ dest = COORDINATOR_ADDRESS chunk_size = MAX_PACKET_SIZE - 1 # Minus 1 to make room for the packet type byte. for i in range(0, len(msg), chunk_size - 1): chunk = msg[i:i + MAX_PACKET_SIZE] tx = bytes([PACKET_TYPE_LOG]) + chunk try: xbee.transmit(dest, tx) except: print( msg ) # Looks like xbee.transmit isn't working, so just use print instead.
def ble_callback(relay_frame): if relay_frame is None: return raw_data = relay_frame["message"] raw_data_len = len(raw_data) sys.stdout.buffer.write("raw data len:" + str(raw_data_len) + "\r\n") if (raw_data_len < 11): return header = raw_data[0:11] start_byte, data_length, addr0, addr1, addr2, addr3, addr4, addr5, addr6, addr7 = unpack( '>BHBBBBBBBB', header) sys.stdout.buffer.write("start byte:" + str(start_byte) + "\r\n") if (start_byte != 0x7e): sys.stdout.buffer.write("error: invalid start byte:" + str(start_byte) + "\r\n") return sys.stdout.buffer.write("data length:" + str(data_length) + "\r\n") if (raw_data_len < data_length + 11): sys.stdout.buffer.write("error: invalid data length:" + str(data_length) + "+11<" + str(raw_data_len)) return sys.stdout.buffer.write("addr0:" + hex(addr0) + "\r\n") sys.stdout.buffer.write("addr1:" + hex(addr1) + "\r\n") sys.stdout.buffer.write("addr2:" + hex(addr2) + "\r\n") sys.stdout.buffer.write("addr3:" + hex(addr3) + "\r\n") sys.stdout.buffer.write("addr4:" + hex(addr4) + "\r\n") sys.stdout.buffer.write("addr5:" + hex(addr5) + "\r\n") sys.stdout.buffer.write("addr6:" + hex(addr6) + "\r\n") sys.stdout.buffer.write("addr7:" + hex(addr7) + "\r\n") #dest_addr = bytes([0x00,0x13,0xA2,0x00,0x41,0xB7,0x64,0xAD]) dest_addr = bytes((addr0, addr1, addr2, addr3, addr4, addr5, addr6, addr7)) sys.stdout.buffer.write("dest addr:" + str(dest_addr) + "\r\n") xmit_data = raw_data[11:11 + data_length] sys.stdout.buffer.write("xmit data:" + str(xmit_data) + "\r\n") try: xbee.transmit(dest_addr, xmit_data) xbee.relay.send( xbee.relay.BLUETOOTH, bytes([0x7e, 0x00, 0x07, 0x8B, 0, 0xFF, 0xFE, 0, 0x00, 0x00, 0x00])) except Exception as e: xbee.relay.send( xbee.relay.BLUETOOTH, bytes([0x7e, 0x00, 0x07, 0x8B, 0, 0xFF, 0xFE, 0, 0x01, 0x00, 0x00]))
def publish_relay_state(relay_id): _ai = xbee.atcmd('AI') if _ai != 0: print( 'publish_relay_state: Not associated to a PAN (current state is {}. Cannot publish' .format(_ai)) return global reporting_tsn state = True if relay_state & (1 << relay_id) else False msg = zha.serialize_on_off_report(reporting_tsn & 0xFF, state) reporting_tsn += 1 ep = relay_id + base_ep xbee.transmit(xbee.ADDR_COORDINATOR, msg, source_ep=ep, dest_ep=ep, cluster=0x0006, profile=260)
Temp = Temp / 100 fTemp = (Temp * 9 / 5) + 32 print('Temp = ', '%.1fC' % Temp) print('Temp = ', '%.1fF' % fTemp) print('Pressure = ', '%.1f ' % Pres) except: print('ms5837 read failed') # build ms5837 sensor data payload try: time_snapshot = str(utime.ticks_cpu()) #print_TH = "T9602:" + time_snapshot + ":Humidity:" + str(t96h) + "%:Temp:" + str(fTemp) + "F:#" #T9602 humidity and temp print_PT = "MS5837:" + time_snapshot + ":Press:" + str( Pres) + "mB:Temp:" + str(fTemp) + "F:#" # MS5837 sensor payload print(print_PT) except: print("sensor payload build failed") #transmit Temp Humidity data over Zigbee to coordinator try: xbee.transmit(TARGET_64BIT_ADDR, print_PT) #xbee.transmit(ROUTER_64BIT_x1B2D, print_TH) print("send data to coordinator") except: print("xbee coordinator transmit failed") utime.sleep(10.0) #delay between sensors utime.sleep(15.0)
##Micropython script that can be flashed to an xbee module that supports ##micropython ##Requirments: #Mac address of receiving Xbee import xbee import time import machine # TODO: replace with the 64-bit address of your target device. dest = b'\x00\x13\xa2\x00A\x8d\x03=' #specific to xbee, at command to change vref to 3.3v #and to set AD0 pi to adc mode x = xbee.XBee() x.atcmd('AV', 2) apin = machine.ADC('D0') while True: #read the value of the pin raw_val = apin.read() voltage = (raw_val / 4095) * 3.3 p = ((voltage - .33) / 1.32) - 1 string = str(p) #transmit the message try: xbee.transmit(dest, string) time.sleep(0.01) print("Data sent successfully") except Exception as e: print("Tranmit failure: %s" % str(e))
for x in sender), payload.decode())) try: received_data_dict = loads(payload.decode()) # for item_key in received_data_dict.keys(): # print("{0}: {1}".format(str(item_key), str(received_data_dict[item_key]))) min_t = float(received_data_dict['min_interval']) max_t = float(received_data_dict['max_interval']) change_t = float(received_data_dict['change_threshold']) xbee_temperature_sensor.min_interval = min_t xbee_temperature_sensor.max_interval = max_t xbee_temperature_sensor.change_trigger = change_t xbee.transmit( gps_temp_device.COORD_64_ADDRESS, dumps({ 'Received params': { 'min': int(xbee_temperature_sensor.min_interval), 'max': int(xbee_temperature_sensor.max_interval), 'change': xbee_temperature_sensor.change_trigger } })) # print("updated: min={0}, max={1}, change_trigger={2}".format(str(xbee_temperature_sensor.min_interval), str(xbee_temperature_sensor.max_interval), str(xbee_temperature_sensor.change_trigger))) except Exception as e: print("exception in casting the incoming message: {0}".format( str(e))) # *** Run the following for each device # Health if idx % 10 == 0 or gps_temp_device.sent_idx != idx - (idx % 10): gps_temp_device.health['idx'] = idx # TODO Add here health measures into the 'stat_v' field try: # print(str(gps_temp_device.health))
def buscar(read_text): sr = b'' while sr.decode() is not ';': sr = stdin.buffer.read(1) read_text = read_text + sr return read_text dispositivos = {} descubrir_red() while True: # Check if the XBee has any message in the queue. received_msg = xbee.receive() if received_msg: # Get the sender's 64-bit address and payload from the received message. sender = received_msg['sender_eui64'] payload = received_msg['payload'] stdout.buffer.write(payload) time.sleep_ms(50) read_text = stdin.buffer.read() if read_text is not None: try: index_final = read_text.decode().index(";") except: read_text = buscar(read_text) try: xbee.transmit(dispositivos["coordinador"], read_text) except Exception as e: pass time.sleep(0.1)
def main(): """ Main execution of the application. """ # Initialize variables. global sensor global identified global finished global simulate_temp print(" +-----------------------------------+") print(" | End-to-End IoT Agriculture Sample |") print(" +-----------------------------------+\n") # Instantiate the HDC1080 peripheral. try: sensor = HDC1080(I2C(1)) except AssertionError: pass # Configure the Bluetooth advertisement. config_advertisement() # Register relay callback to handle incoming relay packets. relay.callback(relay_frame_callback) # Set the LED pin initial value to off (0). led_pin.off() was_btn_pressed = is_button_pressed() # Start the main application loop. while True: # Sleep 100 ms. time.sleep_ms(100) if sensor is not None: # If the button has been pressed, swap the temperature source # (reading or simulation). if not was_btn_pressed and is_button_pressed(): simulate_temp = not simulate_temp print("- Temperature source changed to %s" % ("simulation" if simulate_temp else "reading")) was_btn_pressed = is_button_pressed() # Blink identification LED if necessary. if identified: if finished: identified = False finished = False else: led_pin.value(not led_pin.value()) # Check if we received any XBee packet from the gateway. incoming = xbee.receive() if incoming is not None: print("- Packet received with payload '%s'" % list(incoming["payload"])) # Get the packet payload. message = incoming["payload"].decode("utf-8") # Parse the JSON items. try: json_items = ujson.loads(message) print(" - Parsed status: %s" % json_items) except ValueError as e: json_items = None print(" - Error parsing status: %s" % str(e)) if json_items is not None: # Get the operation to perform. operation = json_items[ITEM_OP] if operation is None: return elif operation == OP_STATUS: # Configure status values. statuses = json_items[ITEM_PROP] for status_id in statuses: set_status_value(status_id, statuses[status_id]) # Return the sensor values. status_response = { ITEM_OP: OP_STATUS, ITEM_PROP: get_sensors_values() } print("- Reporting status data: %s" % status_response) try: xbee.transmit(xbee.ADDR_COORDINATOR, ujson.dumps(status_response)) except Exception as e: print(" - Transmit failure: %s" % str(e))
# this file was based on the example code from: # https://learn.adafruit.com/adafruit-stemma-soil-sensor-i2c-capacitive-moisture-sensor?view=all import xbee from machine import I2C from moisture_sensor import Seesaw import time import json i2c_bus = I2C(1, freq=400000) ss = Seesaw(i2c_bus, addr=0x36) while True: # read moisture level through capacitive touch pad touch = ss.moisture_read() data = {'SensorID': 1, 'Humidity': touch} output = json.dumps(data) + '\n' print(output) xbee.transmit(xbee.ADDR_BROADCAST, output) time.sleep(10)
data_pending = False data_length = 0 while (True): # read header header_marker1 = 0 header_marker2 = 0 data_type = 0 if (data_pending): for x in range(0, data_length, 84): current_length = min(84, data_length - x) data = stdin.buffer.read(current_length) attempts = 0 pending = True while pending and attempts < 10: try: xbee.transmit(0xB4A4, data) pending = False except Exception as e: pending = True attempts = attempts + 1 s = str(e) stdout.buffer.write("Error while transmitting data: " + s + "\n") data_pending = False micropython.kbd_intr(3) data_length = 0 else: #xbee.transmit(xbee.ADDR_BROADCAST, "Waiting for header") # --- DEBUG header_data = stdin.buffer.read(11) # blocks until receiving 10 bytes #xbee.transmit(xbee.ADDR_BROADCAST, "Received header " + str(header_data)) # --- DEBUG header_marker, data_type, data_length = unpack('<bhQ', header_data)
:return: The XBee device with the given node identifier or ``None`` if it could not be found. """ for dev in xbee.discover(): if dev['node_id'] == node_id: return dev return None print(" +--------------------------------------------+") print(" | XBee MicroPython Transmit Data (NI) Sample |") print(" +--------------------------------------------+\n") # Find the device with the configure node identifier. device = find_device(TARGET_NODE_ID) if not device: print("Could not find the device with node identifier '%s'" % TARGET_NODE_ID) sys.exit(-1) addr16 = device['sender_nwk'] addr64 = device['sender_eui64'] print("Sending data to %s >> %s" % (TARGET_NODE_ID, MESSAGE)) try: # Some protocols do not have 16-bit address. In those cases, use the 64-bit one. xbee.transmit(addr16 if addr16 else addr64, MESSAGE) print("Data sent successfully") except Exception as e: print("Transmit failure: %s" % str(e))
while network_status() != 0: time.sleep(0.1) print("Connected to Network\n") last_sent = time.ticks_ms() interval = 1000 # How often to send a message in ms # read digital input D12 and set D19 output D12 = Pin("D12", Pin.IN, Pin.PULL_UP) D19 = Pin("D19", Pin.OUT, value=0) # Start the transmit/receive loop print("Sending temp data every {} seconds".format(interval / 1000)) while True: p = xbee.receive() if p: format_packet(p) else: # Transmit sensor state if ready if time.ticks_diff(time.ticks_ms(), last_sent) > interval: # TE sensor state is monitored by D12 input sensor = str(D12.value()) D19.value(D12.value()) print("\tsending sensor state= " + sensor) try: xbee.transmit(xbee.ADDR_COORDINATOR, sensor) except Exception as err: print(err) last_sent = time.ticks_ms() time.sleep(0.25)
It works by checking if the amount of time between transmissions has elapsed, and then sending a signal to the coordinator XBee. Print statement is included after the sending line for debugging/timing the number of transmissions. @arwensadler """ import xbee import time # How often to send a signal in ms interval = 100 # Initialize last_sent to the current time last_sent = time.ticks_ms() # Start looping through while True: # Check if it's time to send a signal if time.ticks_diff(time.ticks_ms(), last_sent) > interval: # Attempt to send a signal try: xbee.transmit(xbee.ADDR_COORDINATOR, "h") # Arbitrary message content print("sent!") except Exception as err: print(err) # Reset last_sent to the current time last_sent = time.ticks_ms()
switch = tilt_switch.value() # Evaluate dip switch positions zone = 0x3 & (sw_bit_1.value() << 1) | (sw_bit_0.value()) try: print("Sector: " + str(zone) + "\nMoisture: " + str(moisture) + "\nSunlight: " + str(ambiance) + "\nBattery: " + str(battery) + "\nTilt: " + str(switch) + "\n") xbee.transmit(xbee.ADDR_COORDINATOR, ("{'Sector': " + str(zone) + ", 'Moisture': " + str(moisture) + ", 'Sunlight': " + str(ambiance) + ", 'Battery': " + str(battery) + ", 'Tilt': " + str(switch) + "}") ) except Exception as err: print(err) else: # Read data from moisture probe moisture_sensor_power.on() time.sleep_ms(100) moisture_average += moisture_probe.read() moisture_sensor_power.off() # Evaluate ambient light in area
# Instantiate the HDC1080 peripheral. sensor = HDC1080(I2C(1)) # Instantiate the XBee device. xb = xbee.XBee() # Configure sleep mode to be managed by MicroPython. xb.atcmd("SM", 0x06) sleep_time = SLEEP_TIME_MS # Start reading temperature and humidity measures. while True: # Notify the gateway that the XBee is awake. xbee.transmit(xbee.ADDR_COORDINATOR, MSG_AWAKE) # Wait during the configured time for incoming messages. start_time_ms = time.ticks_ms() while time.ticks_diff(time.ticks_ms(), start_time_ms) < AWAKE_TIME_MS: incoming = xbee.receive() if incoming is not None and incoming[ "sender_nwk"] == 0 and not incoming["broadcast"]: try: payload = int(incoming["payload"].decode()) except ValueError: continue if payload < 0: continue # Update the sleep time. sleep_time = payload * 1000 print("Temperature/humidity service stopped.\n" if sleep_time ==
# on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License # for the specific language governing permissions and limitations under the License. # # Change History: # # Date Who What # ---- --- ---- # 2019-05-21 Daniel Terryn Original Creation # # import xbee import time import binascii import sys x = xbee.XBee() #Create an XBee object while True: voltage = x.atcmd('%V') print("Voltage at " + str(voltage)) tx_req = ("7E" + "00" + "05" + "2D" + "01" + str(voltage)) try: xbee.transmit(xbee.ADDR_COORDINATOR, binascii.unhexlify(tx_req)) except: print( "Error occured to send package, probably not connected to ZigBee network" ) print("going to sleep now") time.sleep_ms(60000) if x.wake_reason() is xbee.PIN_WAKE: print("woke early on DTR toggle") sys.exit()
while network_status() != 0: time.sleep(0.1) print("Network Established\n") print("Waiting for a remote node to join...") node_list = [] while len(node_list) == 0: # Perform a network discovery until the remote joins node_list = list(xbee.discover()) print("Remote node found, transmitting data") for node in node_list: dest_addr = node['sender_eui64'] # using 64-bit addressing dest_node_id = node['node_id'] payload_data = "Hello, " + dest_node_id xbee.transmit(dest_addr, payload_data) # Start the receive loop print("Receiving data...") print("Hit CTRL+C to cancel") while True: p = xbee.receive() if p: # Here you recieve the message format_packet(p) else: time.sleep(0.25)
import xbee TARGET_64BIT_ADDR = b'' # Put target Xbee module adress here MESSAGE = "Hello World" print("Sending data to %s >> %s" % (''.join('{:02x}'.format(x).upper() for x in TARGET_64BIT_ADDR), MESSAGE)) try: xbee.transmit(TARGET_64BIT_ADDR, MESSAGE) print("Data sent successfully") except Exception as e: print("Transmit failure: %s" % str(e))
print("humidity sensor conversion failed") # build PTH sensor data payload try: time_snapshot = str(utime.ticks_cpu()) #print_PTH = "PTH_sensor:" + time_snapshot + ":Press:" + str(Pres) + "mB:Temp:" + str(fTemp) + "F:Temp1:" + str(ftemp9) + "F:Humidity:" + str(RH) + "%:#" print_PTH = "PTH_sensor:" + time_snapshot + ":Press:" + str( Pres) + "mB:Temp:" + str(fTemp) + "F:Humidity:" + str( RH) + "%:#" #remove MCP9808 print(print_PTH) except: print("sensor payload build failed") #transmit PTH data over Zigbee to coordinator try: xbee.transmit(TARGET_64BIT_ADDR, print_PTH) #xbee.transmit(ROUTER_64BIT_x1B2D, print_PTH) # except: print("xbee coordinator transmit failed") utime.sleep(5.0) #short delay between transmit #transmit info over Zigbee to router for testing try: #xbee.transmit(TARGET_64BIT_ADDR, print_PTH) xbee.transmit(ROUTER_64BIT_RTR, FWver) print("xbee rtr = ", ROUTER_64BIT_RTR) # except: print("xbee router transmit failed")