Skip to content

Commit

Permalink
Closes bitcraze#622: Implenent app_channel communication API
Browse files Browse the repository at this point in the history
  • Loading branch information
ataffanel committed Dec 3, 2020
1 parent 992e23e commit 0bda471
Show file tree
Hide file tree
Showing 12 changed files with 440 additions and 1 deletion.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@ PROJ_OBJ += vl53l1_register_funcs.o vl53l1_wait.o vl53l1_core_support.o
PROJ_OBJ += system.o comm.o console.o pid.o crtpservice.o param.o
PROJ_OBJ += log.o worker.o trigger.o sitaw.o queuemonitor.o msp.o
PROJ_OBJ += platformservice.o sound_cf2.o extrx.o sysload.o mem.o
PROJ_OBJ += range.o app_handler.o static_mem.o
PROJ_OBJ += range.o app_handler.o static_mem.o app_channel.o

# Stabilizer modules
PROJ_OBJ += commander.o crtp_commander.o crtp_commander_rpyt.o
Expand Down
9 changes: 9 additions & 0 deletions app_api/src/app_main.c
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@
#include "log.h"
#include "param.h"
#include "pm.h"
#include "app_channel.h"


#define DEBUG_MODULE "APPAPI"
Expand Down Expand Up @@ -123,4 +124,12 @@ void appMain() {
pmIsCharging();
pmIsDischarging();
}

// App-channel
{
char buffer[APPCHANNEL_MTU];
appchannelSendPacket("hello", 5);
appchannelReceivePacket(buffer, APPCHANNEL_MTU, APPCHANNEL_WAIT_FOREVER);
appchannelHasOverflowOccured();
}
}
8 changes: 8 additions & 0 deletions docs/userguides/app_layer.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,14 @@ For the app-layer, it would be good to have access to log and/or parameter value

It is possible to run LED sequences from the app layer to control the four LEDs on the Crazyflie and provide runtime information to the user. See the src/hal/interface/ledseq.h file for more information.

## App channel: packet based communication between the Crazyflie and the Python lib

The Appchannel API allows to communicate using radio packets with an app.
The packets can contain anything of a size up to 31 bytes, the protocol is defined by the app.

For more information about the API see the header file src/modules/interface/app_channel.h.
An example of how to use the app channel is in examples/app_appchannel_test/

## Examples

In the [example folder](https://github.com/bitcraze/crazyflie-firmware/tree/master/examples) of the crazyflie-firmware repository, there are several examples shown tha tuse the app layer, including a simple hello world example.
2 changes: 2 additions & 0 deletions examples/app_appchannel_test/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
bin/*
cf2.*
10 changes: 10 additions & 0 deletions examples/app_appchannel_test/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@

# enable app support
APP=1
APP_STACKSIZE=300

VPATH += src/
PROJ_OBJ += appchannel_test.o

CRAZYFLIE_BASE=../..
include $(CRAZYFLIE_BASE)/Makefile
10 changes: 10 additions & 0 deletions examples/app_appchannel_test/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
# Appchannel test app for Crazyflie 2.x

This application demonstrates how to use the appchannel API to send and receive
radio packets between a Crazyflie app and the python lib.

This demo defines a protocol where the Crazyflie waits for 3 floas (x, y, z) and sends back the sum as one float.

To run this example, compile and flash the app with ```make && make cload```.

When the Crazyflie is flashed and started, you can run the python example with ```python3 tools/appchannelTest.py```.
64 changes: 64 additions & 0 deletions examples/app_appchannel_test/src/appchannel_test.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
/**
* ,---------, ____ _ __
* | ,-^-, | / __ )(_) /_______________ _____ ___
* | ( O ) | / __ / / __/ ___/ ___/ __ `/_ / / _ \
* | / ,--´ | / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
* +------` /_____/_/\__/\___/_/ \__,_/ /___/\___/
*
* Crazyflie control firmware
*
* Copyright (C) 2019 Bitcraze AB
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, in version 3.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*
* appchanel_test.c: Demonstrate the appchanel functionality
*/

#include "app.h"
#include "app_channel.h"

#include "debug.h"

#define DEBUG_MODULE "HELLOWORLD"

struct testPacketRX {
float x;
float y;
float z;
} __attribute__((packed));

struct testPacketTX {
float sum;
} __attribute__((packed));

void appMain()
{
DEBUG_PRINT("Waiting for activation ...\n");

struct testPacketRX rxPacket;
struct testPacketTX txPacket;

while(1) {
if (appchannelReceivePacket(&rxPacket, sizeof(rxPacket), APPCHANNEL_WAIT_FOREVER)) {

DEBUG_PRINT("App channel received x: %f, y: %f, z: %f\n", (double)rxPacket.x, (double)rxPacket.y, (double)rxPacket.z);

txPacket.sum = rxPacket.x;
txPacket.sum += rxPacket.y;
txPacket.sum += rxPacket.z;

appchannelSendPacket(&txPacket, sizeof(txPacket));
}
}
}
117 changes: 117 additions & 0 deletions examples/app_appchannel_test/tools/appchannelTest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,117 @@
# -*- coding: utf-8 -*-
#
# || ____ _ __
# +------+ / __ )(_) /_______________ _____ ___
# | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
# +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
# || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
#
# Copyright (C) 2014 Bitcraze AB
#
# Crazyflie Nano Quadcopter Client
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
"""
Simple example that connects to the first Crazyflie found, Sends and
receive appchannel packets
The protocol is:
- 3 floats are send, x, y and z
- The Crazyflie sends back the sum as one float
"""
import logging
import time
from threading import Thread

import struct

import cflib
from cflib.crazyflie import Crazyflie

logging.basicConfig(level=logging.ERROR)


class AppchannelTest:
"""Example that connects to a Crazyflie and ramps the motors up/down and
the disconnects"""

def __init__(self, link_uri):
""" Initialize and run the example with the specified link_uri """

self._cf = Crazyflie()

self._cf.connected.add_callback(self._connected)
self._cf.disconnected.add_callback(self._disconnected)
self._cf.connection_failed.add_callback(self._connection_failed)
self._cf.connection_lost.add_callback(self._connection_lost)

self._cf.appchannel.packet_received.add_callback(self._app_packet_received)

self._cf.open_link(link_uri)

print('Connecting to %s' % link_uri)

def _connected(self, link_uri):
""" This callback is called form the Crazyflie API when a Crazyflie
has been connected and the TOCs have been downloaded."""

# Start a separate thread to do the motor test.
# Do not hijack the calling thread!
Thread(target=self._test_appchannel).start()

def _connection_failed(self, link_uri, msg):
"""Callback when connection initial connection fails (i.e no Crazyflie
at the specified address)"""
print('Connection to %s failed: %s' % (link_uri, msg))

def _connection_lost(self, link_uri, msg):
"""Callback when disconnected after a connection has been made (i.e
Crazyflie moves out of range)"""
print('Connection to %s lost: %s' % (link_uri, msg))

def _disconnected(self, link_uri):
"""Callback when the Crazyflie is disconnected (called in all cases)"""
print('Disconnected from %s' % link_uri)

def _app_packet_received(self, data):
(sum, ) = struct.unpack("<f", data)
print(f"Received sum: {sum}")

def _test_appchannel(self):
for i in range(10):
(x, y, z) = (i, i+1, i+2)
data = struct.pack("<fff", x, y, z)
self._cf.appchannel.send_packet(data)
print(f"Sent x: {x}, y: {y}, z: {z}")

time.sleep(1)

self._cf.close_link()


if __name__ == '__main__':
# Initialize the low-level drivers (don't list the debug drivers)
cflib.crtp.init_drivers(enable_debug_driver=False)
# Scan for Crazyflies and use the first one found
print('Scanning interfaces for Crazyflies...')
available = cflib.crtp.scan_interfaces()
print('Crazyflies found:')
for i in available:
print(i[0])

if len(available) > 0:
le = AppchannelTest(available[0][0])
else:
print('No Crazyflies found, cannot run example')
96 changes: 96 additions & 0 deletions src/modules/interface/app_channel.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,96 @@
/*
* || ____ _ __
* +------+ / __ )(_) /_______________ _____ ___
* | 0xBC | / __ / / __/ ___/ ___/ __ `/_ / / _ \
* +------+ / /_/ / / /_/ /__/ / / /_/ / / /_/ __/
* || || /_____/_/\__/\___/_/ \__,_/ /___/\___/
*
* LPS node firmware.
*
* Copyright 2020, Bitcraze AB
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Foobar is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Foobar. If not, see <http://www.gnu.org/licenses/>.
*/
/* app_channel.h: App realtime communication channel with the ground */
#pragma once

#include <stddef.h>
#include <stdbool.h>

#include "crtp.h"

#define APPCHANNEL_WAIT_FOREVER (-1)
#define APPCHANNEL_MTU (31)

/**
* Send an app-channel packet
*
* The maximum buffer size that can be sent is define in APPCHANNEL_MTU.
* If the length of the buffer is longer than that, the packet will be cropped
* to send only the APPCHANNEL_MTU first bytes.
*
* This function can block if there is no more space in the Crazyflie TX queue.
* This is very unlikely to happen when CRTP is connected but can happen when the
* connection is not active.
*
* @param data Pointer to the data buffer to be sent
* @param length Length of the data buffer to send
*
* \app_api
*/
void appchannelSendPacket(void* data, size_t length);

/**
* Receive an app-channel packet
*
* If the data received is longer than max_length, the data will be silently cropped and only
* the fist "max_length" bytes of the packet will be copied in the buffer.
*
* The maximum length packet possible to be received is APPCHANNEL_MTU bytes long.
*
* @param buffer Data buffer where the packet content will be copied
* @param max_length Maximum length of the data to be received, ie. length of the data buffer
* @param timeout_ms Time to wait for a packet in millisecond. A value of 0 will make the
* function non blocking, only reporting a packet is one is already in the
* receive queue. A value of APPCHANNEL_WAIT_FOREVER make the funciton block
* infinitly until a packet is received.
* @return 0 if no packet has been received. The data length of the packet received.
*/
size_t appchannelReceivePacket(void* buffer, size_t max_length, int timeout_ms);

/**
* Returns if an overflow has occured in the receive queue
*
* The app-channel received packets are put in a queue. It is expected that the app is
* regularly calling appchannelReceivePacket() to get the packets from the receive queue.
* If that is not the case, the queue can overflow and this function allows the app to know
* about it. The overflow flag is being reset by this call.
*
* @return true if an overflow has occured in the receive queue.
*/
bool appchannelHasOverflowOccured();


// Function declared bellow are private to the Crazyflie firmware and
// should not be called from an app

/**
*
*/
void appchannelInit();

/**
*
*/
void appchannelIncomingPacket(CRTPPacket *p);
4 changes: 4 additions & 0 deletions src/modules/interface/platformservice.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,12 +29,16 @@

#include <stdbool.h>

#include "crtp.h"

/**
* Initialize the platform CRTP port
*/
void platformserviceInit(void);

bool platformserviceTest(void);

void platformserviceSendAppchannelPacket(CRTPPacket *p);

#endif /* __PLATFORMSERVICE_H__ */

Loading

0 comments on commit 0bda471

Please sign in to comment.