Ejemplo n.º 1
0
def relay_frame_callback(relay_frame):
    sender = relay_frame["sender"]
    message = relay_frame["message"].decode("utf-8")

    # Send back a response.
    relay.send(sender, "New message from %s: %s" % (INTERFACES[sender],
                                                    message))
Ejemplo n.º 2
0
def sending():
    while True:
        # relay.receive() -> Receives the message from the client
        relay_frame = relay.receive()

        # Stay in loop until an actual message is received
        while relay_frame is None:
            relay_frame = relay.receive()
            time.sleep(0.25)

        if relay_frame is not None:
            # Send acknowledgment message back to client
            relay.send(relay.BLUETOOTH, "OK")

            # Don't change this line. This is how it knows who to send the message to.
            sender = relay_frame["sender"]

            # Alter 'message' to send the desired payload
            file = open("example.txt", "r")
            lines = file.readlines()
            message = ""
            for line in lines:
                message = message + line
                message = message + "@@@"

            # Send the message and start reading relay frames again.
            relay.send(sender, message)

        else:
            # No connection between XBee and Android
            print("no connection")
            time.sleep(30)
Ejemplo n.º 3
0
 def print(self, msg):
     """
     print sends the given message as a User Data Relay API Frame out the relay.SERIAL
     interface so that the Connect Sensor can print it out its Serial Console.
     """
     dest = relay.SERIAL
     data = bytes([self.CSXB_MSG_LOG]) + msg
     try:
         relay.send(dest, data)
     except:
         pass  # Do nothing because relay must be broken so we have nowhere to send the error!
Ejemplo n.º 4
0
def demo_handle_api_frames():
    '''
    Provides loopback functionality. Receives a User Data Relay API frame
    from the serial interface, adds some data to it, then sends it back to the sender.
    
    How to run this demo:
    1) In XCTU's MicroPython Terminal, first put the XBee into MicroPython mode (+++-wait-ATAP4).
       Then press Ctrl+f, paste in the code, and compile it into /flash/main.mpy.
       Then press Ctrl+d to soft reboot and run the code.
       (Make sure there is no /flash/main.py file or that would get executed instead.)
       Alternatively, copy this code into /flash/main.py using XCTU's File System Manager tool
       (and then you can press the reset pushbutton to restart the system and run the new code).
       Then put the device back into API Mode with Escapes (+++-wait-ATAP2) so that it is ready to receive the data.
       Close the serial port in XCTU when done so that you can reopen the port with gecko.py.
    2) In another terminal, run api_frames_loopback_test() defined in gecko.py.
       That script will open the serial port using PySerial and send a User Data Relay message to MicroPython.
       The code below receives that message, appends to it, and then sends it back to the sender.

    Notes:
    - You could add the "+++-wait-ATAP4" commands here to streamline changing modes for testing.
    - You can also set up a loopback example within MicroPython. relay.send(relay.MICROPYTHON, b"blah") and then call relay.receive().
    '''

    print("Launching API frames demo.")

    from machine import Pin
    import time

    from xbee import relay

    led = Pin(
        "D5", Pin.OUT, value=0
    )  # DIO5 = XBee3 Cellular "Associated Indicator" LED, which is Pin 15 of the through-hole package.

    while True:
        rx = relay.receive()
        if rx is not None:
            dest = rx['sender']
            data = rx['message'] + b'world'
            relay.send(dest, data)
        time.sleep_ms(500)
        led.toggle()
Ejemplo n.º 5
0
def relay_frame_callback(relay_frame):
    """
    Callback executed every time the XBee module receives a relay packet.
    Processes the packet, executes the proper actions and sends a response
    back.

    Args:
         relay_frame (dict): the relay packet to process.
    """
    # Initialize variables.
    global identified
    global finished
    response = {}

    # Discard non BLE packets.
    sender = relay_frame["sender"]
    if sender != relay.BLUETOOTH:
        return

    # Get the packet payload.
    message = relay_frame["message"].decode("utf-8")

    # Parse the JSON items
    try:
        json_items = ujson.loads(message)
    except ValueError:
        return

    # Get the operation to perform.
    operation = json_items[ITEM_OP]
    if operation is None:
        return
    elif operation == OP_READ:
        print("- BLE: Read parameters request received.")
        # Set the response command command ID.
        response[ITEM_OP] = OP_READ
        # Read the properties.
        read_settings = read_properties()
        if read_settings is None:
            response[ITEM_STATUS] = STATUS_ERROR
            response[ITEM_MSG] = "Error reading settings from the XBee module."
        else:
            response[ITEM_STATUS] = STATUS_SUCCESS
            response[ITEM_PROP] = read_settings
    elif operation == OP_WRITE:
        print("- BLE: Write parameters request received.")
        # Set the response command ID.
        response[ITEM_OP] = OP_WRITE
        # Write the given properties.
        success = save_properties(json_items[ITEM_PROP])
        if success:
            response[ITEM_STATUS] = STATUS_SUCCESS
        else:
            response[ITEM_STATUS] = STATUS_ERROR
            response[ITEM_MSG] = "Error writing settings to the XBee module."
    elif operation == OP_ID:
        print("- BLE: Identification request received.")
        # Set the response command ID.
        response[ITEM_OP] = OP_ID
        # Get the XBee MAC address.
        mac_address = get_mac()
        if mac_address is None:
            response[ITEM_STATUS] = STATUS_ERROR
            response[ITEM_MSG] = "Error getting the MAC address from the " \
                                 "XBee module."
        else:
            response[ITEM_STATUS] = STATUS_SUCCESS
            response[ITEM_MAC] = mac_address
            response[ITEM_VALUE] = VALUE_IRRIGATION
            identified = True
    elif operation == OP_FINISH:
        print("- BLE: Finish request received.")
        # Disable BLE interface. This operation does not require a response.
        xbee.atcmd(AT_CMD_BT, VALUE_DISABLED)
        # Write settings in the device.
        xbee.atcmd(AT_CMD_WR)
        finished = True
    else:
        return

    # Send back the response.
    try:
        print("- Sending BLE response.")
        relay.send(sender, ujson.dumps(response))
    except Exception as e:
        print("  - Transmit failure: %s" % str(e))
Ejemplo n.º 6
0
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import time
from xbee import relay

INTERFACES = {0x00: "Serial Port", 0x01: "Bluetooth", 0x02: "MicroPython"}

print(" +--------------------------------------+")
print(" | XBee MicroPython Relay Frames Sample |")
print(" +--------------------------------------+\n")

while True:
    # Start reading relay frames.
    relay_frame = relay.receive()
    while relay_frame is None:
        relay_frame = relay.receive()
        time.sleep(0.25)

    # Get the relay frame parameters.
    sender = relay_frame["sender"]
    message = relay_frame["message"].decode("utf-8")

    # Send back the answer and start reading relay frames again.
    relay.send(sender,
               "New message from %s: %s" % (INTERFACES[sender], message))
Ejemplo n.º 7
0
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.

import time
from machine import Pin
from xbee import relay

# Pin D0 (AD0/DIO0)
INPUT_PIN_ID = "D0"

print(" +---------------------------------------------+")
print(" | XBee MicroPython Relay Frames Button Sample |")
print(" +---------------------------------------------+\n")

# Set up the button pin object to check the input value. Configure the pin
# as input and enable the internal pull-up.
input_pin = Pin(INPUT_PIN_ID, Pin.IN, Pin.PULL_UP)

prev_value = input_pin.value()

while True:
    value = input_pin.value()

    # If the button has been pressed, send a User Data Relay frame to the serial interface.
    if value == 0 and prev_value == 1:
        relay.send(relay.SERIAL, "Button pressed")

    prev_value = value
    time.sleep(0.1)
Ejemplo n.º 8
0
if HDC1080_ADDR not in i2c.scan():
    print("Could not find the sensor!")
    sys.exit(1)

while True:
    # Check if a relay frame has been received.
    relay_frame = relay.receive()
    if relay_frame is not None:
        data = relay_frame["message"].decode("utf-8")
        # If the message starts with "ON", parse the refresh rate.
        if data.startswith(MSG_ON):
            running = True
            refresh_rate = int(data.split(MSG_SEPARATOR)[1])
            deadline = 0
            # Send an ACK to confirm the reception.
            relay.send(relay.BLUETOOTH, MSG_ACK)
        elif data.startswith(MSG_OFF):
            running = False
            # Send an ACK to confirm the reception.
            relay.send(relay.BLUETOOTH, MSG_ACK)

    if running and time.ticks_ms() > deadline:
        # Change the pointer to 0x00 (Temperature register)
        i2c.writeto(HDC1080_ADDR, bytearray([REG_TMP]))
        # Wait for the temperature measure to complete (per data sheet).
        time.sleep(0.0635)
        # Read the temperature value (2 bytes).
        temp_bytes = i2c.readfrom(HDC1080_ADDR, 2)
        # Calculate the temperature in Celsius.
        temp_celsius = (int.from_bytes(temp_bytes, "big") / 2**16) * 165 - 40