Merge pull request 'meier/pcduhandler' (#10) from meier/pcduhandler into develop

Reviewed-on: eive/eive_obsw#10
This commit is contained in:
Robin Müller 2020-12-29 12:35:44 +01:00 committed by Robin Müller
commit eba9fac100
146 changed files with 16706 additions and 42 deletions

View File

@ -25,6 +25,7 @@ MISSION_PATH = mission
CONFIG_PATH = fsfwconfig
TEST_PATH = test
UNITTEST_PATH = unittest
LIBCSP_PATH = libcsp
# Board specific paths
BSP_PATH = $(BOARD_FILE_ROOT)
@ -113,7 +114,7 @@ INCLUDES :=
# Directories where $(directoryname).mk files should be included from
SUBDIRS := $(FRAMEWORK_PATH) $(TEST_PATH) $(BSP_PATH) $(UNITTEST_PATH)\
$(CONFIG_PATH) $(MISSION_PATH)
$(CONFIG_PATH) $(MISSION_PATH) $(LIBCSP_PATH)
# INCLUDES += framework/test/catch2
# ETL library include.

View File

@ -323,3 +323,28 @@ git merge upstream/master
Alternatively, changes from other upstreams (forks) and branches can be merged like that in
the same way.
## PCDU
Connect to serial console of P60 Dock
````
picocom -b 500000 /dev/ttyUSBx
````
General information
````
cmp ident
````
List parameter table:
x values: 1,2 or 4
````
param table x
````
Table 4 lists HK parameters
Changing parameters
First switch to table where parameter shall be changed (here table id is 1)
````
p60-dock # param mem 1
p60-dock # param set out_en[0] 1
p60-dock # param get out_en[0]
GET out_en[0] = 1
````

View File

@ -10,6 +10,7 @@
#include <fsfw/tasks/TaskFactory.h>
#include <fsfwconfig/objects/systemObjectList.h>
#include <fsfwconfig/OBSWConfig.h>
#include <fsfwconfig/pollingsequence/PollingSequenceFactory.h>
#include <iostream>
@ -125,16 +126,34 @@ void InitMission::initTasks(){
sif::error << "Object add component failed" << std::endl;
}
// PeriodicTaskIF* P60DockTask = TaskFactory::instance()->
// createPeriodicTask("P60Dock Task", 30, PeriodicTaskIF::MINIMUM_STACK_SIZE*4,
// 1.6, nullptr);
// result = P60DockTask->addComponent(objects::P60DOCK_HANDLER);
// if(result!=HasReturnvaluesIF::RETURN_OK){
// sif::error << "Object add component failed" << std::endl;
// }
#if ADD_TEST_CODE == 1
FixedTimeslotTaskIF* TestTimeslotTask = TaskFactory::instance()->
createFixedTimeslotTask("PST_TEST_TASK", 10,
PeriodicTaskIF::MINIMUM_STACK_SIZE, 1.0, nullptr);
result = pst::pollingSequenceTestFunction(TestTimeslotTask);
FixedTimeslotTaskIF* GomSpacePstTask = TaskFactory::instance()->
createFixedTimeslotTask("GS_PST_TASK", 50,
PeriodicTaskIF::MINIMUM_STACK_SIZE*4, 1.0, nullptr);
result = pst::gomspacePstInit(GomSpacePstTask);
if(result != HasReturnvaluesIF::RETURN_OK) {
sif::error << "InitMission::createTasks: Test PST initialization "
sif::error << "InitMission::initTasks: GomSpace PST initialization "
<< "failed!" << std::endl;
}
#if ADD_TEST_CODE == 1
// FixedTimeslotTaskIF* TestTimeslotTask = TaskFactory::instance()->
// createFixedTimeslotTask("PST_TEST_TASK", 10,
// PeriodicTaskIF::MINIMUM_STACK_SIZE, 1.0, nullptr);
// result = pst::pollingSequenceTestFunction(TestTimeslotTask);
// if(result != HasReturnvaluesIF::RETURN_OK) {
// sif::error << "InitMission::createTasks: Test PST initialization "
// << "failed!" << std::endl;
// }
#endif
//Main thread sleep
@ -143,13 +162,18 @@ void InitMission::initTasks(){
UdpBridgeTask->startTask();
UdpPollingTask->startTask();
GomSpacePstTask->startTask();
PusVerification->startTask();
PusEvents->startTask();
PusHighPrio->startTask();
PusMedPrio->startTask();
PusLowPrio->startTask();
// P60DockTask->startTask();
#if ADD_TEST_CODE == 1
TestTimeslotTask->startTask();
// TestTimeslotTask->startTask();
#endif
sif::info << "Tasks started.." << std::endl;
}

View File

@ -1,4 +1,6 @@
CXXSRC += $(wildcard $(CURRENTPATH)/*.cpp)
CXXSRC += $(wildcard $(CURRENTPATH)/comIF/cookies/*.cpp)
CXXSRC += $(wildcard $(CURRENTPATH)/comIF/*.cpp)
CSRC += $(wildcard $(CURRENTPATH)/*.c)
CSRC += $(wildcard $(CURRENTPATH)/boardconfig/*.c)

View File

@ -0,0 +1,211 @@
#include "CspComIF.h"
#include <bsp_linux/comIF/cookies/CspCookie.h>
#include <fsfw/serviceinterface/ServiceInterfaceStream.h>
#include <csp/drivers/can_socketcan.h>
#include <fsfw/serialize/SerializeAdapter.h>
CspComIF::CspComIF(object_id_t objectId) :
SystemObject(objectId) {
}
CspComIF::~CspComIF() {
}
ReturnValue_t CspComIF::initializeInterface(CookieIF *cookie) {
if(cookie == nullptr) {
return NULLPOINTER;
}
CspCookie* cspCookie = dynamic_cast<CspCookie*>(cookie);
if(cspCookie == nullptr) {
return NULLPOINTER;
}
/* Perform CAN and CSP initialization only once */
if(cspDeviceMap.empty()){
/* Define the memory to allocate for the CSP stack */
int buf_count = 10;
int buf_size = 300;
/* Init CSP and CSP buffer system */
if (csp_init(cspClientAddress) != CSP_ERR_NONE
|| csp_buffer_init(buf_count, buf_size) != CSP_ERR_NONE) {
sif::error << "Failed to init CSP\r\n" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
int promisc = 0; // Set filter mode on
csp_iface_t *csp_if_ptr = &csp_if;
csp_if_ptr = csp_can_socketcan_init(canInterface, bitrate, promisc);
/* Set default route and start router */
uint8_t address = CSP_DEFAULT_ROUTE;
uint8_t netmask = 0;
uint8_t mac = CSP_NODE_MAC;
int result = csp_rtable_set(address, netmask, csp_if_ptr, mac);
if(result != CSP_ERR_NONE){
sif::error << "Failed to add can interface to router table"
<< std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
/* Start the route task */
unsigned int task_stack_size = 500;
unsigned int priority = 0;
result = csp_route_start_task(task_stack_size, priority);
if(result != CSP_ERR_NONE){
sif::error << "Failed to start csp route task" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
}
uint8_t cspAddress = cspCookie->getCspAddress();
uint16_t maxReplyLength = cspCookie->getMaxReplyLength();
if(cspDeviceMap.find(cspAddress) == cspDeviceMap.end()){
/* Insert device information in CSP map */
cspDeviceMap.emplace(cspAddress, vectorBuffer(maxReplyLength));
}
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CspComIF::sendMessage(CookieIF *cookie,
const uint8_t * sendData, size_t sendLen) {
int result;
if(cookie == NULL){
return HasReturnvaluesIF::RETURN_FAILED;
}
CspCookie* cspCookie = dynamic_cast<CspCookie*> (cookie);
if(cspCookie == NULL){
return HasReturnvaluesIF::RETURN_FAILED;
}
/* Extract csp port and bytes to query from command buffer */
uint8_t cspPort;
uint16_t querySize;
result = getPortAndQuerySize(&sendData, &sendLen, &cspPort, &querySize);
if(result != HasReturnvaluesIF::RETURN_OK) {
return result;
}
uint8_t cspAddress = cspCookie->getCspAddress();
switch(cspPort) {
case(Ports::CSP_PING): {
initiatePingRequest(cspAddress, querySize);
break;
}
case(Ports::CSP_REBOOT): {
csp_reboot(cspAddress);
break;
}
case(Ports::P60_PORT_GNDWDT_RESET):
case(Ports::P60_PORT_RPARAM): {
/* No CSP fixed port was selected. Send data to the specified port and
* wait for querySize number of bytes */
result = cspTransfer(cspAddress, cspPort, sendData, sendLen,
querySize);
if(result != HasReturnvaluesIF::RETURN_OK){
return HasReturnvaluesIF::RETURN_FAILED;
}
replySize = querySize;
break;
}
default:
sif::error << "CspComIF: Invalid port specified" << std::endl;
break;
}
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CspComIF::getSendSuccess(CookieIF *cookie) {
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CspComIF::requestReceiveMessage(CookieIF *cookie,
size_t requestLen) {
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CspComIF::readReceivedMessage(CookieIF *cookie,
uint8_t** buffer, size_t* size) {
if(cookie == NULL){
return HasReturnvaluesIF::RETURN_FAILED;
}
CspCookie* cspCookie = dynamic_cast<CspCookie*> (cookie);
if(cspCookie == NULL){
return HasReturnvaluesIF::RETURN_FAILED;
}
uint8_t cspAddress = cspCookie->getCspAddress();
*buffer = cspDeviceMap[cspAddress].data();
*size = replySize;
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CspComIF::cspTransfer(uint8_t cspAddress, uint8_t cspPort,
const uint8_t* cmdBuffer, int cmdBufferLen, uint16_t querySize) {
uint32_t timeout_ms = 500;
vectorBufferIter iter = cspDeviceMap.find(cspAddress);
if(iter == cspDeviceMap.end()){
sif::error << "CSP device with address " << cspAddress << " no found in"
<< " device map" << std::endl;
}
uint8_t* replyBuffer = iter->second.data();
uint8_t tmpCmdBuffer[cmdBufferLen];
memcpy(tmpCmdBuffer, cmdBuffer, cmdBufferLen);
csp_conn_t * conn = csp_connect(CSP_PRIO_HIGH, cspAddress, cspPort, 0,
CSP_O_NONE);
int result = csp_transaction_persistent(conn, timeout_ms,
tmpCmdBuffer, cmdBufferLen, replyBuffer, querySize);
if(querySize != 0){
if(result != querySize){
sif::error << "CSP transfer failed to receive all requested bytes "
<< std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
} else {
if(result != 1){
sif::error << "CSP transfer failed" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
}
csp_close(conn);
return HasReturnvaluesIF::RETURN_OK;
}
ReturnValue_t CspComIF::getPortAndQuerySize(const uint8_t** sendData,
size_t* sendLen, uint8_t* cspPort, uint16_t* querySize) {
ReturnValue_t result = SerializeAdapter::deSerialize(cspPort, sendData,
sendLen, SerializeIF::Endianness::BIG);
if(result != HasReturnvaluesIF::RETURN_OK){
sif::error << "CspComIF: Failed to deserialize CSP port from command "
<< "buffer" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
SerializeAdapter::deSerialize(querySize, sendData, sendLen,
SerializeIF::Endianness::BIG);
if(result != HasReturnvaluesIF::RETURN_OK){
sif::error << "CspComIF: Failed to deserialize querySize from command "
<< "buffer" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
return HasReturnvaluesIF::RETURN_OK;
}
void CspComIF::initiatePingRequest(uint8_t cspAddress, uint16_t querySize){
uint32_t timeout_ms = 500;
uint32_t replyTime = csp_ping(cspAddress, timeout_ms, querySize,
CSP_O_NONE);
sif::info << "Ping address: " << cspAddress << ", reply after "
<< replyTime << " ms" << std::endl;
/* Store reply time in reply buffer * */
uint8_t* replyBuffer = cspDeviceMap[cspAddress].data();
memcpy(replyBuffer, &replyTime, sizeof(replyTime));
replySize = sizeof(replyTime);
}

View File

@ -0,0 +1,89 @@
#ifndef BSP_LINUX_COMIF_COOKIES_CSPCOMIF_H_
#define BSP_LINUX_COMIF_COOKIES_CSPCOMIF_H_
#include <fsfw/devicehandlers/DeviceCommunicationIF.h>
#include <fsfw/objectmanager/SystemObject.h>
#include <fsfw/returnvalues/HasReturnvaluesIF.h>
#include <csp/csp.h>
#include <vector>
#include <unordered_map>
/**
* @brief This class serves as the communication interface to devices
* supporting the CSP protocol. As physical layer can0 is used
* in this implementation.
* @author J. Meier
*/
class CspComIF: public DeviceCommunicationIF, public SystemObject {
public:
CspComIF(object_id_t objectId);
virtual ~CspComIF();
ReturnValue_t initializeInterface(CookieIF * cookie) override;
ReturnValue_t sendMessage(CookieIF *cookie, const uint8_t * sendData,
size_t sendLen) override;
ReturnValue_t getSendSuccess(CookieIF *cookie) override;
ReturnValue_t requestReceiveMessage(CookieIF *cookie,
size_t requestLen) override;
ReturnValue_t readReceivedMessage(CookieIF *cookie,
uint8_t **readData, size_t *readLen) override;
private:
/**
* @brief This function initiates the CSP transfer.
*
* @param cspAddress The CSP address of the target device.
* @param cspPort The port of the target device.
* @param timeout The timeout to wait for csp_send and csp_read
* functions. Specifies how long the functions wait
* for a successful operation.
* @param cmdBuffer The data to send.
* @param cmpBuffer The number of bytes to send.
* @param querySize The size of the requested message.
*/
ReturnValue_t cspTransfer(uint8_t cspAddress, uint8_t cspPort,
const uint8_t* cmdBuffer, int cmdBufferLen, uint16_t querySize);
enum Ports {
CSP_PING = 1,
CSP_REBOOT = 4,
P60_PORT_RPARAM = 7,
P60_PORT_GNDWDT_RESET = 9
};
typedef uint8_t node_t;
using vectorBuffer = std::vector<uint8_t>;
using VectorBufferMap = std::unordered_map<node_t, vectorBuffer>;
using vectorBufferIter = VectorBufferMap::iterator;
/* In this map assigns reply buffers to a CSP device */
VectorBufferMap cspDeviceMap;
uint16_t replySize = 0;
/* This is the CSP address of the OBC. */
node_t cspClientAddress = 1;
/* Interface struct for csp protocol stack */
csp_iface_t csp_if;
char canInterface[5] = "can0";
int bitrate = 1000;
/**
* @brief Function to extract the csp port and the query size from the
* command buffer.
*/
ReturnValue_t getPortAndQuerySize(const uint8_t** sendData, size_t* sendLen,
uint8_t* cspPort, uint16_t* querySize);
/**
* @brief This function initiates the ping request.
*/
void initiatePingRequest(uint8_t cspAddress, uint16_t querySize);
};
#endif /* BSP_LINUX_COMIF_COOKIES_CSPCOMIF_H_ */

View File

@ -0,0 +1,16 @@
#include "CspCookie.h"
CspCookie::CspCookie(uint16_t maxReplyLength_, uint8_t cspAddress_) :
maxReplyLength(maxReplyLength_), cspAddress(cspAddress_) {
}
CspCookie::~CspCookie() {
}
uint16_t CspCookie::getMaxReplyLength(){
return maxReplyLength;
}
uint8_t CspCookie::getCspAddress(){
return cspAddress;
}

View File

@ -0,0 +1,27 @@
#ifndef BSP_LINUX_COMIF_COOKIES_CSPCOOKIE_H_
#define BSP_LINUX_COMIF_COOKIES_CSPCOOKIE_H_
#include <fsfw/devicehandlers/CookieIF.h>
#include <stdint.h>
/**
* @brief This is the cookie for devices supporting the CSP (CubeSat Space
* Protocol).
* @author J. Meier
*/
class CspCookie: public CookieIF {
public:
CspCookie(uint16_t maxReplyLength_, uint8_t cspAddress_);
virtual ~CspCookie();
uint16_t getMaxReplyLength();
uint8_t getCspAddress();
private:
uint16_t maxReplyLength;
uint8_t cspAddress;
};
#endif /* BSP_LINUX_COMIF_COOKIES_CSPCOOKIE_H_ */

View File

@ -9,7 +9,7 @@
#include "returnvalues/classIds.h"
#include "events/subsystemIdRanges.h"
#define OBSW_ADD_TEST_CODE 0
#define ADD_TEST_CODE 0
// These defines should be disabled for mission code but are useful for
// debugging.

View File

@ -4,7 +4,7 @@
* \date 06.11.2019
*/
#include <fsfwconfig/devices/logicalAddresses.h>
#include "addresses.h"

View File

@ -0,0 +1,35 @@
/**
* \file addresses.cpp
*
* \date 07.11.2019
*/
#ifndef FSFWCONFIG_DEVICES_ADDRESSES_H_
#define FSFWCONFIG_DEVICES_ADDRESSES_H_
#include <stdint.h>
#include <fsfw/devicehandlers/CookieIF.h>
#include <fsfwconfig/objects/systemObjectList.h>
namespace addresses {
/* Logical addresses have uint32_t datatype */
enum logicalAddresses: address_t {
PCDU,
/* Dummy and Test Addresses */
DUMMY_ECHO = 129,
DUMMY_GPS0 = 130,
DUMMY_GPS1 = 131,
};
/* Addresses of devices supporting the CSP protocol */
enum cspAddresses: uint8_t {
P60DOCK = 4,
ACU = 2,
PDU1 = 3,
/* PDU2 occupies X4 slot of P60Dock */
PDU2 = 6
};
}
#endif /* FSFWCONFIG_DEVICES_ADDRESSES_H_ */

View File

@ -1,26 +0,0 @@
/**
* \file logicalAddresses.cpp
*
* \date 07.11.2019
*/
#ifndef FSFWCONFIG_DEVICES_LOGICALADDRESSES_H_
#define FSFWCONFIG_DEVICES_LOGICALADDRESSES_H_
#include <stdint.h>
#include <fsfw/devicehandlers/CookieIF.h>
#include <fsfwconfig/objects/systemObjectList.h>
namespace addresses {
/* Logical addresses have uint32_t datatype */
enum logicalAddresses: address_t {
PCDU,
/* Dummy and Test Addresses */
DUMMY_ECHO = 129,
DUMMY_GPS0 = 130,
DUMMY_GPS1 = 131,
};
}
#endif /* FSFWCONFIG_DEVICES_LOGICALADDRESSES_H_ */

View File

@ -26,9 +26,17 @@ namespace objects {
TEST_TASK = 0x42694269,
DUMMY_INTERFACE = 0xCAFECAFE,
DUMMY_HANDLER = 0x4400AFFE,
P60DOCK_TEST_TASK = 0x00005060,
/* 0x49 ('I') for Communication Interfaces **/
ARDUINO_COM_IF = 0x49000001
ARDUINO_COM_IF = 0x49000001,
CSP_COM_IF = 0x49000002,
/* 0x44 ('D') for device handlers */
P60DOCK_HANDLER = 0x44000001,
PDU1_HANDLER = 0x44000002,
PDU2_HANDLER = 0x44000003,
ACU_HANDLER = 0x44000004
};
}

View File

@ -28,3 +28,61 @@ ReturnValue_t pst::pollingSequenceInitDefault(FixedTimeslotTaskIF *thisSequence)
}
}
ReturnValue_t pst::gomspacePstInit(FixedTimeslotTaskIF *thisSequence){
uint32_t length = thisSequence->getPeriodMs();
thisSequence->addSlot(objects::P60DOCK_HANDLER,
length * 0, DeviceHandlerIF::PERFORM_OPERATION);
thisSequence->addSlot(objects::PDU1_HANDLER,
length * 0, DeviceHandlerIF::PERFORM_OPERATION);
thisSequence->addSlot(objects::PDU2_HANDLER,
length * 0, DeviceHandlerIF::PERFORM_OPERATION);
thisSequence->addSlot(objects::ACU_HANDLER,
length * 0, DeviceHandlerIF::PERFORM_OPERATION);
thisSequence->addSlot(objects::P60DOCK_HANDLER,
length * 0, DeviceHandlerIF::SEND_WRITE);
thisSequence->addSlot(objects::PDU1_HANDLER,
length * 0, DeviceHandlerIF::SEND_WRITE);
thisSequence->addSlot(objects::PDU2_HANDLER,
length * 0, DeviceHandlerIF::SEND_WRITE);
thisSequence->addSlot(objects::ACU_HANDLER,
length * 0, DeviceHandlerIF::SEND_WRITE);
thisSequence->addSlot(objects::P60DOCK_HANDLER,
length * 0.25, DeviceHandlerIF::GET_WRITE);
thisSequence->addSlot(objects::PDU1_HANDLER,
length * 0.25, DeviceHandlerIF::GET_WRITE);
thisSequence->addSlot(objects::PDU2_HANDLER,
length * 0.25, DeviceHandlerIF::GET_WRITE);
thisSequence->addSlot(objects::ACU_HANDLER,
length * 0.25, DeviceHandlerIF::GET_WRITE);
thisSequence->addSlot(objects::P60DOCK_HANDLER,
length * 0.5, DeviceHandlerIF::SEND_READ);
thisSequence->addSlot(objects::PDU1_HANDLER,
length * 0.5, DeviceHandlerIF::SEND_READ);
thisSequence->addSlot(objects::PDU2_HANDLER,
length * 0.5, DeviceHandlerIF::SEND_READ);
thisSequence->addSlot(objects::ACU_HANDLER,
length * 0.5, DeviceHandlerIF::SEND_READ);
thisSequence->addSlot(objects::P60DOCK_HANDLER,
length * 0.75, DeviceHandlerIF::GET_READ);
thisSequence->addSlot(objects::PDU1_HANDLER,
length * 0.75, DeviceHandlerIF::GET_READ);
thisSequence->addSlot(objects::PDU2_HANDLER,
length * 0.75, DeviceHandlerIF::GET_READ);
thisSequence->addSlot(objects::ACU_HANDLER,
length * 0.75, DeviceHandlerIF::GET_READ);
if (thisSequence->checkSequence() == HasReturnvaluesIF::RETURN_OK) {
return HasReturnvaluesIF::RETURN_OK;
}
else {
sif::error << "Initialization of GomSpace PST failed" << std::endl;
return HasReturnvaluesIF::RETURN_FAILED;
}
}

View File

@ -26,6 +26,13 @@ namespace pst {
/* 0.4 second period init*/
ReturnValue_t pollingSequenceInitDefault(FixedTimeslotTaskIF *thisSequence);
/**
* @brief This function creates the PST for all gomspace devices. They are
* scheduled in a separate PST because the gomspace library uses
* blocking calls when requesting data from devices.
*/
ReturnValue_t gomspacePstInit(FixedTimeslotTaskIF *thisSequence);
}
#endif /* POLLINGSEQUENCEINIT_H_ */

View File

@ -0,0 +1,6 @@
import sys
if sys.version_info >= (3, 0):
from libcsp_py3 import *
else:
from libcsp_py2 import *

123
libcsp/doc/example.rst Normal file
View File

@ -0,0 +1,123 @@
Client and server example
=========================
The following examples show the initialization of the protocol stack and examples of client/server code.
Initialization Sequence
-----------------------
This code initializes the CSP buffer system, device drivers and router core. The example uses the CAN interface function csp_can_tx but the initialization is similar for other interfaces. The loopback interface does not require any explicit initialization.
.. code-block:: c
#include <csp/csp.h>
#include <csp/interfaces/csp_if_can.h>
/* CAN configuration struct for SocketCAN interface "can0" */
struct csp_can_config can_conf = {.ifc = "can0"};
/* Init buffer system with 10 packets of maximum 320 bytes each */
csp_buffer_init(10, 320);
/* Init CSP with address 1 */
csp_init(1);
/* Init the CAN interface with hardware filtering */
csp_can_init(CSP_CAN_MASKED, &can_conf)
/* Setup default route to CAN interface */
csp_route_set(CSP_DEFAULT_ROUTE, &csp_can_tx, CSP_HOST_MAC);
/* Start router task with 500 word stack, OS task priority 1 */
csp_route_start_task(500, 1);
Server
------
This example shows how to create a server task that listens for incoming connections. CSP should be initialized before starting this task. Note the use of `csp_service_handler()` as the default branch in the port switch case. The service handler will automatically reply to ICMP-like requests, such as pings and buffer status requests.
.. code-block:: c
void csp_task(void *parameters) {
/* Create socket without any socket options */
csp_socket_t *sock = csp_socket(CSP_SO_NONE);
/* Bind all ports to socket */
csp_bind(sock, CSP_ANY);
/* Create 10 connections backlog queue */
csp_listen(sock, 10);
/* Pointer to current connection and packet */
csp_conn_t *conn;
csp_packet_t *packet;
/* Process incoming connections */
while (1) {
/* Wait for connection, 10000 ms timeout */
if ((conn = csp_accept(sock, 10000)) == NULL)
continue;
/* Read packets. Timout is 1000 ms */
while ((packet = csp_read(conn, 1000)) != NULL) {
switch (csp_conn_dport(conn)) {
case MY_PORT:
/* Process packet here */
default:
/* Let the service handler reply pings, buffer use, etc. */
csp_service_handler(conn, packet);
break;
}
}
/* Close current connection, and handle next */
csp_close(conn);
}
}
Client
------
This example shows how to allocate a packet buffer, connect to another host and send the packet. CSP should be initialized before calling this function. RDP, XTEA, HMAC and CRC checksums can be enabled per connection, by setting the connection option to a bitwise OR of any combination of `CSP_O_RDP`, `CSP_O_XTEA`, `CSP_O_HMAC` and `CSP_O_CRC`.
.. code-block:: c
int send_packet(void) {
/* Get packet buffer for data */
csp_packet_t *packet = csp_buffer_get(data_size);
if (packet == NULL) {
/* Could not get buffer element */
printf("Failed to get buffer element\\n");
return -1;
}
/* Connect to host HOST, port PORT with regular UDP-like protocol and 1000 ms timeout */
csp_conn_t *conn = csp_connect(CSP_PRIO_NORM, HOST, PORT, 1000, CSP_O_NONE);
if (conn == NULL) {
/* Connect failed */
printf("Connection failed\\n");
/* Remember to free packet buffer */
csp_buffer_free(packet);
return -1;
}
/* Copy message to packet */
char *msg = "HELLO";
strcpy(packet->data, msg);
/* Set packet length */
packet->length = strlen(msg);
/* Send packet */
if (!csp_send(conn, packet, 1000)) {
/* Send failed */
printf("Send failed\\n");
csp_buffer_free(packet);
}
/* Close connection */
csp_close(conn);
return 0
}

17
libcsp/doc/history.rst Normal file
View File

@ -0,0 +1,17 @@
History
=======
The idea was developed by a group of students from Aalborg University in 2008. In 2009 the main developer started working for GomSpace, and CSP became integrated into the GomSpace products. The protocol is based on a 32-bit header containing both transport, network and MAC-layer information. It's implementation is designed for, but not limited to, embedded systems such as the 8-bit AVR microprocessor and the 32-bit ARM and AVR from Atmel. The implementation is written in C and is currently ported to run on FreeRTOS and POSIX and pthreads based operating systems like Linux and BSD. The three letter acronym CSP was originally an abbreviation for CAN Space Protocol because the first MAC-layer driver was written for CAN-bus. Now the physical layer has extended to include spacelink, I2C and RS232, the name was therefore extended to the more general CubeSat Space Protocol without changing the abbreviation.
Satellites using CSP
--------------------
This is the known list of satellites or organisations that uses CSP.
* GomSpace GATOSS GOMX-1
* AAUSAT-3
* EgyCubeSat
* EuroLuna
* NUTS
* Hawaiian Space Flight Laboratory
* GomSpace GOMX-3

95
libcsp/doc/interfaces.rst Normal file
View File

@ -0,0 +1,95 @@
CSP Interfaces
==============
This is an example of how to implement a new layer-2 interface in CSP. The example is going to show how to create a `csp_if_fifo`, using a set of [named pipes](http://en.wikipedia.org/wiki/Named_pipe). The complete interface example code can be found in `examples/fifo.c`. For an example of a fragmenting interface, see the CAN interface in `src/interfaces/csp_if_can.c`.
CSP interfaces are declared in a `csp_iface_t` structure, which sets the interface nexthop function and name. A maximum transmission unit can also be set, which forces CSP to drop outgoing packets above a certain size. The fifo interface is defined as:
.. code-block:: c
#include <csp/csp.h>
#include <csp/csp_interface.h>
csp_iface_t csp_if_fifo = {
.name = "fifo",
.nexthop = csp_fifo_tx,
.mtu = BUF_SIZE,
};
Outgoing traffic
----------------
The nexthop function takes a pointer to a CSP packet and a timeout as parameters. All outgoing packets that are routed to the interface are passed to this function:
.. code-block:: c
int csp_fifo_tx(csp_packet_t *packet, uint32_t timeout) {
write(tx_channel, &packet->length, packet->length + sizeof(uint32_t) + sizeof(uint16_t));
csp_buffer_free(packet);
return 1;
}
In the fifo interface, we simply transmit the header, length field and data using a write to the fifo. CSP does not dictate the wire format, so other interfaces may decide to e.g. ignore the length field if the physical layer provides start/stop flags.
_Important notice: If the transmission succeeds, the interface must free the packet and return 1. If transmission fails, the nexthop function should return 0 and not free the packet, to allow retransmissions by the caller._
Incoming traffic
----------------
The interface also needs to receive incoming packets and pass it to the CSP protocol stack. In the fifo interface, this is handled by a thread that blocks on the incoming fifo and waits for packets:
.. code-block:: c
void * fifo_rx(void * parameters) {
csp_packet_t *buf = csp_buffer_get(BUF_SIZE);
/* Wait for packet on fifo */
while (read(rx_channel, &buf->length, BUF_SIZE) > 0) {
csp_qfifo_write(buf, &csp_if_fifo, NULL);
buf = csp_buffer_get(BUF_SIZE);
}
}
A new CSP buffer is preallocated with csp_buffer_get(). When data is received, the packet is passed to CSP using `csp_qfifo_write()` and a new buffer is allocated for the next packet. In addition to the received packet, `csp_qfifo_write()` takes two additional arguments:
.. code-block:: c
void csp_qfifo_write(csp_packet_t *packet, csp_iface_t *interface, CSP_BASE_TYPE *pxTaskWoken);
The calling interface must be passed in `interface` to avoid routing loops. Furthermore, `pxTaskWoken` must be set to a non-NULL value if the packet is received in an interrupt service routine. If the packet is received in task context, NULL must be passed. 'pxTaskWoken' only applies to FreeRTOS systems, and POSIX system should always set the value to NULL.
`csp_qfifo_write` will either accept the packet or free the packet buffer, so the interface must never free the packet after passing it to CSP.
Initialization
--------------
In order to initialize the interface, and make it available to the router, use the following function found in `csp/csp_interface.h`:
.. code-block:: c
csp_route_add_if(&csp_if_fifo);
This actually happens automatically if you try to call `csp_route_add()` with an interface that is unknown to the router. This may however be removed in the future, in order to ensure that all interfaces are initialised before configuring the routing table. The reason is, that some products released in the future may ship with an empty routing table, which is then configured by a routing protocol rather than a static configuration.
In order to setup a manual static route, use the following example where the default route is set to the fifo interface:
.. code-block:: c
csp_route_set(CSP_DEFAULT_ROUTE, &csp_if_fifo, CSP_NODE_MAC);
All outgoing traffic except loopback, is now passed to the fifo interface's nexthop function.
Building the example
--------------------
The fifo examples can be compiled with:
.. code-block:: bash
% gcc csp_if_fifo.c -o csp_if_fifo -I<CSP PATH>/include -L<CSP PATH>/build -lcsp -lpthread -lrt
The two named pipes are created with:
.. code-block:: bash
% mkfifo server_to_client client_to_server

21
libcsp/doc/libcsp.rst Normal file
View File

@ -0,0 +1,21 @@
.. CSP Documentation master file.
.. _libcsp:
**********************
CubeSat Space Protocol
**********************
.. toctree::
:maxdepth: 3
../README
history
structure
interfaces
memory
protocolstack
topology
mtu
example

28
libcsp/doc/memory.rst Normal file
View File

@ -0,0 +1,28 @@
How CSP uses memory
===================
CSP has been written for small microprocessor systems. The way memory is handled is therefore a tradeoff between the amount used and the code efficiency. This section tries to give some answers to what the memory is used for and how it it used. The primary memory blocks in use by CSP is:
* Routing table
* Ports table
* Connection table
* Buffer pool
* Interface list
Tables
------
The reason for using tables for the routes, ports and connections is speed. When a new packet arrives the core of CSP needs to do a quick lookup in the connection so see if it can find an existing connection to which the packet matches. If this is not found, it will take a lookup in the ports table to see if there are any applications listening on the incoming port number. Another argument of using tables are pre-allocation. The linker will reserve an area of the memory for which the routes and connections can be stored. This avoid an expensive `malloc()` call during initialization of CSP, and practically costs zero CPU instructions. The downside of using tables are the wasted memory used by unallocated ports and connections. For the routing table the argumentation is the same, pre-allocation is better than calling `malloc()`.
Buffer Pool
-----------
The buffer handling system can be compiled for either static allocation or a one-time dynamic allocation of the main memory block. After this, the buffer system is entirely self-contained. All allocated elements are of the same size, so the buffer size must be chosen to be able to handle the maximum possible packet length. The buffer pool uses a queue to store pointers to free buffer elements. First of all, this gives a very quick method to get the next free element since the dequeue is an O(1) operation. Furthermore, since the queue is a protected operating system primitive, it can be accessed from both task-context and interrupt-context. The `csp_buffer_get` version is for task-context and `csp_buffer_get_isr` is for interrupt-context. Using fixed size buffer elements that are preallocated is again a question of speed and safety.
A basic concept of the buffer system is called Zero-Copy. This means that from userspace to the kernel-driver, the buffer is never copied from one buffer to another. This is a big deal for a small microprocessor, where a call to `memcpy()` can be very expensive. In practice when data is inserted into a packet, it is shifted a certain number of bytes in order to allow for a packet header to be prepended at the lower layers. This also means that there is a strict contract between the layers, which data can be modified and where. The buffer object is normally casted to a `csp_packet_t`, but when its given to an interface on the MAC layer it's casted to a `csp_i2c_frame_t` for example.
Interface list
--------------
The interface list is a simple single-ended linked list of references to the interface specification structures. These structures are static const and allocated by the linker. The pointer to this data is inserted into the list one time during setup of the interface. Each entry in the routing table has a direct pointer to the interface element, thereby avoiding list lookup, but the list is needed in order for the dynamic route configuration to know which interfaces are available.

19
libcsp/doc/mtu.rst Normal file
View File

@ -0,0 +1,19 @@
Maximum Transfer Unit
=====================
There are two things limiting the MTU of CSP.
1. The pre-allocated buffer pools allocation size
2. The link layer protocol.
So lets assume that you have made a protocol called KISS with a MTU of 256. The 256 is the total amount of data that you can put into the CSP-packet. However, you need to take the overhead of the link layer into account. Typically this could consist of a length field and/or a start/stop flag. So the actual frame size on the link layer would for example be 256 bytes of data + 2 bytes sync flag + 2 bytes length field.
This requires a buffer allocation of at lest 256 + 2 + 2. However, the CSP packet itself has some reserved bytes in the beginning of the packet (which you can see in csp.h) - so the recommended buffer allocation size is MAX MTU + 16 bytes. In this case the max MTU would be 256.
If you try to pass data which is longer than the MTU, the chance is that you will also make a buffer overflow in the CSP buffer pool. However, lets assume that you have two interfaces one with an MTU of 200 bytes and another with an MTU of 100 bytes. In this case you might successfully transfer 150 bytes over the first interface, but the packet will be rejected once it comes to the second interface.
If you want to increase your MTU of a specific link layer, it is up to the link layer protocol to implement its own fragmentation protocol. A good example is CAN-bus which only allows a frame size of 8 bytes. libcsp have a small protocol for this called the “CAN fragmentation protocol" or CFP for short. This allows data of much larger size to be transferred over the CAN bus.
Okay, but what if you want to transfer 1000 bytes, and the network maximum MTU is 256? Well, since CSP does not include streaming sockets, only packets. Somebody will have to split that data up into chunks. It might be that you application have special knowledge about the datatype you are transmitting, and that it makes sense to split the 1000 byte content into 10 chunks of 100 byte status messages. This, application layer delimitation might be good if you have a situation with packet loss, because your receiver could still make good usage of the partially delivered chunks.
But, what if you just want 1000 bytes transmitted, and you dont care about the fragmentation unit, and also dont want the hassle of writing the fragmentation code yourself? - In this case, libcsp now features a new (still experimental) feature called SFP (small fragmentation protocol) designed to work on the application layer. For this purpose you will not use csp_send and csp_recv, but csp_sfp_send and csp_sfp_recv. This will split your data into chunks of a certain size, enumerate them and transfer over a given connection. If a chunk is missing the SFP client will abort the reception, because SFP does not provide retransmission. If you wish to also have retransmission and orderly delivery you will have to open an RDP connection and send your SFP message to that connection.

View File

@ -0,0 +1,54 @@
The Protocol Stack
==================
The CSP protocol stack includes functionality on all layers of the TCP/IP model:
Layer 1: Drivers
----------------
Lib CSP is not designed for any specific processor or hardware peripheral, but yet these drivers are required in order to work. The intention of LibCSP is not to provide CAN, I2C or UART drivers for all platforms, however some drivers has been included for some platforms. If you do not find your platform supported, it is quite simple to add a driver that conforms to the CSP interfaces. For example the I2C driver just requires three functions: `init`, `send` and `recv`. For good stability and performance interrupt driven drivers are preferred in favor of polled drivers. Where applicable also DMA usage is recommended.
Layer 2: MAC interfaces
-----------------------
CSP has interfaces for I2C, CAN, RS232 (KISS) and Loopback. The layer 2 protocol software defines a frame-format that is suitable for the media. CSP can be easily extended with implementations for even more links. For example a radio-link and IP-networks. The file `csp_interface.h` declares the rx and tx functions needed in order to define a network interface in CSP. During initialisation of CSP each interface will be inserted into a linked list of interfaces that is available to the router. In cases where link-layer addresses are required, such as I2C, the routing table supports specifying next-hop link-layer address directly. This avoids the need to implement an address resolution protocol to translate CSP addresses to I2C addresses.
Layer 3: Network Router
-----------------------
The router core is the backbone of the CSP implementation. The router works by looking at a 32-bit CSP header which contains the delivery and source address together with port numbers for the connection. Each router supports both local delivery and forwarding of frames to another destination. Frames will never exit the router on the same interface that they arrives at, this concept is called split horizon, and helps prevent routing loops.
The main purpose of the router is to accept incoming packets and deliver them to the right message queue. Therefore, in order to listen on a port-number on the network, a task must create a socket and call the accept() call. This will make the task block and wait for incoming traffic, just like a web-server or similar. When an incoming connection is opened, the task is woken. Depending on the task-priority, the task can even preempt another task and start execution immediately.
There is no routing protocol for automatic route discovery, all routing tables are pre-programmed into the subsystems. The table itself contains a separate route to each of the possible 32 nodes in the network and the additional default route. This means that the overall topology must be decided before putting sub-systems together, as explained in the `topology.md` file. However CSP has an extension on port zero CMP (CSP management protocol), which allows for over-the-network routing table configuration. This has the advantage that default routes could be changed if for example the primary radio fails, and the secondary should be used instead.
Layer 4: Transport Layer
------------------------
LibCSP implements two different Transport Layer protocols, they are called UDP (unreliable datagram protocol) and RDP (reliable datagram protocol). The name UDP has not been chosen to be an exact replica of the UDP (user datagram protocol) known from the TCP/IP model, but they have certain similarities.
The most important thing to notice is that CSP is entirely a datagram service. There is no stream based service like TCP. A datagram is defined a block of data with a specified size and structure. This block enters the transport layer as a single datagram and exits the transport layer in the other end as a single datagram. CSP preserves this structure all the way to the physical layer for I2C, KISS and Loopback interfaces are used. The CAN-bus interface has to fragment the datagram into CAN-frames of 8 bytes, however only a fully completed datagram will arrive at the receiver.
UDP
^^^
UDP uses a simple transmission model without implicit hand-shaking dialogues for guaranteeing reliability, ordering, or data integrity. Thus, UDP provides an unreliable service and datagrams may arrive out of order, appear duplicated, or go missing without notice. UDP assumes that error checking and correction is either not necessary or performed in the application, avoiding the overhead of such processing at the network interface level. Time-sensitive applications often use UDP because dropping packets is preferable to waiting for delayed packets, which may not be an option in a real-time system.
UDP is very practical to implement request/reply based communication where a single packet forms the request and a single packet forms the reply. In this case a typical request and wait protocol is used between the client and server, which will simply return an error if a reply is not received within a specified time limit. An error would normally lead to a retransmission of the request from the user or operator which sent the request.
While UDP is very simple, it also has some limitations. Normally a human in the loop is a good thing when operating the satellite over UDP. But when it comes to larger file transfers, the human becomes the bottleneck. When a high-speed file transfer is initiated data acknowledgment should be done automatically in order to speed up the transfer. This is where the RDP protocol can help.
RDP
^^^
CSP provides a transport layer extension called RDP (reliable datagram protocol) which is an implementation of RFC908 and RFC1151. RDP provides a few additional features:
* Three-way handshake
* Flow Control
* Data-buffering
* Packet re-ordering
* Retransmission
* Windowing
* Extended Acknowledgment
For more information on this, please refer to RFC908.

27
libcsp/doc/structure.rst Normal file
View File

@ -0,0 +1,27 @@
Structure
=========
The Cubesat Space Protocol library is structured as shown in the following table:
============================= =========================================================================
**Folder** **Description**
============================= =========================================================================
libcsp/include/csp Main include files
libcsp/include/csp/arch Architecture include files
libcsp/include/csp/interfaces Interface include files
libcsp/include/csp/drivers Drivers include files
libcsp/src Main modules for CSP: io, router, connections, services
libcsp/src/interfaces Interface modules for CAN, I2C, KISS, LOOP and ZMQHUB
libcsp/src/drivers/can Driver for CAN
libcsp/src/drivers/usart Driver for USART
libcsp/src/arch/freertos FreeRTOS architecture module
libcsp/src/arch/macosx Mac OS X architecture module
libcsp/src/arch/posix Posix architecture module
libcsp/src/arch/windows Windows architecture module
libcsp/src/rtable Routing table module
libcsp/transport Transport module, UDP and RDP
libcsp/crypto Crypto module
libcsp/utils Utilities
libcsp/bindings/python Python wrapper for libcsp
libcsp/examples CSP examples (source code)
libasf/doc The doc folder contains the source code for this documentation
============================= =========================================================================

26
libcsp/doc/topology.rst Normal file
View File

@ -0,0 +1,26 @@
Network Topology
================
CSP uses a network oriented terminology similar to what is known from the Internet and the TCP/IP model. A CSP network can be configured for several different topologies. The most common topology is to create two segments, one for the Satellite and one for the Ground-Station.
.. code-block:: none
I2C BUS
_______________________________
/ | | | \
+---+ +---+ +---+ +---+ +---+
|OBC| |COM| |EPS| |PL1| |PL2| Nodes 0 - 7 (Space segment)
+---+ +---+ +---+ +---+ +---+
^
| Radio
v
+---+ +----+
|TNC| ------- | PC | Nodes 8 - 15 (Ground segment)
+---+ USB +----+
Node 9 Node 10
The address range, from 0 to 15, has been segmented into two equal size segments. This allows for easy routing in the network. All addresses starting with binary 1 is on the ground-segment, and all addresses starting with 0 is on the space segment. From CSP v1.0 the address space has been increased to 32 addresses, 0 to 31. But for legacy purposes, the old 0 to 15 is still used in most products.
The network is configured using static routes initialised at boot-up of each sub-system. This means that the basic routing table must be assigned compile-time of each subsystem. However each node supports assigning an individual route to every single node in the network and can be changed run-time. This means that the network topology can be easily reconfigured after startup.

View File

@ -0,0 +1,165 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <pthread.h>
#include <stdint.h>
#include <csp/csp.h>
#include <csp/csp_interface.h>
#define TYPE_SERVER 1
#define TYPE_CLIENT 2
#define PORT 10
#define BUF_SIZE 250
pthread_t rx_thread;
int rx_channel, tx_channel;
int csp_fifo_tx(csp_iface_t *ifc, csp_packet_t *packet, uint32_t timeout);
csp_iface_t csp_if_fifo = {
.name = "fifo",
.nexthop = csp_fifo_tx,
.mtu = BUF_SIZE,
};
int csp_fifo_tx(csp_iface_t *ifc, csp_packet_t *packet, uint32_t timeout) {
/* Write packet to fifo */
if (write(tx_channel, &packet->length, packet->length + sizeof(uint32_t) + sizeof(uint16_t)) < 0)
printf("Failed to write frame\r\n");
csp_buffer_free(packet);
return CSP_ERR_NONE;
}
void * fifo_rx(void * parameters) {
csp_packet_t *buf = csp_buffer_get(BUF_SIZE);
/* Wait for packet on fifo */
while (read(rx_channel, &buf->length, BUF_SIZE) > 0) {
csp_qfifo_write(buf, &csp_if_fifo, NULL);
buf = csp_buffer_get(BUF_SIZE);
}
return NULL;
}
int main(int argc, char **argv) {
int me, other, type;
const char *message = "Testing CSP";
const char *rx_channel_name;
const char *tx_channel_name;
csp_socket_t *sock;
csp_conn_t *conn;
csp_packet_t *packet;
/* Run as either server or client */
if (argc != 2) {
printf("usage: %s <server/client>\r\n", argv[0]);
return -1;
}
/* Set type */
if (strcmp(argv[1], "server") == 0) {
me = 1;
other = 2;
tx_channel_name = "server_to_client";
rx_channel_name = "client_to_server";
type = TYPE_SERVER;
} else if (strcmp(argv[1], "client") == 0) {
me = 2;
other = 1;
tx_channel_name = "client_to_server";
rx_channel_name = "server_to_client";
type = TYPE_CLIENT;
} else {
printf("Invalid type. Must be either 'server' or 'client'\r\n");
return -1;
}
/* Init CSP and CSP buffer system */
if (csp_init(me) != CSP_ERR_NONE || csp_buffer_init(10, 300) != CSP_ERR_NONE) {
printf("Failed to init CSP\r\n");
return -1;
}
tx_channel = open(tx_channel_name, O_RDWR);
if (tx_channel < 0) {
printf("Failed to open TX channel\r\n");
return -1;
}
rx_channel = open(rx_channel_name, O_RDWR);
if (rx_channel < 0) {
printf("Failed to open RX channel\r\n");
return -1;
}
/* Start fifo RX task */
pthread_create(&rx_thread, NULL, fifo_rx, NULL);
/* Set default route and start router */
csp_route_set(CSP_DEFAULT_ROUTE, &csp_if_fifo, CSP_NODE_MAC);
csp_route_start_task(0, 0);
/* Create socket and listen for incoming connections */
if (type == TYPE_SERVER) {
sock = csp_socket(CSP_SO_NONE);
csp_bind(sock, PORT);
csp_listen(sock, 5);
}
/* Super loop */
while (1) {
if (type == TYPE_SERVER) {
/* Process incoming packet */
conn = csp_accept(sock, 1000);
if (conn) {
packet = csp_read(conn, 0);
if (packet)
printf("Received: %s\r\n", packet->data);
csp_buffer_free(packet);
csp_close(conn);
}
} else {
/* Send a new packet */
packet = csp_buffer_get(strlen(message));
if (packet) {
strcpy((char *) packet->data, message);
packet->length = strlen(message);
conn = csp_connect(CSP_PRIO_NORM, other, PORT, 1000, CSP_O_NONE);
printf("Sending: %s\r\n", message);
if (!conn || !csp_send(conn, packet, 1000))
return -1;
csp_close(conn);
}
sleep(1);
}
}
close(rx_channel);
close(tx_channel);
return 0;
}

View File

@ -0,0 +1,225 @@
#include <Windows.h>
#include <process.h>
#include <stdio.h>
#include <ctype.h>
#include <stddef.h>
#undef interface
#include <csp/csp.h>
#include <csp/csp_interface.h>
#define PIPE_BUFSIZE 1024
#define TYPE_SERVER 1
#define TYPE_CLIENT 2
#define PORT 10
#define BUF_SIZE 250
static LPCTSTR pipeName = TEXT("\\\\.\\pipe\\CSP_Pipe");
static HANDLE pipe = INVALID_HANDLE_VALUE;
unsigned WINAPI fifo_rx(void *);
unsigned WINAPI pipe_listener(void *);
void printError(void);
int csp_fifo_tx(csp_packet_t *packet, uint32_t timeout);
csp_iface_t csp_if_fifo = {
.name = "fifo",
.nexthop = csp_fifo_tx,
.mtu = BUF_SIZE,
};
int csp_fifo_tx(csp_packet_t *packet, uint32_t timeout) {
printf("csp_fifo_tx tid: %lu\n", GetCurrentThreadId());
DWORD expectedSent = packet->length + sizeof(uint32_t) + sizeof(uint16_t);
DWORD actualSent;
/* Write packet to fifo */
if( !WriteFile(pipe, &packet->length, expectedSent, &actualSent, NULL)
|| actualSent != expectedSent ) {
printError();
}
csp_buffer_free(packet);
return CSP_ERR_NONE;
}
int main(int argc, char *argv[]) {
int me, other, type;
char *message = "Testing CSP";
csp_socket_t *sock = NULL;
csp_conn_t *conn = NULL;
csp_packet_t *packet = NULL;
/* Run as either server or client */
if (argc != 2) {
printf("usage: server <server/client>\r\n");
return -1;
}
/* Set type */
if (strcmp(argv[1], "server") == 0) {
me = 1;
other = 2;
type = TYPE_SERVER;
} else if (strcmp(argv[1], "client") == 0) {
me = 2;
other = 1;
type = TYPE_CLIENT;
} else {
printf("Invalid type. Must be either 'server' or 'client'\r\n");
return -1;
}
/* Init CSP and CSP buffer system */
if (csp_init(me) != CSP_ERR_NONE || csp_buffer_init(10, 300) != CSP_ERR_NONE) {
printf("Failed to init CSP\r\n");
return -1;
}
if( type == TYPE_SERVER ) {
_beginthreadex(NULL, 0, pipe_listener, NULL, 0, 0);
} else {
pipe = CreateFile(
pipeName,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
OPEN_EXISTING,
0,
NULL);
if( pipe == INVALID_HANDLE_VALUE ) {
printError();
return -1;
}
}
/* Set default route and start router */
csp_route_set(CSP_DEFAULT_ROUTE, &csp_if_fifo, CSP_NODE_MAC);
csp_route_start_task(0, 0);
/* Create socket and listen for incoming connections */
if (type == TYPE_SERVER) {
sock = csp_socket(CSP_SO_NONE);
csp_bind(sock, PORT);
csp_listen(sock, 5);
}
/* Super loop */
while (1) {
if (type == TYPE_SERVER) {
/* Process incoming packet */
conn = csp_accept(sock, 1000);
if (conn) {
packet = csp_read(conn, 0);
if (packet)
printf("Received: %s\r\n", packet->data);
csp_buffer_free(packet);
csp_close(conn);
}
} else {
/* Send a new packet */
packet = csp_buffer_get(strlen(message));
if (packet) {
strcpy((char *) packet->data, message);
packet->length = strlen(message);
conn = csp_connect(CSP_PRIO_NORM, other, PORT, 1000, CSP_O_NONE);
printf("Sending: %s\r\n", message);
if (!conn || !csp_send(conn, packet, 1000))
return -1;
csp_close(conn);
Sleep(1000);
}
}
}
return 0;
}
void printError(void) {
LPTSTR messageBuffer = NULL;
DWORD errorCode = GetLastError();
DWORD formatMessageRet;
formatMessageRet = FormatMessage(
FORMAT_MESSAGE_ALLOCATE_BUFFER |
FORMAT_MESSAGE_FROM_SYSTEM |
FORMAT_MESSAGE_IGNORE_INSERTS,
NULL,
errorCode,
MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
(LPTSTR)&messageBuffer,
0,
NULL);
if( !formatMessageRet ) {
wprintf(L"FormatMessage error, code: %lu\n", GetLastError());
return;
}
printf("%s\n", messageBuffer);
LocalFree(messageBuffer);
}
unsigned WINAPI pipe_listener(void *parameters) {
while(1) {
HANDLE pipe = CreateNamedPipe(
pipeName,
PIPE_ACCESS_DUPLEX,
PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT,
PIPE_UNLIMITED_INSTANCES,
PIPE_BUFSIZE,
PIPE_BUFSIZE,
0,
NULL);
BOOL clientConnected;
if( pipe == INVALID_HANDLE_VALUE ) {
printf("Error creating named pipe. Code %lu\n", GetLastError());
return -1;
}
// True if client connects *after* server called ConnectNamedPipe
// or *between* CreateNamedPipe and ConnectNamedPipe
clientConnected =
ConnectNamedPipe(pipe, NULL) ? TRUE : GetLastError()==ERROR_PIPE_CONNECTED;
printf("Client connected!\n");
if( !clientConnected ) {
printf("Failure while listening for clients. Code %lu\n", GetLastError());
CloseHandle(pipe);
return -1;
}
printf("Create client thread\n");
_beginthreadex(NULL, 0, fifo_rx, (PVOID)pipe, 0, 0);
}
return 0;
}
unsigned WINAPI fifo_rx(void *handle) {
printf("fifo_rx tid: %lu\n", GetCurrentThreadId());
HANDLE pipe = (HANDLE) handle;
csp_packet_t *buf = csp_buffer_get(BUF_SIZE);
DWORD bytesRead;
BOOL readSuccess;
while(1) {
readSuccess =
ReadFile(pipe, &buf->length, BUF_SIZE, &bytesRead, NULL);
if( !readSuccess || bytesRead == 0 ) {
csp_buffer_free(buf);
printError();
break;
}
csp_qfifo_write(buf, &csp_if_fifo, NULL);
buf = csp_buffer_get(BUF_SIZE);
}
printf("Closing pipe to client\n");
CloseHandle(pipe);
return 0;
}

151
libcsp/examples/kiss.c Normal file
View File

@ -0,0 +1,151 @@
/**
* Build this example on linux with:
* ./waf configure --enable-examples --enable-if-kiss --with-driver-usart=linux --enable-crc32 clean build
*/
#include <stdio.h>
#include <csp/csp.h>
#include <csp/interfaces/csp_if_kiss.h>
#include <csp/drivers/usart.h>
#include <csp/arch/csp_thread.h>
#define PORT 10
#define MY_ADDRESS 1
#define SERVER_TIDX 0
#define CLIENT_TIDX 1
#define USART_HANDLE 0
CSP_DEFINE_TASK(task_server) {
int running = 1;
csp_socket_t *socket = csp_socket(CSP_SO_NONE);
csp_conn_t *conn;
csp_packet_t *packet;
csp_packet_t *response;
response = csp_buffer_get(sizeof(csp_packet_t) + 2);
if( response == NULL ) {
fprintf(stderr, "Could not allocate memory for response packet!\n");
return CSP_TASK_RETURN;
}
response->data[0] = 'O';
response->data[1] = 'K';
response->length = 2;
csp_bind(socket, CSP_ANY);
csp_listen(socket, 5);
printf("Server task started\r\n");
while(running) {
if( (conn = csp_accept(socket, 10000)) == NULL ) {
continue;
}
while( (packet = csp_read(conn, 100)) != NULL ) {
switch( csp_conn_dport(conn) ) {
case PORT:
if( packet->data[0] == 'q' )
running = 0;
csp_buffer_free(packet);
csp_send(conn, response, 1000);
break;
default:
csp_service_handler(conn, packet);
break;
}
}
csp_close(conn);
}
csp_buffer_free(response);
return CSP_TASK_RETURN;
}
CSP_DEFINE_TASK(task_client) {
char outbuf = 'q';
char inbuf[3] = {0};
int pingResult;
for(int i = 50; i <= 200; i+= 50) {
pingResult = csp_ping(MY_ADDRESS, 1000, 100, CSP_O_NONE);
printf("Ping with payload of %d bytes, took %d ms\n", i, pingResult);
csp_sleep_ms(1000);
}
csp_ps(MY_ADDRESS, 1000);
csp_sleep_ms(1000);
csp_memfree(MY_ADDRESS, 1000);
csp_sleep_ms(1000);
csp_buf_free(MY_ADDRESS, 1000);
csp_sleep_ms(1000);
csp_uptime(MY_ADDRESS, 1000);
csp_sleep_ms(1000);
csp_transaction(0, MY_ADDRESS, PORT, 1000, &outbuf, 1, inbuf, 2);
printf("Quit response from server: %s\n", inbuf);
return CSP_TASK_RETURN;
}
int main(int argc, char **argv) {
csp_debug_toggle_level(CSP_PACKET);
csp_debug_toggle_level(CSP_INFO);
csp_buffer_init(10, 300);
csp_init(MY_ADDRESS);
struct usart_conf conf;
#if defined(CSP_WINDOWS)
conf.device = argc != 2 ? "COM4" : argv[1];
conf.baudrate = CBR_9600;
conf.databits = 8;
conf.paritysetting = NOPARITY;
conf.stopbits = ONESTOPBIT;
conf.checkparity = FALSE;
#elif defined(CSP_POSIX)
conf.device = argc != 2 ? "/dev/ttyUSB0" : argv[1];
conf.baudrate = 500000;
#elif defined(CSP_MACOSX)
conf.device = argc != 2 ? "/dev/tty.usbserial-FTSM9EGE" : argv[1];
conf.baudrate = 115200;
#endif
/* Run USART init */
usart_init(&conf);
/* Setup CSP interface */
static csp_iface_t csp_if_kiss;
static csp_kiss_handle_t csp_kiss_driver;
csp_kiss_init(&csp_if_kiss, &csp_kiss_driver, usart_putc, usart_insert, "KISS");
/* Setup callback from USART RX to KISS RS */
void my_usart_rx(uint8_t * buf, int len, void * pxTaskWoken) {
csp_kiss_rx(&csp_if_kiss, buf, len, pxTaskWoken);
}
usart_set_callback(my_usart_rx);
csp_route_set(MY_ADDRESS, &csp_if_kiss, CSP_NODE_MAC);
csp_route_start_task(0, 0);
csp_conn_print_table();
csp_route_print_table();
csp_route_print_interfaces();
csp_thread_handle_t handle_server;
csp_thread_create(task_server, "SERVER", 1000, NULL, 0, &handle_server);
csp_thread_handle_t handle_client;
csp_thread_create(task_client, "CLIENT", 1000, NULL, 0, &handle_client);
/* Wait for program to terminate (ctrl + c) */
while(1) {
csp_sleep_ms(1000000);
}
return 0;
}

View File

@ -0,0 +1,42 @@
#!/usr/bin/python
# libcsp must be build with at least these options to run this example client:
# ./waf distclean configure build --enable-bindings --enable-crc32 --enable-rdp --enable-if-zmq --with-driver-usart=linux --enable-if-kiss --enable-xtea --enable-if-can --enable-can-socketcan --enable-hmac --enable-examples
# Can be run from root of libcsp like this:
# LD_LIBRARY_PATH=build PYTHONPATH=bindings/python:build python examples/python_bindings_example_client.py
#
import os
import time
import libcsp as csp
if __name__ == "__main__":
csp.buffer_init(10, 300)
csp.init(28)
csp.zmqhub_init(28, "localhost")
csp.rtable_set(27, 5, "ZMQHUB")
csp.route_start_task()
## allow router task startup
time.sleep(1)
## cmp_ident
(rc, host, model, rev, date, time) = csp.cmp_ident(27)
if rc == csp.CSP_ERR_NONE:
print (host, model, rev, date, time)
else:
print ("error in cmp_ident, rc=%i" % (rc))
## transaction
outbuf = bytearray().fromhex('01')
inbuf = bytearray(1)
print ("using csp_transaction to send a single byte")
if csp.transaction(0, 27, 10, 1000, outbuf, inbuf) < 1:
print ("csp_transaction failed")
else:
print ("got reply, data=" + ''.join('{:02x}'.format(x) for x in inbuf))

View File

@ -0,0 +1,30 @@
#!/usr/bin/python
# libcsp must be build with at least these options to run this example client:
# ./waf distclean configure build --enable-bindings --enable-crc32 --enable-rdp --enable-if-zmq --with-driver-usart=linux --enable-if-kiss --enable-xtea --enable-if-can --enable-can-socketcan --enable-hmac --enable-examples
# Can be run from root of libcsp like this:
# LD_LIBRARY_PATH=build PYTHONPATH=bindings/python:build python examples/python_bindings_example_client.py
#
import os
import time
import libcsp as csp
if __name__ == "__main__":
csp.buffer_init(10, 300)
csp.init(28)
csp.can_socketcan_init("can0")
csp.rtable_set(4, 5, "CAN")
csp.route_start_task()
## allow router task startup
time.sleep(1)
node = 4
if csp.ping(node) < 0:
print ("Unable to ping node %d"%(node))

View File

@ -0,0 +1,72 @@
#!/usr/bin/python
# libcsp must be build with at least these options to run this example server:
# ./waf distclean configure build --enable-bindings --enable-crc32 --enable-rdp --enable-if-zmq --with-driver-usart=linux --enable-if-kiss --enable-xtea --enable-if-can --enable-can-socketcan --enable-hmac --enable-examples
# Can be run from root of libcsp like this:
# LD_LIBRARY_PATH=build PYTHONPATH=bindings/python:build python examples/python_bindings_example_server.py
#
import os
import time
import sys
import libcsp as csp
import subprocess
if __name__ == "__main__":
# start a zmqproxy to transport messages to and from the client
zmqp = subprocess.Popen('build/zmqproxy')
# init csp
csp.buffer_init(10, 300)
csp.init(27)
csp.zmqhub_init(27, "localhost")
csp.rtable_set(28, 5, "ZMQHUB")
csp.route_start_task()
# set identity
csp.set_hostname("test_service")
csp.set_model("bindings")
csp.set_revision("1.2.3")
# and read it back
print (csp.get_hostname())
print (csp.get_model())
print (csp.get_revision())
# start listening for packets...
sock = csp.socket()
csp.bind(sock, csp.CSP_ANY)
csp.listen(sock)
while True:
conn = csp.accept(sock)
if not conn:
continue
print ("connection: source=%i:%i, dest=%i:%i" % (csp.conn_src(conn),
csp.conn_sport(conn),
csp.conn_dst(conn),
csp.conn_dport(conn)))
while True:
packet = csp.read(conn)
if not packet:
break
if csp.conn_dport(conn) == 10:
data = bytearray(csp.packet_get_data(packet))
length = csp.packet_get_length(packet)
print ("got packet, len=" + str(length) + ", data=" + ''.join('{:02x}'.format(x) for x in data))
data[0] = data[0] + 1
reply_packet = csp.buffer_get(1)
if reply_packet:
csp.packet_set_data(reply_packet, data)
csp.sendto_reply(packet, reply_packet, csp.CSP_O_NONE)
csp.buffer_free(packet)
else:
csp.service_handler(conn, packet)
csp.close(conn)

200
libcsp/examples/simple.c Normal file
View File

@ -0,0 +1,200 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <csp/csp.h>
/* Using un-exported header file.
* This is allowed since we are still in libcsp */
#include <csp/arch/csp_thread.h>
/** Example defines */
#define MY_ADDRESS 1 // Address of local CSP node
#define MY_PORT 10 // Port to send test traffic to
CSP_DEFINE_TASK(task_server) {
/* Create socket without any socket options */
csp_socket_t *sock = csp_socket(CSP_SO_NONE);
/* Bind all ports to socket */
csp_bind(sock, CSP_ANY);
/* Create 10 connections backlog queue */
csp_listen(sock, 10);
/* Pointer to current connection and packet */
csp_conn_t *conn;
csp_packet_t *packet;
/* Process incoming connections */
while (1) {
/* Wait for connection, 10000 ms timeout */
if ((conn = csp_accept(sock, 10000)) == NULL)
continue;
/* Read packets. Timout is 100 ms */
while ((packet = csp_read(conn, 100)) != NULL) {
switch (csp_conn_dport(conn)) {
case MY_PORT:
/* Process packet here */
printf("Packet received on MY_PORT: %s\r\n", (char *) packet->data);
csp_buffer_free(packet);
break;
default:
/* Let the service handler reply pings, buffer use, etc. */
csp_service_handler(conn, packet);
break;
}
}
/* Close current connection, and handle next */
csp_close(conn);
}
return CSP_TASK_RETURN;
}
CSP_DEFINE_TASK(task_client) {
csp_packet_t * packet;
csp_conn_t * conn;
while (1) {
/**
* Try ping
*/
csp_sleep_ms(1000);
int result = csp_ping(MY_ADDRESS, 100, 100, CSP_O_NONE);
printf("Ping result %d [ms]\r\n", result);
csp_sleep_ms(1000);
/**
* Try data packet to server
*/
/* Get packet buffer for data */
packet = csp_buffer_get(100);
if (packet == NULL) {
/* Could not get buffer element */
printf("Failed to get buffer element\n");
return CSP_TASK_RETURN;
}
/* Connect to host HOST, port PORT with regular UDP-like protocol and 1000 ms timeout */
conn = csp_connect(CSP_PRIO_NORM, MY_ADDRESS, MY_PORT, 1000, CSP_O_NONE);
if (conn == NULL) {
/* Connect failed */
printf("Connection failed\n");
/* Remember to free packet buffer */
csp_buffer_free(packet);
return CSP_TASK_RETURN;
}
/* Copy dummy data to packet */
const char *msg = "Hello World";
strcpy((char *) packet->data, msg);
/* Set packet length */
packet->length = strlen(msg);
/* Send packet */
if (!csp_send(conn, packet, 1000)) {
/* Send failed */
printf("Send failed\n");
csp_buffer_free(packet);
}
/* Close connection */
csp_close(conn);
}
return CSP_TASK_RETURN;
}
int main(int argc, char * argv[]) {
/**
* Initialise CSP,
* No physical interfaces are initialised in this example,
* so only the loopback interface is registered.
*/
/* Init buffer system with 10 packets of maximum 300 bytes each */
printf("Initialising CSP\r\n");
csp_buffer_init(5, 300);
/* Init CSP with address MY_ADDRESS */
csp_init(MY_ADDRESS);
/* Start router task with 500 word stack, OS task priority 1 */
csp_route_start_task(500, 1);
/* Enable debug output from CSP */
if ((argc > 1) && (strcmp(argv[1], "-v") == 0)) {
printf("Debug enabed\r\n");
csp_debug_toggle_level(3);
csp_debug_toggle_level(4);
printf("Conn table\r\n");
csp_conn_print_table();
printf("Route table\r\n");
csp_route_print_table();
printf("Interfaces\r\n");
csp_route_print_interfaces();
}
/**
* Initialise example threads, using pthreads.
*/
/* Server */
printf("Starting Server task\r\n");
csp_thread_handle_t handle_server;
csp_thread_create(task_server, "SERVER", 1000, NULL, 0, &handle_server);
/* Client */
printf("Starting Client task\r\n");
csp_thread_handle_t handle_client;
csp_thread_create(task_client, "SERVER", 1000, NULL, 0, &handle_client);
/* Wait for execution to end (ctrl+c) */
while(1) {
csp_sleep_ms(100000);
}
return 0;
}

View File

@ -0,0 +1,82 @@
#include <zmq.h>
#include <assert.h>
#include <stdio.h>
#include <pthread.h>
#include <malloc.h>
#include <unistd.h>
#include <csp/csp.h>
static void * task_capture(void *ctx) {
/* Subscriber (RX) */
void *subscriber = zmq_socket(ctx, ZMQ_SUB);
assert(zmq_connect(subscriber, "tcp://localhost:7000") == 0);
assert(zmq_setsockopt(subscriber, ZMQ_SUBSCRIBE, "", 0) == 0);
while (1) {
zmq_msg_t msg;
zmq_msg_init_size(&msg, 1024);
/* Receive data */
if (zmq_msg_recv(&msg, subscriber, 0) < 0) {
zmq_msg_close(&msg);
csp_log_error("ZMQ: %s\r\n", zmq_strerror(zmq_errno()));
continue;
}
int datalen = zmq_msg_size(&msg);
if (datalen < 5) {
csp_log_warn("ZMQ: Too short datalen: %u\r\n", datalen);
while(zmq_msg_recv(&msg, subscriber, ZMQ_NOBLOCK) > 0)
zmq_msg_close(&msg);
continue;
}
/* Create new csp packet */
csp_packet_t * packet = malloc(1024);
if (packet == NULL) {
zmq_msg_close(&msg);
continue;
}
/* Copy the data from zmq to csp */
char * satidptr = ((char *) &packet->id) - 1;
memcpy(satidptr, zmq_msg_data(&msg), datalen);
packet->length = datalen - 4 - 1;
printf("Input: Src %u, Dst %u, Dport %u, Sport %u, Pri %u, Flags 0x%02X, Size %"PRIu16"\r\n",
packet->id.src, packet->id.dst, packet->id.dport,
packet->id.sport, packet->id.pri, packet->id.flags, packet->length);
free(packet);
zmq_msg_close(&msg);
}
}
int main(int argc, char ** argv) {
/**
* ZMQ PROXY
*/
void * ctx = zmq_ctx_new();
assert(ctx);
void *frontend = zmq_socket(ctx, ZMQ_XSUB);
assert(frontend);
assert(zmq_bind (frontend, "tcp://*:6000") == 0);
void *backend = zmq_socket(ctx, ZMQ_XPUB);
assert(backend);
assert(zmq_bind(backend, "tcp://*:7000") == 0);
pthread_t capworker;
pthread_create(&capworker, NULL, task_capture, ctx);
printf("Starting ZMQproxy\r\n");
zmq_proxy(frontend, backend, NULL);
printf("Closing ZMQproxy\r\n");
zmq_ctx_destroy(ctx);
return 0;
}

View File

@ -0,0 +1,60 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_CLOCK_H_
#define _CSP_CLOCK_H_
/**
@file
Clock API.
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/**
Cross-platform timestamp.
*/
typedef struct {
//! Seconds
uint32_t tv_sec;
//! Nano-seconds.
uint32_t tv_nsec;
} csp_timestamp_t;
/**
Get time - must be implemented by the user.
*/
__attribute__((weak)) extern void clock_get_time(csp_timestamp_t * time);
/**
Set time - must be implemented by the user.
*/
__attribute__((weak)) extern void clock_set_time(csp_timestamp_t * time);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_CLOCK_H_

View File

@ -0,0 +1,39 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_MALLOC_H_
#define _CSP_MALLOC_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <stddef.h>
#include <stdlib.h>
void * csp_malloc(size_t size);
void csp_free(void * ptr);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_MALLOC_H_

View File

@ -0,0 +1,49 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_QUEUE_H_
#define _CSP_QUEUE_H_
#ifdef __cplusplus
extern "C" {
#endif
#define CSP_QUEUE_FULL 0
#define CSP_QUEUE_ERROR 0
#define CSP_QUEUE_OK 1
typedef void * csp_queue_handle_t;
#include <stdint.h>
#include <csp/csp.h>
csp_queue_handle_t csp_queue_create(int length, size_t item_size);
void csp_queue_remove(csp_queue_handle_t queue);
int csp_queue_enqueue(csp_queue_handle_t handle, void *value, uint32_t timeout);
int csp_queue_enqueue_isr(csp_queue_handle_t handle, void * value, CSP_BASE_TYPE * task_woken);
int csp_queue_dequeue(csp_queue_handle_t handle, void *buf, uint32_t timeout);
int csp_queue_dequeue_isr(csp_queue_handle_t handle, void * buf, CSP_BASE_TYPE * task_woken);
int csp_queue_size(csp_queue_handle_t handle);
int csp_queue_size_isr(csp_queue_handle_t handle);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_QUEUE_H_

View File

@ -0,0 +1,109 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_SEMAPHORE_H_
#define _CSP_SEMAPHORE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
/* POSIX interface */
#if defined(CSP_POSIX)
#include <pthread.h>
#include <semaphore.h>
#define CSP_SEMAPHORE_OK 1
#define CSP_SEMAPHORE_ERROR 2
#define CSP_MUTEX_OK CSP_SEMAPHORE_OK
#define CSP_MUTEX_ERROR CSP_SEMAPHORE_ERROR
typedef sem_t csp_bin_sem_handle_t;
typedef pthread_mutex_t csp_mutex_t;
#endif // CSP_POSIX
/* MAC OS X interface */
#if defined(CSP_MACOSX)
#include <pthread.h>
#include "posix/pthread_queue.h"
#define CSP_SEMAPHORE_OK PTHREAD_QUEUE_OK
#define CSP_SEMAPHORE_ERROR PTHREAD_QUEUE_EMPTY
#define CSP_MUTEX_OK CSP_SEMAPHORE_OK
#define CSP_MUTEX_ERROR CSP_SEMAPHORE_ERROR
typedef pthread_queue_t * csp_bin_sem_handle_t;
typedef pthread_queue_t * csp_mutex_t;
#endif // CSP_MACOSX
#if defined(CSP_WINDOWS)
#include <Windows.h>
#undef interface
#define CSP_SEMAPHORE_OK 1
#define CSP_SEMAPHORE_ERROR 2
#define CSP_MUTEX_OK CSP_SEMAPHORE_OK
#define CSP_MUTEX_ERROR CSP_SEMAPHORE_ERROR
typedef HANDLE csp_bin_sem_handle_t;
typedef HANDLE csp_mutex_t;
#endif
/* FreeRTOS interface */
#if defined(CSP_FREERTOS)
#include <FreeRTOS.h>
#include <semphr.h>
#define CSP_SEMAPHORE_OK pdPASS
#define CSP_SEMAPHORE_ERROR pdFAIL
#define CSP_MUTEX_OK CSP_SEMAPHORE_OK
#define CSP_MUTEX_ERROR CSP_SEMAPHORE_ERROR
typedef xSemaphoreHandle csp_bin_sem_handle_t;
typedef xSemaphoreHandle csp_mutex_t;
#endif // CSP_FREERTOS
int csp_mutex_create(csp_mutex_t * mutex);
int csp_mutex_remove(csp_mutex_t * mutex);
int csp_mutex_lock(csp_mutex_t * mutex, uint32_t timeout);
int csp_mutex_unlock(csp_mutex_t * mutex);
int csp_bin_sem_create(csp_bin_sem_handle_t * sem);
int csp_bin_sem_remove(csp_bin_sem_handle_t * sem);
int csp_bin_sem_wait(csp_bin_sem_handle_t * sem, uint32_t timeout);
int csp_bin_sem_post(csp_bin_sem_handle_t * sem);
int csp_bin_sem_post_isr(csp_bin_sem_handle_t * sem, CSP_BASE_TYPE * task_woken);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_SEMAPHORE_H_

View File

@ -0,0 +1,74 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_SYSTEM_H_
#define _CSP_SYSTEM_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#define COLOR_MASK_COLOR 0x0F
#define COLOR_MASK_MODIFIER 0xF0
typedef enum {
/* Colors */
COLOR_RESET = 0xF0,
COLOR_BLACK = 0x01,
COLOR_RED = 0x02,
COLOR_GREEN = 0x03,
COLOR_YELLOW = 0x04,
COLOR_BLUE = 0x05,
COLOR_MAGENTA = 0x06,
COLOR_CYAN = 0x07,
COLOR_WHITE = 0x08,
/* Modifiers */
COLOR_NORMAL = 0x0F,
COLOR_BOLD = 0x10,
COLOR_UNDERLINE = 0x20,
COLOR_BLINK = 0x30,
COLOR_HIDE = 0x40,
} csp_color_t;
/**
* Writes out a task list into a pre-allocate buffer,
* use csp_sys_tasklist_size to get sizeof buffer to allocate
* @param out pointer to output buffer
* @return
*/
int csp_sys_tasklist(char * out);
/**
* @return Size of tasklist buffer to allocate for the csp_sys_tasklist call
*/
int csp_sys_tasklist_size(void);
uint32_t csp_sys_memfree(void);
int csp_sys_reboot(void);
int csp_sys_shutdown(void);
void csp_sys_set_color(csp_color_t color);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_SYSTEM_H_

View File

@ -0,0 +1,100 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_THREAD_H_
#define _CSP_THREAD_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
/* POSIX interface */
#if defined(CSP_POSIX) || defined(CSP_MACOSX)
#include <pthread.h>
#include <unistd.h>
#define csp_thread_exit() pthread_exit(NULL)
typedef pthread_t csp_thread_handle_t;
typedef void * csp_thread_return_t;
#define CSP_DEFINE_TASK(task_name) csp_thread_return_t task_name(void * param)
#define CSP_TASK_RETURN NULL
#define csp_sleep_ms(time_ms) usleep(time_ms * 1000);
#endif // CSP_POSIX
/* Windows interface */
#if defined(CSP_WINDOWS)
#include <Windows.h>
#undef interface
#include <process.h>
#define csp_thread_exit() _endthreadex(0)
typedef HANDLE csp_thread_handle_t;
typedef unsigned int csp_thread_return_t;
#define CSP_DEFINE_TASK(task_name) csp_thread_return_t __attribute__((stdcall)) task_name(void * param)
#define CSP_TASK_RETURN 0
#define csp_sleep_ms(time_ms) Sleep(time_ms);
#endif // CSP_WINDOWS
/* FreeRTOS interface */
#if defined(CSP_FREERTOS)
#include <FreeRTOS.h>
#include <task.h>
#if INCLUDE_vTaskDelete
#define csp_thread_exit() vTaskDelete(NULL)
#else
#define csp_thread_exit()
#endif
typedef xTaskHandle csp_thread_handle_t;
typedef void csp_thread_return_t;
#define CSP_DEFINE_TASK(task_name) csp_thread_return_t task_name(void * param)
#define CSP_TASK_RETURN
#define csp_sleep_ms(time_ms) vTaskDelay(time_ms / portTICK_RATE_MS);
#endif // CSP_FREERTOS
#ifndef CSP_WINDOWS
int csp_thread_create(csp_thread_return_t (* routine)(void *), const char * const thread_name, unsigned short stack_depth, void * parameters, unsigned int priority, csp_thread_handle_t * handle);
#else
int csp_thread_create(csp_thread_return_t (* routine)(void *)__attribute__((stdcall)), const char * const thread_name, unsigned short stack_depth, void * parameters, unsigned int priority, csp_thread_handle_t * handle);
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_THREAD_H_

View File

@ -0,0 +1,57 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_TIME_H_
#define _CSP_TIME_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
/* Blackfin/x86 on Linux */
#if defined(CSP_POSIX)
#include <time.h>
#include <sys/time.h>
#include <limits.h>
#endif // CSP_POSIX
/* AVR/ARM on FreeRTOS */
#if defined(CSP_FREERTOS)
#include <FreeRTOS.h>
#include <task.h>
#endif // CSP_FREERTOS
uint32_t csp_get_ms(void);
uint32_t csp_get_ms_isr(void);
uint32_t csp_get_s(void);
uint32_t csp_get_s_isr(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_TIME_H_

View File

@ -0,0 +1,118 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _PTHREAD_QUEUE_H_
#define _PTHREAD_QUEUE_H_
/**
@file
Queue implemented using pthread locks and conds.
Inspired by c-pthread-queue by Matthew Dickinson: http://code.google.com/p/c-pthread-queue/
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdlib.h>
#include <stdint.h>
#include <sys/time.h>
#include <csp/arch/csp_queue.h>
/**
Queue error codes.
@{
*/
/**
General error code - something went wrong.
*/
#define PTHREAD_QUEUE_ERROR CSP_QUEUE_ERROR
/**
Queue is empty - cannot extract element.
*/
#define PTHREAD_QUEUE_EMPTY CSP_QUEUE_ERROR
/**
Queue is full - cannot insert element.
*/
#define PTHREAD_QUEUE_FULL CSP_QUEUE_ERROR
/**
Ok - no error.
*/
#define PTHREAD_QUEUE_OK CSP_QUEUE_OK
/** @{ */
/**
Queue handle.
*/
typedef struct pthread_queue_s {
//! Memory area.
void * buffer;
//! Memory size.
int size;
//! Item/element size.
int item_size;
//! Items/elements in queue.
int items;
//! Insert point.
int in;
//! Extract point.
int out;
//! Lock.
pthread_mutex_t mutex;
//! Wait because queue is full (insert).
pthread_cond_t cond_full;
//! Wait because queue is empty (extract).
pthread_cond_t cond_empty;
} pthread_queue_t;
/**
Create queue.
*/
pthread_queue_t * pthread_queue_create(int length, size_t item_size);
/**
Delete queue.
*/
void pthread_queue_delete(pthread_queue_t * q);
/**
Enqueue/insert element.
*/
int pthread_queue_enqueue(pthread_queue_t * queue, void * value, uint32_t timeout);
/**
Dequeue/extract element.
*/
int pthread_queue_dequeue(pthread_queue_t * queue, void * buf, uint32_t timeout);
/**
Return number of elements in the queue.
*/
int pthread_queue_items(pthread_queue_t * queue);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _PTHREAD_QUEUE_H_

View File

@ -0,0 +1,73 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_HMAC_H_
#define _CSP_HMAC_H_
#include <csp/csp_types.h>
#ifdef __cplusplus
extern "C" {
#endif
#define CSP_HMAC_LENGTH 4
/**
* Append HMAC to packet
* @param packet Pointer to packet
* @param include_header use header in hmac calculation (this will not modify the flags field)
* @return 0 on success, negative on failure
*/
int csp_hmac_append(csp_packet_t * packet, bool include_header);
/**
* Verify HMAC of packet
* @param packet Pointer to packet
* @param include_header use header in hmac calculation (this will not modify the flags field)
* @return 0 on success, negative on failure
*/
int csp_hmac_verify(csp_packet_t * packet, bool include_header);
/**
* Calculate HMAC on buffer
*
* This function is used by append/verify but cal also be called separately.
* @param key HMAC key
* @param keylen HMAC key length
* @param data pointer to data
* @param datalen lehgth of data
* @param hmac output HMAC calculation (CSP_HMAC_LENGTH)
* @return 0 on success, negative on failure
*/
int csp_hmac_memory(const uint8_t * key, uint32_t keylen, const uint8_t * data, uint32_t datalen, uint8_t * hmac);
/**
* Save a copy of the key string for use by the append/verify functions
* @param key HMAC key
* @param keylen HMAC key length
* @return Always returns 0
*/
int csp_hmac_set_key(char * key, uint32_t keylen);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_HMAC_H_

View File

@ -0,0 +1,81 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_SHA1_H_
#define _CSP_SHA1_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/* The SHA1 block and message digest size in bytes */
#define SHA1_BLOCKSIZE 64
#define SHA1_DIGESTSIZE 20
/**
SHA1 state structure
*/
typedef struct {
//! Internal SHA1 state.
uint64_t length;
//! Internal SHA1 state.
uint32_t state[5];
//! Internal SHA1 state.
uint32_t curlen;
//! Internal SHA1 state.
uint8_t buf[SHA1_BLOCKSIZE];
} csp_sha1_state;
/**
* Initialize the hash state
* @param sha1 The hash state you wish to initialize
*/
void csp_sha1_init(csp_sha1_state * sha1);
/**
* Process a block of memory though the hash
* @param sha1 The hash state
* @param in The data to hash
* @param inlen The length of the data (octets)
*/
void csp_sha1_process(csp_sha1_state * sha1, const uint8_t * in, uint32_t inlen);
/**
* Terminate the hash to get the digest
* @param sha1 The hash state
* @param out [out] The destination of the hash (20 bytes)
*/
void csp_sha1_done(csp_sha1_state * sha1, uint8_t * out);
/**
* Calculate SHA1 hash of block of memory.
* @param msg Pointer to message buffer
* @param len Length of message
* @param sha1 Pointer to SHA1 output buffer. Must be 20 bytes or more!
*/
void csp_sha1_memory(const uint8_t * msg, uint32_t len, uint8_t * hash);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_SHA1_H_

View File

@ -0,0 +1,52 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_XTEA_H_
#define _CSP_XTEA_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
#define CSP_XTEA_IV_LENGTH 8
/**
* XTEA encrypt byte array
* @param plain Pointer to plain text
* @param len Length of plain text
* @param iv Initialization vector
*/
int csp_xtea_encrypt(uint8_t * plain, const uint32_t len, uint32_t iv[2]);
/**
* Decrypt XTEA encrypted byte array
* @param cipher Pointer to cipher text
* @param len Length of plain text
* @param iv Initialization vector
*/
int csp_xtea_decrypt(uint8_t * cipher, const uint32_t len, uint32_t iv[2]);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_XTEA_H_

545
libcsp/include/csp/csp.h Normal file
View File

@ -0,0 +1,545 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_H_
#define _CSP_H_
#ifdef __cplusplus
extern "C" {
#endif
/* Includes */
#include <stdint.h>
#include <csp/csp_autoconfig.h>
/* CSP includes */
#include "csp_types.h"
#include "csp_platform.h"
#include "csp_error.h"
#include "csp_debug.h"
#include "csp_buffer.h"
#include "csp_rtable.h"
#include "csp_iflist.h"
/** csp_init
* Start up the can-space protocol
* @param my_node_address The CSP node address
*/
int csp_init(uint8_t my_node_address);
/** csp_set_address
* Set the systems own address
* @param addr The new address of the system
*/
void csp_set_address(uint8_t addr);
/** csp_get_address
* Get the systems own address
* @return The current address of the system
*/
uint8_t csp_get_address(void);
/** csp_set_hostname
* Set subsystem hostname.
* This function takes a pointer to a string, which should remain static
* @param hostname Hostname to set
*/
void csp_set_hostname(const char *hostname);
/** csp_get_hostname
* Get current subsystem hostname.
* @return Pointer to char array with current hostname.
*/
const char *csp_get_hostname(void);
/** csp_set_model
* Set subsystem model name.
* This function takes a pointer to a string, which should remain static
* @param model Model name to set
*/
void csp_set_model(const char *model);
/** csp_get_model
* Get current model name.
* @return Pointer to char array with current model name.
*/
const char *csp_get_model(void);
/** csp_set_revision
* Set subsystem revision. This can be used to override the CMP revision field.
* This function takes a pointer to a string, which should remain static
* @param revision Revision name to set
*/
void csp_set_revision(const char *revision);
/** csp_get_revision
* Get subsystem revision.
* @return Pointer to char array with software revision.
*/
const char *csp_get_revision(void);
/** csp_socket
* Create CSP socket endpoint
* @param opts Socket options
* @return Pointer to socket on success, NULL on failure
*/
csp_socket_t *csp_socket(uint32_t opts);
/**
* Wait for a new connection on a socket created by csp_socket
* @param socket Socket to accept connections on
* @param timeout use CSP_MAX_DELAY for infinite timeout
* @return Return pointer to csp_conn_t or NULL if timeout was reached
*/
csp_conn_t *csp_accept(csp_socket_t *socket, uint32_t timeout);
/**
* Read data from a connection
* This fuction uses the RX queue of a connection to receive a packet
* If no packet is available and a timeout has been specified
* The call will block.
* Do NOT call this from ISR
* @param conn pointer to connection
* @param timeout timeout in ms, use CSP_MAX_DELAY for infinite blocking time
* @return Returns pointer to csp_packet_t, which you MUST free yourself, either by calling csp_buffer_free() or reusing the buffer for a new csp_send.
*/
csp_packet_t *csp_read(csp_conn_t *conn, uint32_t timeout);
/**
* Send a packet on an already established connection
* @param conn pointer to connection
* @param packet pointer to packet,
* @param timeout a timeout to wait for TX to complete. NOTE: not all underlying drivers supports flow-control.
* @return returns 1 if successful and 0 otherwise. you MUST free the frame yourself if the transmission was not successful.
*/
int csp_send(csp_conn_t *conn, csp_packet_t *packet, uint32_t timeout);
/**
* Send a packet on an already established connection, and change the default priority of the connection
*
* @note When using this function, the priority of the connection will change. If you need to change it back
* use another call to csp_send_prio, or ensure that all packets sent on a given connection is using send_prio call.
*
* @param prio csp priority
* @param conn pointer to connection
* @param packet pointer to packet,
* @param timeout a timeout to wait for TX to complete. NOTE: not all underlying drivers supports flow-control.
* @return returns 1 if successful and 0 otherwise. you MUST free the frame yourself if the transmission was not successful.
*/
int csp_send_prio(uint8_t prio, csp_conn_t *conn, csp_packet_t *packet, uint32_t timeout);
/**
* Perform an entire request/reply transaction
* Copies both input buffer and reply to output buffeer.
* Also makes the connection and closes it again
* @param prio CSP Prio
* @param dest CSP Dest
* @param port CSP Port
* @param timeout timeout in ms
* @param outbuf pointer to outgoing data buffer
* @param outlen length of request to send
* @param inbuf pointer to incoming data buffer
* @param inlen length of expected reply, -1 for unknown size (note inbuf MUST be large enough)
* @return Return 1 or reply size if successful, 0 if error or incoming length does not match or -1 if timeout was reached
*/
int csp_transaction(uint8_t prio, uint8_t dest, uint8_t port, uint32_t timeout, void *outbuf, int outlen, void *inbuf, int inlen);
/**
* Perform an entire request/reply transaction
* Copies both input buffer and reply to output buffeer.
* Also makes the connection and closes it again
* @param prio CSP Prio
* @param dest CSP Dest
* @param port CSP Port
* @param timeout timeout in ms
* @param outbuf pointer to outgoing data buffer
* @param outlen length of request to send
* @param inbuf pointer to incoming data buffer
* @param inlen length of expected reply, -1 for unknown size (note inbuf MUST be large enough)
* @param opts Connection options.
* @return Return 1 or reply size if successful, 0 if error or incoming length does not match or -1 if timeout was reached
*/
int csp_transaction2(uint8_t prio, uint8_t dest, uint8_t port, uint32_t timeout, void *outbuf, int outlen, void *inbuf, int inlen, uint32_t opts);
/**
* Use an existing connection to perform a transaction,
* This is only possible if the next packet is on the same port and destination!
* @param conn pointer to connection structure
* @param timeout timeout in ms
* @param outbuf pointer to outgoing data buffer
* @param outlen length of request to send
* @param inbuf pointer to incoming data buffer
* @param inlen length of expected reply, -1 for unknown size (note inbuf MUST be large enough)
* @return
*/
int csp_transaction_persistent(csp_conn_t *conn, uint32_t timeout, void *outbuf, int outlen, void *inbuf, int inlen);
/**
* Read data from a connection-less server socket
* This fuction uses the socket directly to receive a frame
* If no packet is available and a timeout has been specified the call will block.
* Do NOT call this from ISR
* @return Returns pointer to csp_packet_t, which you MUST free yourself, either by calling csp_buffer_free() or reusing the buffer for a new csp_send.
*/
csp_packet_t *csp_recvfrom(csp_socket_t *socket, uint32_t timeout);
/**
* Send a packet without previously opening a connection
* @param prio CSP_PRIO_x
* @param dest destination node
* @param dport destination port
* @param src_port source port
* @param opts CSP_O_x
* @param packet pointer to packet
* @param timeout timeout used by interfaces with blocking send
* @return -1 if error (you must free packet), 0 if OK (you must discard pointer)
*/
int csp_sendto(uint8_t prio, uint8_t dest, uint8_t dport, uint8_t src_port, uint32_t opts, csp_packet_t *packet, uint32_t timeout);
/**
* Send a packet as a direct reply to the source of an incoming packet,
* but still without holding an entire connection
* @param request_packet pointer to packet to reply to
* @param reply_packet actual reply data
* @param opts CSP_O_x
* @param timeout timeout used by interfaces with blocking send
* @return -1 if error (you must free packet), 0 if OK (you must discard pointer)
*/
int csp_sendto_reply(csp_packet_t * request_packet, csp_packet_t * reply_packet, uint32_t opts, uint32_t timeout);
/** csp_connect
* Used to establish outgoing connections
* This function searches the port table for free slots and finds an unused
* connection from the connection pool
* There is no handshake in the CSP protocol
* @param prio Connection priority.
* @param dest Destination address.
* @param dport Destination port.
* @param timeout Timeout in ms.
* @param opts Connection options.
* @return a pointer to a new connection or NULL
*/
csp_conn_t *csp_connect(uint8_t prio, uint8_t dest, uint8_t dport, uint32_t timeout, uint32_t opts);
/** csp_close
* Closes a given connection and frees buffers used.
* @param conn pointer to connection structure
* @return CSP_ERR_NONE if connection was closed. Otherwise, an err code is returned.
*/
int csp_close(csp_conn_t *conn);
/**
* @param conn pointer to connection structure
* @return destination port of an incoming connection
*/
int csp_conn_dport(csp_conn_t *conn);
/**
* @param conn pointer to connection structure
* @return source port of an incoming connection
*/
int csp_conn_sport(csp_conn_t *conn);
/**
* @param conn pointer to connection structure
* @return destination address of an incoming connection
*/
int csp_conn_dst(csp_conn_t *conn);
/**
* @param conn pointer to connection structure
* @return source address of an incoming connection
*/
int csp_conn_src(csp_conn_t *conn);
/**
* @param conn pointer to connection structure
* @return flags field of an incoming connection
*/
int csp_conn_flags(csp_conn_t *conn);
/**
* Set socket to listen for incoming connections
* @param socket Socket to enable listening on
* @param conn_queue_length Lenght of backlog connection queue
* @return 0 on success, -1 on error.
*/
int csp_listen(csp_socket_t *socket, size_t conn_queue_length);
/**
* Bind port to socket
* @param socket Socket to bind port to
* @param port Port number to bind
* @return 0 on success, -1 on error.
*/
int csp_bind(csp_socket_t *socket, uint8_t port);
/**
* Start the router task.
* @param task_stack_size The number of portStackType to allocate. This only affects FreeRTOS systems.
* @param priority The OS task priority of the router
*/
int csp_route_start_task(unsigned int task_stack_size, unsigned int priority);
/**
* Call the router worker function manually (without the router task)
* This must be run inside a loop or called periodically for the csp router to work.
* Use this function instead of calling and starting the router task.
* @param timeout max blocking time
* @return -1 if no packet was processed, 0 otherwise
*/
int csp_route_work(uint32_t timeout);
/**
* Start the bridge task.
* @param task_stack_size The number of portStackType to allocate. This only affects FreeRTOS systems.
* @param priority The OS task priority of the router
* @param _if_a pointer to first side
* @param _if_b pointer to second side
* @return CSP_ERR type
*/
int csp_bridge_start(unsigned int task_stack_size, unsigned int task_priority, csp_iface_t * _if_a, csp_iface_t * _if_b);
/**
* Enable promiscuous mode packet queue
* This function is used to enable promiscuous mode for the router.
* If enabled, a copy of all incoming packets are placed in a queue
* that can be read with csp_promisc_get(). Not all interface drivers
* support promiscuous mode.
*
* @param buf_size Size of buffer for incoming packets
*/
int csp_promisc_enable(unsigned int buf_size);
/**
* Disable promiscuous mode.
* If the queue was initialised prior to this, it can be re-enabled
* by calling promisc_enable(0)
*/
void csp_promisc_disable(void);
/**
* Get packet from promiscuous mode packet queue
* Returns the first packet from the promiscuous mode packet queue.
* The queue is FIFO, so the returned packet is the oldest one
* in the queue.
*
* @param timeout Timeout in ms to wait for a new packet
*/
csp_packet_t *csp_promisc_read(uint32_t timeout);
/**
* Send multiple packets using the simple fragmentation protocol
* CSP will add total size and offset to all packets
* This can be read by the client using the csp_sfp_recv, if the CSP_FFRAG flag is set
* @param conn pointer to connection
* @param data pointer to data to send
* @param totalsize size of data to send
* @param mtu maximum transfer unit
* @param timeout timeout in ms to wait for csp_send()
* @return 0 if OK, -1 if ERR
*/
int csp_sfp_send(csp_conn_t * conn, const void * data, int totalsize, int mtu, uint32_t timeout);
/**
* Same as csp_sfp_send but with option to supply your own memcpy function.
* This is usefull if you wish to send data stored in flash memory or another location
* @param conn pointer to connection
* @param data pointer to data to send
* @param totalsize size of data to send
* @param mtu maximum transfer unit
* @param timeout timeout in ms to wait for csp_send()
* @param memcpyfcn, pointer to memcpy function
* @return 0 if OK, -1 if ERR
*/
int csp_sfp_send_own_memcpy(csp_conn_t * conn, const void * data, int totalsize, int mtu, uint32_t timeout, void * (*memcpyfcn)(void *, const void *, size_t));
/**
* This is the counterpart to the csp_sfp_send function
* @param conn pointer to active conn, on which you expect to receive sfp packed data
* @param dataout pointer to NULL pointer, whill be overwritten with malloc pointer
* @param datasize actual size of received data
* @param timeout timeout in ms to wait for csp_recv()
* @return 0 if OK, -1 if ERR
*/
int csp_sfp_recv(csp_conn_t * conn, void ** dataout, int * datasize, uint32_t timeout);
/**
* This is the counterpart to the csp_sfp_send function
* @param conn pointer to active conn, on which you expect to receive sfp packed data
* @param dataout pointer to NULL pointer, whill be overwritten with malloc pointer
* @param datasize actual size of received data
* @param timeout timeout in ms to wait for csp_recv()
* @param first_packet This is a pointer to the first SFP packet (previously received with csp_read)
* @return 0 if OK, -1 if ERR
*/
int csp_sfp_recv_fp(csp_conn_t * conn, void ** dataout, int * datasize, uint32_t timeout, csp_packet_t * first_packet);
/**
* If the given packet is a service-request (that is uses one of the csp service ports)
* it will be handled according to the CSP service handler.
* This function will either use the packet buffer or delete it,
* so this function is typically called in the last "default" clause of
* a switch/case statement in a csp_listener task.
* In order to listen to csp service ports, bind your listener to the CSP_ANY port.
* This function may only be called from task context.
* @param conn Pointer to the new connection
* @param packet Pointer to the first packet, obtained by using csp_read()
*/
void csp_service_handler(csp_conn_t *conn, csp_packet_t *packet);
/**
* Send a single ping/echo packet
* @param node node id
* @param timeout timeout in ms
* @param size size of packet to transmit
* @param conn_options csp connection options
* @return >0 = Echo time in ms, -1 = ERR
*/
int csp_ping(uint8_t node, uint32_t timeout, unsigned int size, uint8_t conn_options);
/**
* Send a single ping/echo packet without waiting for reply
* @param node node id
*/
void csp_ping_noreply(uint8_t node);
/**
* Request process list.
* @note This is only available for FreeRTOS systems
* @param node node id
* @param timeout timeout in ms
*/
void csp_ps(uint8_t node, uint32_t timeout);
/**
* Request amount of free memory
* @param node node id
* @param timeout timeout in ms
*/
void csp_memfree(uint8_t node, uint32_t timeout);
/**
* Request number of free buffer elements
* @param node node id
* @param timeout timeout in ms
*/
void csp_buf_free(uint8_t node, uint32_t timeout);
/**
* Reboot subsystem
* @param node node id
*/
void csp_reboot(uint8_t node);
/**
* Shutdown subsystem
* @param node node id
*/
void csp_shutdown(uint8_t node);
/**
* Request subsystem uptime
* @param node node id
* @param timeout timeout in ms
*/
void csp_uptime(uint8_t node, uint32_t timeout);
/**
* Set RDP options
* @param window_size Window size
* @param conn_timeout_ms Connection timeout in ms
* @param packet_timeout_ms Packet timeout in ms
* @param delayed_acks Enable/disable delayed acknowledgements
* @param ack_timeout Acknowledgement timeout when delayed ACKs is enabled
* @param ack_delay_count Send acknowledgement for every ack_delay_count packets
*/
void csp_rdp_set_opt(unsigned int window_size, unsigned int conn_timeout_ms,
unsigned int packet_timeout_ms, unsigned int delayed_acks,
unsigned int ack_timeout, unsigned int ack_delay_count);
/**
* Get RDP options
* @param window_size Window size
* @param conn_timeout_ms Connection timeout in ms
* @param packet_timeout_ms Packet timeout in ms
* @param delayed_acks Enable/disable delayed acknowledgements
* @param ack_timeout Acknowledgement timeout when delayed ACKs is enabled
* @param ack_delay_count Send acknowledgement for every ack_delay_count packets
*/
void csp_rdp_get_opt(unsigned int *window_size, unsigned int *conn_timeout_ms,
unsigned int *packet_timeout_ms, unsigned int *delayed_acks,
unsigned int *ack_timeout, unsigned int *ack_delay_count);
/**
* Set XTEA key
* @param key Pointer to key array
* @param keylen Length of key
* @return 0 if key was successfully set, -1 otherwise
*/
int csp_xtea_set_key(char *key, uint32_t keylen);
/**
* Set HMAC key
* @param key Pointer to key array
* @param keylen Length of key
* @return 0 if key was successfully set, -1 otherwise
*/
int csp_hmac_set_key(char *key, uint32_t keylen);
/**
* Print connection table
*/
void csp_conn_print_table(void);
int csp_conn_print_table_str(char * str_buf, int str_size);
/**
* Print buffer usage table
*/
void csp_buffer_print_table(void);
/**
* Hex dump to stdout
*/
void csp_hex_dump(const char *desc, void *addr, int len);
#ifdef __AVR__
typedef uint32_t csp_memptr_t;
#else
typedef void * csp_memptr_t;
#endif
typedef csp_memptr_t (*csp_memcpy_fnc_t)(csp_memptr_t, const csp_memptr_t, size_t);
void csp_cmp_set_memcpy(csp_memcpy_fnc_t fnc);
/**
* Set csp_debug hook function
* @param f Hook function
*/
#include <stdarg.h>
typedef void (*csp_debug_hook_func_t)(csp_debug_level_t level, const char *format, va_list args);
void csp_debug_hook_set(csp_debug_hook_func_t f);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_H_

View File

@ -0,0 +1,48 @@
/*
* csp_autoconfig.h
*
* Created on: 20.11.2020
* Author: jakob
*/
#ifndef GOMSPACE_LIBCSP_INCLUDE_CSP_CSP_AUTOCONFIG_H_
#define GOMSPACE_LIBCSP_INCLUDE_CSP_CSP_AUTOCONFIG_H_
#define ENABLE_NANOPOWER2_CLIENT 1
#define GIT_REV "unknown"
/* #undef CSP_FREERTOS */
#define CSP_POSIX 1
/* #undef CSP_WINDOWS */
/* #undef CSP_MACOSX */
#define HAVE_LIBZMQ 1
#define CSP_DEBUG 1
#define CSP_USE_RDP 1
#define CSP_USE_CRC32 1
#define CSP_USE_HMAC 1
#define CSP_USE_XTEA 1
#define CSP_USE_PROMISC 1
#define CSP_USE_QOS 1
/* #undef CSP_USE_DEDUP */
/* #undef CSP_USE_INIT_SHUTDOWN */
#define CSP_USE_CAN 1
/* #define CSP_USE_I2C 1 */
/* #define CSP_USE_KISS 1 */
/* #define CSP_USE_ZMQHUB 1 */
#define CSP_CONN_MAX 10
#define CSP_CONN_QUEUE_LENGTH 100
#define CSP_FIFO_INPUT 100
#define CSP_MAX_BIND_PORT 31
#define CSP_RDP_MAX_WINDOW 20
#define CSP_PADDING_BYTES 8
#define CSP_CONNECTION_SO 64
#define CSP_LOG_LEVEL_DEBUG 1
#define CSP_LOG_LEVEL_INFO 1
#define CSP_LOG_LEVEL_WARN 1
#define CSP_LOG_LEVEL_ERROR 1
#define CSP_LITTLE_ENDIAN 1
/* #undef CSP_BIG_ENDIAN */
#define CSP_HAVE_STDBOOL_H 1
/* #define CSP_HAVE_LIBSOCKETCAN 1 */
#define LIBCSP_VERSION "1.5"
#endif /* GOMSPACE_LIBCSP_INCLUDE_CSP_CSP_AUTOCONFIG_H_ */

View File

@ -0,0 +1,92 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_BUFFER_H_
#define _CSP_BUFFER_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* Start the buffer handling system
* You must specify the number for buffers and the size. All buffers are fixed
* size so you must specify the size of your largest buffer.
*
* @param count Number of buffers to allocate
* @param size Buffer size in bytes.
*
* @return CSP_ERR_NONE if malloc() succeeded, CSP_ERR message otherwise.
*/
int csp_buffer_init(int count, int size);
/**
* Get a reference to a free buffer. This function can only be called
* from task context.
*
* @param size Specify what data-size you will put in the buffer
* @return pointer to a free csp_packet_t or NULL if out of memory
*/
void * csp_buffer_get(size_t size);
/**
* Get a reference to a free buffer. This function can only be called
* from interrupt context.
*
* @param buf_size Specify what data-size you will put in the buffer
* @return pointer to a free csp_packet_t or NULL if out of memory
*/
void * csp_buffer_get_isr(size_t buf_size);
/**
* Free a buffer after use.
* @param packet pointer to memory area, must be acquired by csp_buffer_get().
*/
void csp_buffer_free(void *packet);
/**
* Free a buffer after use in ISR context.
* @param packet pointer to memory area, must be acquired by csp_buffer_get().
*/
void csp_buffer_free_isr(void *packet);
/**
* Clone an existing packet and increase/decrease cloned packet size.
* @param buffer Existing buffer to clone.
*/
void * csp_buffer_clone(void *buffer);
/**
* Return how many buffers that are currently free.
* @return number of free buffers
*/
int csp_buffer_remaining(void);
/**
* Return the size of the CSP buffers
* @return size of CSP buffers
*/
int csp_buffer_size(void);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _CSP_BUFFER_H_ */

View File

@ -0,0 +1,189 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_CMP_H_
#define _CSP_CMP_H_
/**
@file
CSP management protocol (CMP).
*/
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
#include <csp/arch/csp_clock.h>
/**
CMP type.
@{
*/
/**
CMP request.
*/
#define CSP_CMP_REQUEST 0x00
/**
CMP reply.
*/
#define CSP_CMP_REPLY 0xff
/**@}*/
/**
CMP requests.
@{
*/
/**
CMP request codes.
*/
/**
Request identification, compile time, revision, name.
*/
#define CSP_CMP_IDENT 1
/**
Set/configure routing.
*/
#define CSP_CMP_ROUTE_SET 2
/**
Request interface statistics.
*/
#define CSP_CMP_IF_STATS 3
/**
Peek/read data from memory.
*/
#define CSP_CMP_PEEK 4
/**
Poke/write data from memory.
*/
#define CSP_CMP_POKE 5
/**
Get/set clock.
*/
#define CSP_CMP_CLOCK 6
/**@}*/
/**
CMP identification - max revision length.
*/
#define CSP_CMP_IDENT_REV_LEN 20
/**
CMP identification - max date length.
*/
#define CSP_CMP_IDENT_DATE_LEN 12
/**
CMP identification - max time length.
*/
#define CSP_CMP_IDENT_TIME_LEN 9
/**
CMP interface statistics - max interface name length.
*/
#define CSP_CMP_ROUTE_IFACE_LEN 11
/**
CMP peek/read memeory - max read length.
*/
#define CSP_CMP_PEEK_MAX_LEN 200
/**
CMP poke/write memeory - max write length.
*/
#define CSP_CMP_POKE_MAX_LEN 200
/**
CSP management protocol description.
*/
struct csp_cmp_message {
//! CMP request type.
uint8_t type;
//! CMP request code.
uint8_t code;
union {
struct {
char hostname[CSP_HOSTNAME_LEN];
char model[CSP_MODEL_LEN];
char revision[CSP_CMP_IDENT_REV_LEN];
char date[CSP_CMP_IDENT_DATE_LEN];
char time[CSP_CMP_IDENT_TIME_LEN];
} ident;
struct {
uint8_t dest_node;
uint8_t next_hop_mac;
char interface[CSP_CMP_ROUTE_IFACE_LEN];
} route_set;
struct __attribute__((__packed__)) {
char interface[CSP_CMP_ROUTE_IFACE_LEN];
uint32_t tx;
uint32_t rx;
uint32_t tx_error;
uint32_t rx_error;
uint32_t drop;
uint32_t autherr;
uint32_t frame;
uint32_t txbytes;
uint32_t rxbytes;
uint32_t irq;
} if_stats;
struct {
uint32_t addr;
uint8_t len;
char data[CSP_CMP_PEEK_MAX_LEN];
} peek;
struct {
uint32_t addr;
uint8_t len;
char data[CSP_CMP_POKE_MAX_LEN];
} poke;
csp_timestamp_t clock;
};
} __attribute__ ((packed));
/**
Macro for calculating size of management message.
*/
#define CMP_SIZE(_memb) (sizeof(((struct csp_cmp_message *)0)->_memb) + sizeof(uint8_t) + sizeof(uint8_t))
/**
Generic send management message request.
*/
int csp_cmp(uint8_t node, uint32_t timeout, uint8_t code, int membsize, struct csp_cmp_message *msg);
/**
Macro for defining management handling function.
*/
#define CMP_MESSAGE(_code, _memb) \
static inline int csp_cmp_##_memb(uint8_t node, uint32_t timeout, struct csp_cmp_message *msg) { \
return csp_cmp(node, timeout, _code, CMP_SIZE(_memb), msg); \
}
CMP_MESSAGE(CSP_CMP_IDENT, ident)
CMP_MESSAGE(CSP_CMP_ROUTE_SET, route_set)
CMP_MESSAGE(CSP_CMP_IF_STATS, if_stats)
CMP_MESSAGE(CSP_CMP_PEEK, peek)
CMP_MESSAGE(CSP_CMP_POKE, poke)
CMP_MESSAGE(CSP_CMP_CLOCK, clock)
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_CMP_H_

View File

@ -0,0 +1,63 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_CRC32_H_
#define _CSP_CRC32_H_
#include <csp/csp.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Generate precomputed CRC32 table
*/
void csp_crc32_gentab(void);
/**
* Append CRC32 checksum to packet
* @param packet Packet to append checksum
* @param include_header use header in calculation (this will not modify the flags field)
* @return 0 on success, -1 on error
*/
int csp_crc32_append(csp_packet_t * packet, bool include_header);
/**
* Verify CRC32 checksum on packet
* @param packet Packet to verify
* @param include_header use header in calculation (this will not modify the flags field)
* @return 0 if checksum is valid, -1 otherwise
*/
int csp_crc32_verify(csp_packet_t * packet, bool include_header);
/**
* Calculate checksum for a given memory area
* @param data pointer to memory
* @param length length of memory to do checksum on
* @return return uint32_t checksum
*/
uint32_t csp_crc32_memory(const uint8_t * data, uint32_t length);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _CSP_CRC32_H_ */

View File

@ -0,0 +1,150 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_DEBUG_H_
#define _CSP_DEBUG_H_
#include <inttypes.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
/** Debug levels */
typedef enum {
CSP_ERROR = 0,
CSP_WARN = 1,
CSP_INFO = 2,
CSP_BUFFER = 3,
CSP_PACKET = 4,
CSP_PROTOCOL = 5,
CSP_LOCK = 6,
} csp_debug_level_t;
/* Extract filename component from path */
#define BASENAME(_file) ((strrchr(_file, '/') ? : (strrchr(_file, '\\') ? : _file)) + 1)
/* Implement csp_assert_fail_action to override default failure action */
extern void __attribute__((weak)) csp_assert_fail_action(const char *assertion, const char *file, int line);
#ifndef NDEBUG
#define csp_assert(exp) \
do { \
if (!(exp)) { \
const char *assertion = #exp; \
const char *file = BASENAME(__FILE__); \
int line = __LINE__; \
printf("\E[1;31m[%02" PRIu8 "] Assertion \'%s\' failed in %s:%d\E[0m\r\n", \
csp_get_address(), assertion, file, line); \
if (csp_assert_fail_action) \
csp_assert_fail_action(assertion, file, line); \
} \
} while (0)
#else
#define csp_assert(...) do {} while (0)
#endif
#ifdef __AVR__
#include <stdio.h>
#include <avr/pgmspace.h>
#define CONSTSTR(data) PSTR(data)
#undef printf
#undef sscanf
#undef scanf
#undef sprintf
#undef snprintf
#define printf(s, ...) printf_P(PSTR(s), ## __VA_ARGS__)
#define sscanf(buf, s, ...) sscanf_P(buf, PSTR(s), ## __VA_ARGS__)
#define scanf(s, ...) scanf_P(PSTR(s), ## __VA_ARGS__)
#define sprintf(buf, s, ...) sprintf_P(buf, PSTR(s), ## __VA_ARGS__)
#define snprintf(buf, size, s, ...) snprintf_P(buf, size, PSTR(s), ## __VA_ARGS__)
#else
#define CONSTSTR(data) data
#endif
#ifdef CSP_DEBUG
#define csp_debug(level, format, ...) do { do_csp_debug(level, CONSTSTR(format), ##__VA_ARGS__); } while(0)
#else
#define csp_debug(...) do {} while (0)
#endif
#ifdef CSP_LOG_LEVEL_ERROR
#define csp_log_error(format, ...) csp_debug(CSP_ERROR, format, ##__VA_ARGS__)
#else
#define csp_log_error(...) do {} while (0)
#endif
#ifdef CSP_LOG_LEVEL_WARN
#define csp_log_warn(format, ...) csp_debug(CSP_WARN, format, ##__VA_ARGS__)
#else
#define csp_log_warn(...) do {} while (0)
#endif
#ifdef CSP_LOG_LEVEL_INFO
#define csp_log_info(format, ...) csp_debug(CSP_INFO, format, ##__VA_ARGS__)
#else
#define csp_log_info(...) do {} while (0)
#endif
#ifdef CSP_LOG_LEVEL_DEBUG
#define csp_log_buffer(format, ...) csp_debug(CSP_BUFFER, format, ##__VA_ARGS__)
#define csp_log_packet(format, ...) csp_debug(CSP_PACKET, format, ##__VA_ARGS__)
#define csp_log_protocol(format, ...) csp_debug(CSP_PROTOCOL, format, ##__VA_ARGS__)
#define csp_log_lock(format, ...) csp_debug(CSP_LOCK, format, ##__VA_ARGS__)
#else
#define csp_log_buffer(...) do {} while (0)
#define csp_log_packet(...) do {} while (0)
#define csp_log_protocol(...) do {} while (0)
#define csp_log_lock(...) do {} while (0)
#endif
/**
* This function should not be used directly, use csp_log_<level>() macro instead
* @param level
* @param format
*/
void do_csp_debug(csp_debug_level_t level, const char *format, ...);
/**
* Toggle debug level on/off
* @param level Level to toggle
*/
void csp_debug_toggle_level(csp_debug_level_t level);
/**
* Set debug level
* @param level Level to set
* @param value New level value
*/
void csp_debug_set_level(csp_debug_level_t level, bool value);
/**
* Get current debug level value
* @param level Level value to get
* @return Level value
*/
int csp_debug_get_level(csp_debug_level_t level);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_DEBUG_H_

View File

@ -0,0 +1,170 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_ENDIAN_H_
#define _CSP_ENDIAN_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/**
* Convert 16-bit integer from host byte order to network byte order
* @param h16 Host byte order 16-bit integer
*/
uint16_t csp_hton16(uint16_t h16);
/**
* Convert 16-bit integer from host byte order to host byte order
* @param n16 Network byte order 16-bit integer
*/
uint16_t csp_ntoh16(uint16_t n16);
/**
* Convert 32-bit integer from host byte order to network byte order
* @param h32 Host byte order 32-bit integer
*/
uint32_t csp_hton32(uint32_t h32);
/**
* Convert 32-bit integer from host byte order to host byte order
* @param n32 Network byte order 32-bit integer
*/
uint32_t csp_ntoh32(uint32_t n32);
/**
* Convert 64-bit integer from host byte order to network byte order
* @param h64 Host byte order 64-bit integer
*/
uint64_t csp_hton64(uint64_t h64);
/**
* Convert 64-bit integer from host byte order to host byte order
* @param n64 Network byte order 64-bit integer
*/
uint64_t csp_ntoh64(uint64_t n64);
/**
* Convert 16-bit integer from host byte order to big endian byte order
* @param h16 Host byte order 16-bit integer
*/
uint16_t csp_htobe16(uint16_t h16);
/**
* Convert 16-bit integer from host byte order to little endian byte order
* @param h16 Host byte order 16-bit integer
*/
uint16_t csp_htole16(uint16_t h16);
/**
* Convert 16-bit integer from big endian byte order to little endian byte order
* @param be16 Big endian byte order 16-bit integer
*/
uint16_t csp_betoh16(uint16_t be16);
/**
* Convert 16-bit integer from little endian byte order to host byte order
* @param le16 Little endian byte order 16-bit integer
*/
uint16_t csp_letoh16(uint16_t le16);
/**
* Convert 32-bit integer from host byte order to big endian byte order
* @param h32 Host byte order 32-bit integer
*/
uint32_t csp_htobe32(uint32_t h32);
/**
* Convert 32-bit integer from little endian byte order to host byte order
* @param h32 Host byte order 32-bit integer
*/
uint32_t csp_htole32(uint32_t h32);
/**
* Convert 32-bit integer from big endian byte order to host byte order
* @param be32 Big endian byte order 32-bit integer
*/
uint32_t csp_betoh32(uint32_t be32);
/**
* Convert 32-bit integer from little endian byte order to host byte order
* @param le32 Little endian byte order 32-bit integer
*/
uint32_t csp_letoh32(uint32_t le32);
/**
* Convert 64-bit integer from host byte order to big endian byte order
* @param h64 Host byte order 64-bit integer
*/
uint64_t csp_htobe64(uint64_t h64);
/**
* Convert 64-bit integer from host byte order to little endian byte order
* @param h64 Host byte order 64-bit integer
*/
uint64_t csp_htole64(uint64_t h64);
/**
* Convert 64-bit integer from big endian byte order to host byte order
* @param be64 Big endian byte order 64-bit integer
*/
uint64_t csp_betoh64(uint64_t be64);
/**
* Convert 64-bit integer from little endian byte order to host byte order
* @param le64 Little endian byte order 64-bit integer
*/
uint64_t csp_letoh64(uint64_t le64);
/**
* Convert float from host to network byte order
* @param f Float in host order
* @return Float in network order
*/
float csp_htonflt(float f);
/**
* Convert float from network to host byte order
* @param f Float in network order
* @return Float in host order
*/
float csp_ntohflt(float f);
/**
* Convert double from host to network byte order
* @param d Double in host order
* @return Double in network order
*/
double csp_htondbl(double d);
/**
* Convert double from network to host order
* @param d Double in network order
* @return Double in host order
*/
double csp_ntohdbl(double d);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_ENDIAN_H_

View File

@ -0,0 +1,50 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_ERROR_H_
#define _CSP_ERROR_H_
#ifdef __cplusplus
extern "C" {
#endif
#define CSP_ERR_NONE 0 /* No error */
#define CSP_ERR_NOMEM -1 /* Not enough memory */
#define CSP_ERR_INVAL -2 /* Invalid argument */
#define CSP_ERR_TIMEDOUT -3 /* Operation timed out */
#define CSP_ERR_USED -4 /* Resource already in use */
#define CSP_ERR_NOTSUP -5 /* Operation not supported */
#define CSP_ERR_BUSY -6 /* Device or resource busy */
#define CSP_ERR_ALREADY -7 /* Connection already in progress */
#define CSP_ERR_RESET -8 /* Connection reset */
#define CSP_ERR_NOBUFS -9 /* No more buffer space available */
#define CSP_ERR_TX -10 /* Transmission failed */
#define CSP_ERR_DRIVER -11 /* Error in driver layer */
#define CSP_ERR_AGAIN -12 /* Resource temporarily unavailable */
#define CSP_ERR_HMAC -100 /* HMAC failed */
#define CSP_ERR_XTEA -101 /* XTEA failed */
#define CSP_ERR_CRC32 -102 /* CRC32 failed */
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_ERROR_H_

View File

@ -0,0 +1,56 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef CSP_IFLIST_H_
#define CSP_IFLIST_H_
#include <csp/csp_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* Add interface to list
* @param ifc Pointer to interface to add
*/
void csp_iflist_add(csp_iface_t *ifc);
/**
* Lookup interface by name
* @param name String with interface name
* @return Pointer to interface or NULL if not found
*/
csp_iface_t * csp_iflist_get_by_name(const char *name);
/**
* Print list of interfaces to stdout
*/
void csp_iflist_print(void);
/**
* Return list of registered interfaces.
*/
csp_iface_t * csp_iflist_get(void);
#ifdef __cplusplus
}
#endif
#endif /* CSP_IFLIST_H_ */

View File

@ -0,0 +1,54 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_INTERFACE_H_
#define _CSP_INTERFACE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <csp/csp.h>
/**
* Inputs a new packet into the system
* This function is called from interface drivers ISR to route and accept packets.
* But it can also be called from a task, provided that the pxTaskWoken parameter is NULL!
*
* EXTREMELY IMPORTANT:
* pxTaskWoken arg must ALWAYS be NULL if called from task,
* and ALWAYS be NON NULL if called from ISR!
* If this condition is met, this call is completely thread-safe
*
* This function is fire and forget, it returns void, meaning
* that a packet will always be either accepted or dropped
* so the memory will always be freed.
*
* @param packet A pointer to the incoming packet
* @param interface A pointer to the incoming interface TX function.
* @param pxTaskWoken This must be a pointer a valid variable if called from ISR or NULL otherwise!
*/
void csp_qfifo_write(csp_packet_t *packet, csp_iface_t *interface, CSP_BASE_TYPE *pxTaskWoken);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_INTERFACE_H_

View File

@ -0,0 +1,56 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_PLATFORM_H_
#define _CSP_PLATFORM_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
/* Set OS */
#if defined(CSP_POSIX) || defined(CSP_WINDOWS) || defined(CSP_MACOSX)
#define CSP_BASE_TYPE int
#define CSP_MAX_DELAY (UINT32_MAX)
#define CSP_INFINITY (UINT32_MAX)
#define CSP_DEFINE_CRITICAL(lock) static csp_bin_sem_handle_t lock
#define CSP_INIT_CRITICAL(lock) ({(csp_bin_sem_create(&lock) == CSP_SEMAPHORE_OK) ? CSP_ERR_NONE : CSP_ERR_NOMEM;})
#define CSP_ENTER_CRITICAL(lock) do { csp_bin_sem_wait(&lock, CSP_MAX_DELAY); } while(0)
#define CSP_EXIT_CRITICAL(lock) do { csp_bin_sem_post(&lock); } while(0)
#elif defined(CSP_FREERTOS)
#include "FreeRTOS.h"
#define CSP_BASE_TYPE portBASE_TYPE
#define CSP_MAX_DELAY portMAX_DELAY
#define CSP_INFINITY portMAX_DELAY
#define CSP_DEFINE_CRITICAL(lock)
#define CSP_INIT_CRITICAL(lock) ({CSP_ERR_NONE;})
#define CSP_ENTER_CRITICAL(lock) do { portENTER_CRITICAL(); } while (0)
#define CSP_EXIT_CRITICAL(lock) do { portEXIT_CRITICAL(); } while (0)
#else
#error "OS must be either CSP_POSIX, CSP_MACOSX, CSP_FREERTOS OR CSP_WINDOWS"
#endif
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_PLATFORM_H_

View File

@ -0,0 +1,149 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef CSP_RTABLE_H_
#define CSP_RTABLE_H_
#include <csp/csp_iflist.h>
#ifdef __cplusplus
extern "C" {
#endif
#define CSP_NODE_MAC 0xFF
#define CSP_ROUTE_COUNT (CSP_ID_HOST_MAX + 2)
#define CSP_ROUTE_TABLE_SIZE 5 * CSP_ROUTE_COUNT
/**
* Find outgoing interface in routing table
* @param id Destination node
* @return pointer to outgoing interface or NULL
*/
csp_iface_t * csp_rtable_find_iface(uint8_t id);
/**
* Find MAC address associated with node
* @param id Destination node
* @return MAC address
*/
uint8_t csp_rtable_find_mac(uint8_t id);
/**
* Setup routing entry
* @param node Host
* @param mask Number of bits in netmask
* @param ifc Interface
* @param mac MAC address
* @return CSP error type
*/
int csp_rtable_set(uint8_t node, uint8_t mask, csp_iface_t *ifc, uint8_t mac);
/**
* Print routing table to stdout
*/
void csp_rtable_print(void);
/**
* Load the routing table from a buffer
* (deprecated, please use new csp_rtable_load)
*
* Warning:
* The table will be RAW from memory and contains direct pointers, not interface names.
* Therefore it's very important that a saved routing table is deleted after a firmware update
*
* @param route_table_in pointer to routing table buffer
*/
void csp_route_table_load(uint8_t route_table_in[CSP_ROUTE_TABLE_SIZE]);
/**
* Save the routing table to a buffer
* (deprecated, please use new csp_rtable_save)
*
* Warning:
* The table will be RAW from memory and contains direct pointers, not interface names.
* Therefore it's very important that a saved routing table is deleted after a firmware update
*
* @param route_table_out pointer to routing table buffer
*/
void csp_route_table_save(uint8_t route_table_out[CSP_ROUTE_TABLE_SIZE]);
/**
* Save routing table as a string to a buffer, which can be parsed
* again by csp_rtable_load.
* @param buffer pointer to buffer
* @param maxlen length of buffer
* @return length of saved string
*/
int csp_rtable_save(char * buffer, int maxlen);
/**
* Load routing table from a string in the format
* %u/%u %s %u
* - Address
* - Netmask
* - Ifname
* - Mac Address (this field is optional)
* An example routing string is "0/0 I2C, 8/2 KISS"
* The string must be \0 null terminated
* @param buffer Pointer to string
*/
void csp_rtable_load(const char * buffer);
/**
* Check string for valid routing table
* @param buffer Pointer to string
* @return number of valid entries found
*/
int csp_rtable_check(const char * buffer);
/**
* Clear routing table:
* This could be done before load to ensure an entire clean table is loaded.
*/
void csp_rtable_clear(void);
/**
* Setup routing entry to single node
* (deprecated, please use csp_rtable_set)
*
* @param node Host
* @param ifc Interface
* @param mac MAC address
* @return CSP error type
*/
#define csp_route_set(node, ifc, mac) csp_rtable_set(node, CSP_ID_HOST_SIZE, ifc, mac)
/**
* Print routing table
* (deprecated, please use csp_rtable_print)
*/
#define csp_route_print_table() csp_rtable_print();
/**
* Print list of interfaces
* (deprecated, please use csp_iflist_print)
*/
#define csp_route_print_interfaces() csp_iflist_print();
#ifdef __cplusplus
}
#endif
#endif /* CSP_RTABLE_H_ */

View File

@ -0,0 +1,235 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef CSP_TYPES_H_
#define CSP_TYPES_H_
#include <stdint.h>
#include <csp/csp_autoconfig.h> // -> CSP_HAVE_X defines
#ifdef CSP_HAVE_STDBOOL_H
#include <stdbool.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
/* Make bool for compilers without stdbool.h */
#ifndef CSP_HAVE_STDBOOL_H
#define bool int
#define false 0
#define true !false
#endif
/**
* RESERVED PORTS (SERVICES)
*/
enum csp_reserved_ports_e {
CSP_CMP = 0,
CSP_PING = 1,
CSP_PS = 2,
CSP_MEMFREE = 3,
CSP_REBOOT = 4,
CSP_BUF_FREE = 5,
CSP_UPTIME = 6,
CSP_ANY = (CSP_MAX_BIND_PORT + 1),
CSP_PROMISC = (CSP_MAX_BIND_PORT + 2)
};
typedef enum {
CSP_PRIO_CRITICAL = 0,
CSP_PRIO_HIGH = 1,
CSP_PRIO_NORM = 2,
CSP_PRIO_LOW = 3,
} csp_prio_t;
#define CSP_PRIORITIES (1 << CSP_ID_PRIO_SIZE)
#ifdef CSP_USE_QOS
#define CSP_RX_QUEUE_LENGTH (CSP_CONN_QUEUE_LENGTH / CSP_PRIORITIES)
#define CSP_ROUTE_FIFOS CSP_PRIORITIES
#define CSP_RX_QUEUES CSP_PRIORITIES
#else
#define CSP_RX_QUEUE_LENGTH CSP_CONN_QUEUE_LENGTH
#define CSP_ROUTE_FIFOS 1
#define CSP_RX_QUEUES 1
#endif
/** Size of bit-fields in CSP header */
#define CSP_ID_PRIO_SIZE 2
#define CSP_ID_HOST_SIZE 5
#define CSP_ID_PORT_SIZE 6
#define CSP_ID_FLAGS_SIZE 8
#define CSP_HEADER_BITS (CSP_ID_PRIO_SIZE + 2 * CSP_ID_HOST_SIZE + 2 * CSP_ID_PORT_SIZE + CSP_ID_FLAGS_SIZE)
#define CSP_HEADER_LENGTH (CSP_HEADER_BITS / 8)
#if CSP_HEADER_BITS != 32 && __GNUC__
#error "Header length must be 32 bits"
#endif
/** Highest number to be entered in field */
#define CSP_ID_PRIO_MAX ((1 << (CSP_ID_PRIO_SIZE)) - 1)
#define CSP_ID_HOST_MAX ((1 << (CSP_ID_HOST_SIZE)) - 1)
#define CSP_ID_PORT_MAX ((1 << (CSP_ID_PORT_SIZE)) - 1)
#define CSP_ID_FLAGS_MAX ((1 << (CSP_ID_FLAGS_SIZE)) - 1)
/** Identifier field masks */
#define CSP_ID_PRIO_MASK ((uint32_t) CSP_ID_PRIO_MAX << (CSP_ID_FLAGS_SIZE + 2 * CSP_ID_PORT_SIZE + 2 * CSP_ID_HOST_SIZE))
#define CSP_ID_SRC_MASK ((uint32_t) CSP_ID_HOST_MAX << (CSP_ID_FLAGS_SIZE + 2 * CSP_ID_PORT_SIZE + 1 * CSP_ID_HOST_SIZE))
#define CSP_ID_DST_MASK ((uint32_t) CSP_ID_HOST_MAX << (CSP_ID_FLAGS_SIZE + 2 * CSP_ID_PORT_SIZE))
#define CSP_ID_DPORT_MASK ((uint32_t) CSP_ID_PORT_MAX << (CSP_ID_FLAGS_SIZE + 1 * CSP_ID_PORT_SIZE))
#define CSP_ID_SPORT_MASK ((uint32_t) CSP_ID_PORT_MAX << (CSP_ID_FLAGS_SIZE))
#define CSP_ID_FLAGS_MASK ((uint32_t) CSP_ID_FLAGS_MAX << (0))
#define CSP_ID_CONN_MASK (CSP_ID_SRC_MASK | CSP_ID_DST_MASK | CSP_ID_DPORT_MASK | CSP_ID_SPORT_MASK)
/**
CSP identifier.
*/
typedef union {
//! Entire identifier.
uint32_t ext;
//! Individual fields.
struct __attribute__((__packed__)) {
#if defined(CSP_BIG_ENDIAN) && !defined(CSP_LITTLE_ENDIAN)
unsigned int pri : CSP_ID_PRIO_SIZE;
unsigned int src : CSP_ID_HOST_SIZE;
unsigned int dst : CSP_ID_HOST_SIZE;
unsigned int dport : CSP_ID_PORT_SIZE;
unsigned int sport : CSP_ID_PORT_SIZE;
unsigned int flags : CSP_ID_FLAGS_SIZE;
#elif defined(CSP_LITTLE_ENDIAN) && !defined(CSP_BIG_ENDIAN)
unsigned int flags : CSP_ID_FLAGS_SIZE;
unsigned int sport : CSP_ID_PORT_SIZE;
unsigned int dport : CSP_ID_PORT_SIZE;
unsigned int dst : CSP_ID_HOST_SIZE;
unsigned int src : CSP_ID_HOST_SIZE;
unsigned int pri : CSP_ID_PRIO_SIZE;
#else
#error "Must define one of CSP_BIG_ENDIAN or CSP_LITTLE_ENDIAN in csp_platform.h"
#endif
};
} csp_id_t;
/** Broadcast address */
#define CSP_BROADCAST_ADDR CSP_ID_HOST_MAX
/** Default routing address */
#define CSP_DEFAULT_ROUTE (CSP_ID_HOST_MAX + 1)
/** CSP Flags */
#define CSP_FRES1 0x80 // Reserved for future use
#define CSP_FRES2 0x40 // Reserved for future use
#define CSP_FRES3 0x20 // Reserved for future use
#define CSP_FFRAG 0x10 // Use fragmentation
#define CSP_FHMAC 0x08 // Use HMAC verification
#define CSP_FXTEA 0x04 // Use XTEA encryption
#define CSP_FRDP 0x02 // Use RDP protocol
#define CSP_FCRC32 0x01 // Use CRC32 checksum
/** CSP Socket options */
#define CSP_SO_NONE 0x0000 // No socket options
#define CSP_SO_RDPREQ 0x0001 // Require RDP
#define CSP_SO_RDPPROHIB 0x0002 // Prohibit RDP
#define CSP_SO_HMACREQ 0x0004 // Require HMAC
#define CSP_SO_HMACPROHIB 0x0008 // Prohibit HMAC
#define CSP_SO_XTEAREQ 0x0010 // Require XTEA
#define CSP_SO_XTEAPROHIB 0x0020 // Prohibit HMAC
#define CSP_SO_CRC32REQ 0x0040 // Require CRC32
#define CSP_SO_CRC32PROHIB 0x0080 // Prohibit CRC32
#define CSP_SO_CONN_LESS 0x0100 // Enable Connection Less mode
#define CSP_SO_INTERNAL_LISTEN 0x1000 // Internal flag: listen called on socket
/** CSP Connect options */
#define CSP_O_NONE CSP_SO_NONE // No connection options
#define CSP_O_RDP CSP_SO_RDPREQ // Enable RDP
#define CSP_O_NORDP CSP_SO_RDPPROHIB // Disable RDP
#define CSP_O_HMAC CSP_SO_HMACREQ // Enable HMAC
#define CSP_O_NOHMAC CSP_SO_HMACPROHIB // Disable HMAC
#define CSP_O_XTEA CSP_SO_XTEAREQ // Enable XTEA
#define CSP_O_NOXTEA CSP_SO_XTEAPROHIB // Disable XTEA
#define CSP_O_CRC32 CSP_SO_CRC32REQ // Enable CRC32
#define CSP_O_NOCRC32 CSP_SO_CRC32PROHIB // Disable CRC32
/**
* CSP PACKET STRUCTURE
* Note: This structure is constructed to fit
* with all interface frame types in order to
* have buffer reuse
*/
typedef struct __attribute__((__packed__)) {
uint8_t padding[CSP_PADDING_BYTES]; /**< Interface dependent padding */
uint16_t length; /**< Length field must be just before CSP ID */
csp_id_t id; /**< CSP id must be just before data */
union {
uint8_t data[0]; /**< This just points to the rest of the buffer, without a size indication. */
uint16_t data16[0]; /**< The data 16 and 32 types makes it easy to reference an integer (properly aligned) */
uint32_t data32[0]; /**< without the compiler warning about strict aliasing rules. */
};
} csp_packet_t;
/** Interface TX function */
struct csp_iface_s;
typedef int (*nexthop_t)(struct csp_iface_s * interface, csp_packet_t *packet, uint32_t timeout);
/** Interface struct */
typedef struct csp_iface_s {
const char *name; /**< Interface name (keep below 10 bytes) */
void * driver; /**< Pointer to interface handler structure */
nexthop_t nexthop; /**< Next hop function */
uint16_t mtu; /**< Maximum Transmission Unit of interface */
uint8_t split_horizon_off; /**< Disable the route-loop prevention on if */
uint32_t tx; /**< Successfully transmitted packets */
uint32_t rx; /**< Successfully received packets */
uint32_t tx_error; /**< Transmit errors */
uint32_t rx_error; /**< Receive errors */
uint32_t drop; /**< Dropped packets */
uint32_t autherr; /**< Authentication errors */
uint32_t frame; /**< Frame format errors */
uint32_t txbytes; /**< Transmitted bytes */
uint32_t rxbytes; /**< Received bytes */
uint32_t irq; /**< Interrupts */
struct csp_iface_s *next; /**< Next interface */
} csp_iface_t;
/**
* This define must be equal to the size of the packet overhead in csp_packet_t.
* It is used in csp_buffer_get() to check the allocated buffer size against
* the required buffer size.
*/
#define CSP_BUFFER_PACKET_OVERHEAD (sizeof(csp_packet_t) - sizeof(((csp_packet_t *)0)->data))
/** Forward declaration of socket and connection structures */
typedef struct csp_conn_s csp_socket_t;
typedef struct csp_conn_s csp_conn_t;
#define CSP_HOSTNAME_LEN 20
#define CSP_MODEL_LEN 30
/* CSP_REBOOT magic values */
#define CSP_REBOOT_MAGIC 0x80078007
#define CSP_REBOOT_SHUTDOWN_MAGIC 0xD1E5529A
#ifdef __cplusplus
}
#endif
#endif /* CSP_TYPES_H_ */

View File

@ -0,0 +1,22 @@
/*
* can_socketcan.h
*
* Created on: Feb 6, 2017
* Author: johan
*/
#ifndef LIB_CSP_INCLUDE_CSP_DRIVERS_CAN_SOCKETCAN_H_
#define LIB_CSP_INCLUDE_CSP_DRIVERS_CAN_SOCKETCAN_H_
#include <csp/csp_types.h>
#ifdef __cplusplus
extern "C" {
#endif
csp_iface_t * csp_can_socketcan_init(const char * ifc, int bitrate, int promisc);
#ifdef __cplusplus
}
#endif
#endif /* LIB_CSP_INCLUDE_CSP_DRIVERS_CAN_SOCKETCAN_H_ */

View File

@ -0,0 +1,120 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Common I2C interface,
* This file is derived from the Gomspace I2C driver,
*
*/
#ifndef I2C_H_
#define I2C_H_
#ifdef __cplusplus
extern "C" {
#endif
/**
* The return value of the driver is a bit strange,
* It should return E_NO_ERR if successfull and the value is -1
*/
#define E_NO_ERR -1
/**
* Maximum transfer length on I2C
*/
#define I2C_MTU 256
/**
I2C device modes
@{
*/
/**
I2C Master mode.
*/
#define I2C_MASTER 0
/**
I2C Slave mode.
*/
#define I2C_SLAVE 1
/**@}*/
/**
Data structure for I2C frames.
This structs fits on top of #csp_packet_t, removing the need for copying data.
*/
typedef struct __attribute__((packed)) i2c_frame_s {
//! Not used by CSP
uint8_t padding;
//! Not used by CSP - cleared before Tx
uint8_t retries;
//! Not used by CSP
uint32_t reserved;
//! Destination address
uint8_t dest;
//! Not used by CSP - cleared before Tx
uint8_t len_rx;
//! Length of \a data part
uint16_t len;
//! CSP data
uint8_t data[I2C_MTU];
} i2c_frame_t;
/**
Callback for receiving data.
@param[in] frame received I2C frame
@param[out] pxTaskWoken can be set, if context switch is required due to received data.
*/
typedef void (*i2c_callback_t) (i2c_frame_t * frame, void * pxTaskWoken);
/**
Initialise the I2C driver
Functions is called by csp_i2c_init().
@param handle Which I2C bus (if more than one exists)
@param mode I2C device mode. Must be either I2C_MASTER or I2C_SLAVE
@param addr Own slave address
@param speed Bus speed in kbps
@param queue_len_tx Length of transmit queue
@param queue_len_rx Length of receive queue
@param callback If this value is set, the driver will call this function instead of using an RX queue
@return Error code
*/
int i2c_init(int handle, int mode, uint8_t addr, uint16_t speed, int queue_len_tx, int queue_len_rx, i2c_callback_t callback);
/**
User I2C transmit function.
Called by CSP, when sending message over I2C.
@param handle Handle to the device
@param frame Pointer to I2C frame
@param timeout Ticks to wait
@return Error code
*/
int i2c_send(int handle, i2c_frame_t * frame, uint16_t timeout);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,107 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* Common USART interface,
* This file is derived from the Gomspace USART driver,
* the main difference is the assumption that only one USART will be present on a PC
*/
#ifndef USART_H_
#define USART_H_
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Usart configuration, to be used with the usart_init call.
*/
struct usart_conf {
//! USART device.
const char *device;
//! bits per second.
uint32_t baudrate;
//! Number of data bits.
uint8_t databits;
//! Number of stop bits.
uint8_t stopbits;
//! Parity setting.
uint8_t paritysetting;
//! Enable parity checking (Windows only).
uint8_t checkparity;
};
/**
Initialise UART with the usart_conf data structure
@param[in] conf full configuration structure
*/
void usart_init(struct usart_conf *conf);
/**
In order to catch incoming chars use the callback.
Only one callback per interface.
@param[in] handle usart[0,1,2,3]
@param[in] callback function pointer
*/
typedef void (*usart_callback_t) (uint8_t *buf, int len, void *pxTaskWoken);
/**
Set callback for receiving data.
*/
void usart_set_callback(usart_callback_t callback);
/**
Insert a character to the RX buffer of a usart
@param[in] c character to insert
@param[out] pxTaskWoken can be set, if context switch is required due to received data.
*/
void usart_insert(char c, void *pxTaskWoken);
/**
Polling putchar (stdin).
@param[in] c Character to transmit
*/
void usart_putc(char c);
/**
Send char buffer on UART (stdout).
@param[in] buf Pointer to data
@param[in] len Length of data
*/
void usart_putstr(char *buf, int len);
/**
Buffered getchar (stdin).
@return Character received
*/
char usart_getc(void);
#ifdef __cplusplus
}
#endif
#endif /* USART_H_ */

View File

@ -0,0 +1,76 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_IF_CAN_H_
#define _CSP_IF_CAN_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
#include <csp/csp_interface.h>
/* CAN header macros */
#define CFP_HOST_SIZE 5
#define CFP_TYPE_SIZE 1
#define CFP_REMAIN_SIZE 8
#define CFP_ID_SIZE 10
/* Macros for extracting header fields */
#define CFP_FIELD(id,rsiz,fsiz) ((uint32_t)((uint32_t)((id) >> (rsiz)) & (uint32_t)((1 << (fsiz)) - 1)))
#define CFP_SRC(id) CFP_FIELD(id, CFP_HOST_SIZE + CFP_TYPE_SIZE + CFP_REMAIN_SIZE + CFP_ID_SIZE, CFP_HOST_SIZE)
#define CFP_DST(id) CFP_FIELD(id, CFP_TYPE_SIZE + CFP_REMAIN_SIZE + CFP_ID_SIZE, CFP_HOST_SIZE)
#define CFP_TYPE(id) CFP_FIELD(id, CFP_REMAIN_SIZE + CFP_ID_SIZE, CFP_TYPE_SIZE)
#define CFP_REMAIN(id) CFP_FIELD(id, CFP_ID_SIZE, CFP_REMAIN_SIZE)
#define CFP_ID(id) CFP_FIELD(id, 0, CFP_ID_SIZE)
/* Macros for building CFP headers */
#define CFP_MAKE_FIELD(id,fsiz,rsiz) ((uint32_t)(((id) & (uint32_t)((uint32_t)(1 << (fsiz)) - 1)) << (rsiz)))
#define CFP_MAKE_SRC(id) CFP_MAKE_FIELD(id, CFP_HOST_SIZE, CFP_HOST_SIZE + CFP_TYPE_SIZE + CFP_REMAIN_SIZE + CFP_ID_SIZE)
#define CFP_MAKE_DST(id) CFP_MAKE_FIELD(id, CFP_HOST_SIZE, CFP_TYPE_SIZE + CFP_REMAIN_SIZE + CFP_ID_SIZE)
#define CFP_MAKE_TYPE(id) CFP_MAKE_FIELD(id, CFP_TYPE_SIZE, CFP_REMAIN_SIZE + CFP_ID_SIZE)
#define CFP_MAKE_REMAIN(id) CFP_MAKE_FIELD(id, CFP_REMAIN_SIZE, CFP_ID_SIZE)
#define CFP_MAKE_ID(id) CFP_MAKE_FIELD(id, CFP_ID_SIZE, 0)
/* Mask to uniquely separate connections */
#define CFP_ID_CONN_MASK (CFP_MAKE_SRC((uint32_t)(1 << CFP_HOST_SIZE) - 1) | \
CFP_MAKE_DST((uint32_t)(1 << CFP_HOST_SIZE) - 1) | \
CFP_MAKE_ID((uint32_t)(1 << CFP_ID_SIZE) - 1))
/**
Default Maximum Transmission Unit (MTU) for CSP over CAN.
Maximum value is 2042 bytes.
*/
#define CSP_CAN_MTU 256
int csp_can_rx(csp_iface_t *interface, uint32_t id, const uint8_t * data, uint8_t dlc, CSP_BASE_TYPE *task_woken);
int csp_can_tx(csp_iface_t *interface, csp_packet_t *packet, uint32_t timeout);
/* Must be implemented by the driver */
int csp_can_tx_frame(csp_iface_t *interface, uint32_t id, const uint8_t * data, uint8_t dlc);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _CSP_IF_CAN_H_ */

View File

@ -0,0 +1,51 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_IF_I2C_H_
#define _CSP_IF_I2C_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
#include <csp/csp_interface.h>
#include <csp/drivers/i2c.h>
extern csp_iface_t csp_if_i2c;
/**
* Capture I2C RX events for CSP
* @param opt_addr local i2c address
* @param handle which i2c device to use
* @param speed interface speed in kHz (normally 100 or 400)
* @return csp_error.h code
*/
int csp_i2c_init(uint8_t opt_addr, int handle, int speed);
void csp_i2c_rx(i2c_frame_t * frame, void * pxTaskWoken);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _CSP_IF_I2C_H_ */

View File

@ -0,0 +1,110 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_IF_KISS_H_
#define _CSP_IF_KISS_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <stdint.h>
#include <csp/csp.h>
#include <csp/csp_interface.h>
/**
* The KISS interface relies on the USART callback in order to parse incoming
* messaged from the serial interface. The USART callback however does not
* support passing the handle number of the responding USART, so you need to implement
* a USART callback for each handle and then call kiss_rx subsequently.
*
* In order to initialize the KISS interface. Fist call kiss_init() and then
* setup your usart to call csp_kiss_rx when new data is available.
*
* When a byte is not a part of a kiss packet, it will be returned to your
* usart driver using the usart_insert funtion that you provide.
*
* @param csp_iface pointer to interface
* @param buf pointer to incoming data
* @param len length of incoming data
* @param pxTaskWoken NULL if task context, pointer to variable if ISR
*/
void csp_kiss_rx(csp_iface_t * interface, uint8_t *buf, int len, void *pxTaskWoken);
/**
* The putc function is used by the kiss interface to send
* a string of data to the serial port. This function must
* be implemented by the user, and passed to the kiss
* interface through the kiss_init function.
* @param buf byte to push
*/
typedef void (*csp_kiss_putc_f)(char buf);
/**
* The characters not accepted by the kiss interface, are discarded
* using this function, which must be implemented by the user
* and passed through the kiss_init function.
*
* This reject function is typically used to display ASCII strings
* sent over the serial port, which are not in KISS format. Such as
* debugging information.
*
* @param c rejected character
* @param pxTaskWoken NULL if task context, pointer to variable if ISR
*/
typedef void (*csp_kiss_discard_f)(char c, void *pxTaskWoken);
typedef enum {
KISS_MODE_NOT_STARTED,
KISS_MODE_STARTED,
KISS_MODE_ESCAPED,
KISS_MODE_SKIP_FRAME,
} kiss_mode_e;
/**
* This structure should be statically allocated by the user
* and passed to the kiss interface during the init function
* no member information should be changed
*/
typedef struct csp_kiss_handle_s {
//! Put character on usart (tx).
csp_kiss_putc_f kiss_putc;
//! Discard - not KISS data (rx).
csp_kiss_discard_f kiss_discard;
//! Internal KISS state.
unsigned int rx_length;
//! Internal KISS state.
kiss_mode_e rx_mode;
//! Internal KISS state.
unsigned int rx_first;
//! Not used.
volatile unsigned char *rx_cbuf;
//! Internal KISS state.
csp_packet_t * rx_packet;
} csp_kiss_handle_t;
void csp_kiss_init(csp_iface_t * csp_iface, csp_kiss_handle_t * csp_kiss_handle, csp_kiss_putc_f kiss_putc_f, csp_kiss_discard_f kiss_discard_f, const char * name);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* _CSP_IF_KISS_H_ */

View File

@ -0,0 +1,38 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CSP_IF_LO_H_
#define _CSP_IF_LO_H_
#ifdef __cplusplus
extern "C" {
#endif
/* CSP includes */
#include <csp/csp.h>
#include <csp/csp_interface.h>
extern csp_iface_t csp_if_lo;
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _CSP_IF_LO_H_

View File

@ -0,0 +1,26 @@
#ifndef CSP_IF_ZMQHUB_H_
#define CSP_IF_ZMQHUB_H_
#include <csp/csp.h>
extern csp_iface_t csp_if_zmqhub;
/**
* Setup ZMQ interface
* @param addr only receive messages matching this address (255 means all)
* @param host Pointer to string containing zmqproxy host
* @return CSP_ERR
*/
int csp_zmqhub_init(uint8_t addr, const char * host);
/**
* Setup ZMQ interface
* @param addr only receive messages matching this address (255 means all)
* @param publisher_endpoint Pointer to string containing zmqproxy publisher endpoint
* @param subscriber_endpoint Pointer to string containing zmqproxy subscriber endpoint
* @return CSP_ERR
*/
int csp_zmqhub_init_w_endpoints(uint8_t addr, const char * publisher_url,
const char * subscriber_url);
#endif /* CSP_IF_ZMQHUB_H_ */

12
libcsp/libcsp.mk Normal file
View File

@ -0,0 +1,12 @@
CSRC += $(wildcard $(CURRENTPATH)/src/drivers/can/*.c)
CSRC += $(wildcard $(CURRENTPATH)/src/*.c)
CSRC += $(wildcard $(CURRENTPATH)/src/interfaces/*.c)
CSRC += $(wildcard $(CURRENTPATH)/src/rtable/csp_rtable_cidr.c)
CSRC += $(wildcard $(CURRENTPATH)/src/crypto/*.c)
CSRC += $(wildcard $(CURRENTPATH)/src/arch/posix/*.c)
CSRC += $(wildcard $(CURRENTPATH)/src/transport/*.c)
INCLUDES += $(CURRENTPATH)/include
INCLUDES += $(CURRENTPATH)/include/csp
INCLUDES += $(CURRENTPATH)/include/csp/crypto
INCLUDES += $(CURRENTPATH)

View File

@ -0,0 +1,33 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <csp/arch/csp_malloc.h>
/* FreeRTOS includes */
#include <FreeRTOS.h>
void * csp_malloc(size_t size) {
return pvPortMalloc(size);
}
void csp_free(void *ptr) {
vPortFree(ptr);
}

View File

@ -0,0 +1,66 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
/* FreeRTOS includes */
#include <FreeRTOS.h>
#include <queue.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_queue.h>
csp_queue_handle_t csp_queue_create(int length, size_t item_size) {
return xQueueCreate(length, item_size);
}
void csp_queue_remove(csp_queue_handle_t queue) {
vQueueDelete(queue);
}
int csp_queue_enqueue(csp_queue_handle_t handle, void * value, uint32_t timeout) {
if (timeout != CSP_MAX_DELAY)
timeout = timeout / portTICK_RATE_MS;
return xQueueSendToBack(handle, value, timeout);
}
int csp_queue_enqueue_isr(csp_queue_handle_t handle, void * value, CSP_BASE_TYPE * task_woken) {
return xQueueSendToBackFromISR(handle, value, task_woken);
}
int csp_queue_dequeue(csp_queue_handle_t handle, void * buf, uint32_t timeout) {
if (timeout != CSP_MAX_DELAY)
timeout = timeout / portTICK_RATE_MS;
return xQueueReceive(handle, buf, timeout);
}
int csp_queue_dequeue_isr(csp_queue_handle_t handle, void * buf, CSP_BASE_TYPE * task_woken) {
return xQueueReceiveFromISR(handle, buf, task_woken);
}
int csp_queue_size(csp_queue_handle_t handle) {
return uxQueueMessagesWaiting(handle);
}
int csp_queue_size_isr(csp_queue_handle_t handle) {
return uxQueueMessagesWaitingFromISR(handle);
}

View File

@ -0,0 +1,96 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdint.h>
/* FreeRTOS includes */
#include <FreeRTOS.h>
#include <semphr.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_malloc.h>
#include <csp/arch/csp_semaphore.h>
#include <csp/arch/csp_queue.h>
int csp_mutex_create(csp_mutex_t * mutex) {
*mutex = xSemaphoreCreateMutex();
if (*mutex) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_mutex_remove(csp_mutex_t * mutex) {
return csp_bin_sem_remove(mutex);
}
int csp_mutex_lock(csp_mutex_t * mutex, uint32_t timeout) {
return csp_bin_sem_wait(mutex, timeout);
}
int csp_mutex_unlock(csp_mutex_t * mutex) {
return csp_bin_sem_post(mutex);
}
int csp_bin_sem_create(csp_bin_sem_handle_t * sem) {
vSemaphoreCreateBinary(*sem);
return CSP_SEMAPHORE_OK;
}
int csp_bin_sem_remove(csp_bin_sem_handle_t * sem) {
if ((sem != NULL) && (*sem != NULL)) {
csp_queue_remove(*sem);
}
return CSP_SEMAPHORE_OK;
}
int csp_bin_sem_wait(csp_bin_sem_handle_t * sem, uint32_t timeout) {
csp_log_lock("Wait: %p", sem);
if (timeout != CSP_MAX_DELAY)
timeout = timeout / portTICK_RATE_MS;
if (xSemaphoreTake(*sem, timeout) == pdPASS) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_bin_sem_post(csp_bin_sem_handle_t * sem) {
csp_log_lock("Post: %p", sem);
if (xSemaphoreGive(*sem) == pdPASS) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_bin_sem_post_isr(csp_bin_sem_handle_t * sem, CSP_BASE_TYPE * task_woken) {
csp_log_lock("Post: %p", sem);
if (xSemaphoreGiveFromISR(*sem, task_woken) == pdPASS) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}

View File

@ -0,0 +1,139 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdint.h>
#include <FreeRTOS.h>
#include <task.h>
#include <csp/csp.h>
#include <csp/csp_error.h>
#include <csp/arch/csp_system.h>
int csp_sys_tasklist(char * out) {
#if (tskKERNEL_VERSION_MAJOR < 8)
vTaskList((signed portCHAR *) out);
#else
vTaskList(out);
#endif
return CSP_ERR_NONE;
}
int csp_sys_tasklist_size(void) {
return 40 * uxTaskGetNumberOfTasks();
}
uint32_t csp_sys_memfree(void) {
uint32_t total = 0, max = UINT32_MAX, size;
void * pmem;
/* If size_t is less than 32 bits, start with 10 KiB */
size = sizeof(uint32_t) > sizeof(size_t) ? 10000 : 1000000;
while (1) {
pmem = pvPortMalloc(size + total);
if (pmem == NULL) {
max = size + total;
size = size / 2;
} else {
total += size;
if (total + size >= max)
size = size / 2;
vPortFree(pmem);
}
if (size < 32) break;
}
return total;
}
int csp_sys_reboot(void) {
extern void __attribute__((weak)) cpu_set_reset_cause(unsigned int);
if (cpu_set_reset_cause)
cpu_set_reset_cause(1);
extern void __attribute__((weak)) cpu_reset(void);
if (cpu_reset) {
cpu_reset();
while (1);
}
csp_log_error("Failed to reboot");
return CSP_ERR_INVAL;
}
int csp_sys_shutdown(void) {
extern void __attribute__((weak)) cpu_shutdown(void);
if (cpu_shutdown) {
cpu_shutdown();
while (1);
}
csp_log_error("Failed to shutdown");
return CSP_ERR_INVAL;
}
void csp_sys_set_color(csp_color_t color) {
unsigned int color_code, modifier_code;
switch (color & COLOR_MASK_COLOR) {
case COLOR_BLACK:
color_code = 30; break;
case COLOR_RED:
color_code = 31; break;
case COLOR_GREEN:
color_code = 32; break;
case COLOR_YELLOW:
color_code = 33; break;
case COLOR_BLUE:
color_code = 34; break;
case COLOR_MAGENTA:
color_code = 35; break;
case COLOR_CYAN:
color_code = 36; break;
case COLOR_WHITE:
color_code = 37; break;
case COLOR_RESET:
default:
color_code = 0; break;
}
switch (color & COLOR_MASK_MODIFIER) {
case COLOR_BOLD:
modifier_code = 1; break;
case COLOR_UNDERLINE:
modifier_code = 2; break;
case COLOR_BLINK:
modifier_code = 3; break;
case COLOR_HIDE:
modifier_code = 4; break;
case COLOR_NORMAL:
default:
modifier_code = 0; break;
}
printf("\033[%u;%um", modifier_code, color_code);
}

View File

@ -0,0 +1,38 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <FreeRTOS.h>
#include <task.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_thread.h>
int csp_thread_create(csp_thread_return_t (* routine)(void *), const char * const thread_name, unsigned short stack_depth, void * parameters, unsigned int priority, csp_thread_handle_t * handle) {
#if (tskKERNEL_VERSION_MAJOR >= 8)
portBASE_TYPE ret = xTaskCreate(routine, thread_name, stack_depth, parameters, priority, handle);
#else
portBASE_TYPE ret = xTaskCreate(routine, (signed char *) thread_name, stack_depth, parameters, priority, handle);
#endif
if (ret != pdTRUE)
return CSP_ERR_NOMEM;
return CSP_ERR_NONE;
}

View File

@ -0,0 +1,46 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
/* FreeRTOS includes */
#include <FreeRTOS.h>
#include <task.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_time.h>
uint32_t csp_get_ms(void) {
return (uint32_t)(xTaskGetTickCount() * (1000/configTICK_RATE_HZ));
}
uint32_t csp_get_ms_isr(void) {
return (uint32_t)(xTaskGetTickCountFromISR() * (1000/configTICK_RATE_HZ));
}
uint32_t csp_get_s(void) {
return (uint32_t)(xTaskGetTickCount()/configTICK_RATE_HZ);
}
uint32_t csp_get_s_isr(void) {
return (uint32_t)(xTaskGetTickCountFromISR()/configTICK_RATE_HZ);
}

View File

@ -0,0 +1,31 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <stdlib.h>
void * csp_malloc(size_t size) {
return malloc(size);
}
void csp_free(void *ptr) {
free(ptr);
}

View File

@ -0,0 +1,64 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <pthread.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/posix/pthread_queue.h>
#include <csp/arch/csp_queue.h>
csp_queue_handle_t csp_queue_create(int length, size_t item_size) {
return pthread_queue_create(length, item_size);
}
void csp_queue_remove(csp_queue_handle_t queue) {
return pthread_queue_delete(queue);
}
int csp_queue_enqueue(csp_queue_handle_t handle, void *value, uint32_t timeout) {
return pthread_queue_enqueue(handle, value, timeout);
}
int csp_queue_enqueue_isr(csp_queue_handle_t handle, void * value, CSP_BASE_TYPE * task_woken) {
if (task_woken != NULL)
*task_woken = 0;
return csp_queue_enqueue(handle, value, 0);
}
int csp_queue_dequeue(csp_queue_handle_t handle, void *buf, uint32_t timeout) {
return pthread_queue_dequeue(handle, buf, timeout);
}
int csp_queue_dequeue_isr(csp_queue_handle_t handle, void *buf, CSP_BASE_TYPE * task_woken) {
*task_woken = 0;
return csp_queue_dequeue(handle, buf, 0);
}
int csp_queue_size(csp_queue_handle_t handle) {
return pthread_queue_items(handle);
}
int csp_queue_size_isr(csp_queue_handle_t handle) {
return pthread_queue_items(handle);
}

View File

@ -0,0 +1,105 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <pthread.h>
#include <sys/time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdio.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_semaphore.h>
int csp_mutex_create(csp_mutex_t * mutex) {
csp_log_lock("Mutex init: %p", mutex);
*mutex = pthread_queue_create(1, sizeof(int));
if (mutex) {
int dummy = 0;
pthread_queue_enqueue(*mutex, &dummy, 0);
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_mutex_remove(csp_mutex_t * mutex) {
pthread_queue_delete(*mutex);
return CSP_SEMAPHORE_OK;
}
int csp_mutex_lock(csp_mutex_t * mutex, uint32_t timeout) {
int ret;
csp_log_lock("Wait: %p timeout %"PRIu32, mutex, timeout);
if (timeout == CSP_INFINITY) {
/* TODO: fix this to be infinite */
int dummy = 0;
if (pthread_queue_dequeue(*mutex, &dummy, timeout) == PTHREAD_QUEUE_OK)
ret = CSP_MUTEX_OK;
else
ret = CSP_MUTEX_ERROR;
} else {
int dummy = 0;
if (pthread_queue_dequeue(*mutex, &dummy, timeout) == PTHREAD_QUEUE_OK)
ret = CSP_MUTEX_OK;
else
ret = CSP_MUTEX_ERROR;
}
return ret == CSP_MUTEX_ERROR ? CSP_SEMAPHORE_ERROR : CSP_SEMAPHORE_OK;
}
int csp_mutex_unlock(csp_mutex_t * mutex) {
int dummy = 0;
if (pthread_queue_enqueue(*mutex, &dummy, 0) == PTHREAD_QUEUE_OK) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_bin_sem_create(csp_bin_sem_handle_t * sem) {
return csp_mutex_create(sem);
}
int csp_bin_sem_remove(csp_bin_sem_handle_t * sem) {
return csp_mutex_remove(sem);
}
int csp_bin_sem_wait(csp_bin_sem_handle_t * sem, uint32_t timeout) {
return csp_mutex_lock(sem, timeout);
}
int csp_bin_sem_post(csp_bin_sem_handle_t * sem) {
return csp_mutex_unlock(sem);
}
int csp_bin_sem_post_isr(csp_bin_sem_handle_t * sem, CSP_BASE_TYPE * task_woken) {
return csp_mutex_unlock(sem);
}

View File

@ -0,0 +1,99 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <csp/csp.h>
#include <csp/csp_error.h>
#include <csp/arch/csp_system.h>
int csp_sys_tasklist(char * out) {
strcpy(out, "Tasklist not available on OSX");
return CSP_ERR_NONE;
}
int csp_sys_tasklist_size(void) {
return 100;
}
uint32_t csp_sys_memfree(void) {
/* TODO: Fix memory free on OSX */
uint32_t total = 0;
return total;
}
int csp_sys_reboot(void) {
/* TODO: Fix reboot on OSX */
csp_log_error("Failed to reboot");
return CSP_ERR_INVAL;
}
int csp_sys_shutdown(void) {
/* TODO: Fix shutdown on OSX */
csp_log_error("Failed to shutdown");
return CSP_ERR_INVAL;
}
void csp_sys_set_color(csp_color_t color) {
unsigned int color_code, modifier_code;
switch (color & COLOR_MASK_COLOR) {
case COLOR_BLACK:
color_code = 30; break;
case COLOR_RED:
color_code = 31; break;
case COLOR_GREEN:
color_code = 32; break;
case COLOR_YELLOW:
color_code = 33; break;
case COLOR_BLUE:
color_code = 34; break;
case COLOR_MAGENTA:
color_code = 35; break;
case COLOR_CYAN:
color_code = 36; break;
case COLOR_WHITE:
color_code = 37; break;
case COLOR_RESET:
default:
color_code = 0; break;
}
switch (color & COLOR_MASK_MODIFIER) {
case COLOR_BOLD:
modifier_code = 1; break;
case COLOR_UNDERLINE:
modifier_code = 2; break;
case COLOR_BLINK:
modifier_code = 3; break;
case COLOR_HIDE:
modifier_code = 4; break;
case COLOR_NORMAL:
default:
modifier_code = 0; break;
}
printf("\033[%u;%um", modifier_code, color_code);
}

View File

@ -0,0 +1,31 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <pthread.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_thread.h>
int csp_thread_create(csp_thread_return_t (* routine)(void *), const char * const thread_name, unsigned short stack_depth, void * parameters, unsigned int priority, csp_thread_handle_t * handle) {
return pthread_create(handle, NULL, routine, parameters);
}

View File

@ -0,0 +1,65 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <time.h>
#include <sys/time.h>
#include <mach/clock.h>
#include <mach/mach.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_time.h>
uint32_t csp_get_ms(void) {
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
return (uint32_t)(ts.tv_sec*1000+ts.tv_nsec/1000000);
}
uint32_t csp_get_ms_isr(void) {
return csp_get_ms();
}
uint32_t csp_get_s(void) {
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
return (uint32_t)ts.tv_sec;
}
uint32_t csp_get_s_isr(void) {
return csp_get_s();
}

View File

@ -0,0 +1,179 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Inspired by c-pthread-queue by Matthew Dickinson
http://code.google.com/p/c-pthread-queue/
*/
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <mach/clock.h>
#include <mach/mach.h>
/* CSP includes */
#include <csp/arch/posix/pthread_queue.h>
pthread_queue_t * pthread_queue_create(int length, size_t item_size) {
pthread_queue_t * q = malloc(sizeof(pthread_queue_t));
if (q != NULL) {
q->buffer = malloc(length*item_size);
if (q->buffer != NULL) {
q->size = length;
q->item_size = item_size;
q->items = 0;
q->in = 0;
q->out = 0;
if (pthread_mutex_init(&(q->mutex), NULL) || pthread_cond_init(&(q->cond_full), NULL) || pthread_cond_init(&(q->cond_empty), NULL)) {
free(q->buffer);
free(q);
q = NULL;
}
} else {
free(q);
q = NULL;
}
}
return q;
}
void pthread_queue_delete(pthread_queue_t * q) {
if (q == NULL)
return;
free(q->buffer);
free(q);
return;
}
int pthread_queue_enqueue(pthread_queue_t * queue, void * value, uint32_t timeout) {
int ret;
/* Calculate timeout */
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
uint32_t sec = timeout / 1000;
uint32_t nsec = (timeout - 1000 * sec) * 1000000;
ts.tv_sec += sec;
if (ts.tv_nsec + nsec > 1000000000)
ts.tv_sec++;
ts.tv_nsec = (ts.tv_nsec + nsec) % 1000000000;
/* Get queue lock */
pthread_mutex_lock(&(queue->mutex));
while (queue->items == queue->size) {
ret = pthread_cond_timedwait(&(queue->cond_full), &(queue->mutex), &ts);
if (ret != 0) {
pthread_mutex_unlock(&(queue->mutex));
return PTHREAD_QUEUE_FULL;
}
}
/* Coby object from input buffer */
memcpy(queue->buffer+(queue->in * queue->item_size), value, queue->item_size);
queue->items++;
queue->in = (queue->in + 1) % queue->size;
pthread_mutex_unlock(&(queue->mutex));
/* Nofify blocked threads */
pthread_cond_broadcast(&(queue->cond_empty));
return PTHREAD_QUEUE_OK;
}
int pthread_queue_dequeue(pthread_queue_t * queue, void * buf, uint32_t timeout) {
int ret;
/* Calculate timeout */
struct timespec ts;
clock_serv_t cclock;
mach_timespec_t mts;
host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
clock_get_time(cclock, &mts);
mach_port_deallocate(mach_task_self(), cclock);
ts.tv_sec = mts.tv_sec;
ts.tv_nsec = mts.tv_nsec;
uint32_t sec = timeout / 1000;
uint32_t nsec = (timeout - 1000 * sec) * 1000000;
ts.tv_sec += sec;
if (ts.tv_nsec + nsec > 1000000000)
ts.tv_sec++;
ts.tv_nsec = (ts.tv_nsec + nsec) % 1000000000;
/* Get queue lock */
pthread_mutex_lock(&(queue->mutex));
while (queue->items == 0) {
ret = pthread_cond_timedwait(&(queue->cond_empty), &(queue->mutex), &ts);
if (ret != 0) {
pthread_mutex_unlock(&(queue->mutex));
return PTHREAD_QUEUE_EMPTY;
}
}
/* Coby object to output buffer */
memcpy(buf, queue->buffer+(queue->out * queue->item_size), queue->item_size);
queue->items--;
queue->out = (queue->out + 1) % queue->size;
pthread_mutex_unlock(&(queue->mutex));
/* Nofify blocked threads */
pthread_cond_broadcast(&(queue->cond_full));
return PTHREAD_QUEUE_OK;
}
int pthread_queue_items(pthread_queue_t * queue) {
pthread_mutex_lock(&(queue->mutex));
int items = queue->items;
pthread_mutex_unlock(&(queue->mutex));
return items;
}

View File

@ -0,0 +1,31 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <stdlib.h>
void * csp_malloc(size_t size) {
return malloc(size);
}
void csp_free(void *ptr) {
free(ptr);
}

View File

@ -0,0 +1,64 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <pthread.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/posix/pthread_queue.h>
#include <csp/arch/csp_queue.h>
csp_queue_handle_t csp_queue_create(int length, size_t item_size) {
return pthread_queue_create(length, item_size);
}
void csp_queue_remove(csp_queue_handle_t queue) {
return pthread_queue_delete(queue);
}
int csp_queue_enqueue(csp_queue_handle_t handle, void *value, uint32_t timeout) {
return pthread_queue_enqueue(handle, value, timeout);
}
int csp_queue_enqueue_isr(csp_queue_handle_t handle, void * value, CSP_BASE_TYPE * task_woken) {
if (task_woken != NULL)
*task_woken = 0;
return csp_queue_enqueue(handle, value, 0);
}
int csp_queue_dequeue(csp_queue_handle_t handle, void *buf, uint32_t timeout) {
return pthread_queue_dequeue(handle, buf, timeout);
}
int csp_queue_dequeue_isr(csp_queue_handle_t handle, void *buf, CSP_BASE_TYPE * task_woken) {
*task_woken = 0;
return csp_queue_dequeue(handle, buf, 0);
}
int csp_queue_size(csp_queue_handle_t handle) {
return pthread_queue_items(handle);
}
int csp_queue_size_isr(csp_queue_handle_t handle) {
return pthread_queue_items(handle);
}

View File

@ -0,0 +1,164 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <semaphore.h>
#include <pthread.h>
#include <sys/time.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_semaphore.h>
int csp_mutex_create(csp_mutex_t * mutex) {
csp_log_lock("Mutex init: %p", mutex);
if (pthread_mutex_init(mutex, NULL) == 0) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_mutex_remove(csp_mutex_t * mutex) {
if (pthread_mutex_destroy(mutex) == 0) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_mutex_lock(csp_mutex_t * mutex, uint32_t timeout) {
int ret;
struct timespec ts;
uint32_t sec, nsec;
csp_log_lock("Wait: %p timeout %"PRIu32, mutex, timeout);
if (timeout == CSP_INFINITY) {
ret = pthread_mutex_lock(mutex);
} else {
if (clock_gettime(CLOCK_REALTIME, &ts))
return CSP_SEMAPHORE_ERROR;
sec = timeout / 1000;
nsec = (timeout - 1000 * sec) * 1000000;
ts.tv_sec += sec;
if (ts.tv_nsec + nsec >= 1000000000)
ts.tv_sec++;
ts.tv_nsec = (ts.tv_nsec + nsec) % 1000000000;
ret = pthread_mutex_timedlock(mutex, &ts);
}
if (ret != 0)
return CSP_SEMAPHORE_ERROR;
return CSP_SEMAPHORE_OK;
}
int csp_mutex_unlock(csp_mutex_t * mutex) {
if (pthread_mutex_unlock(mutex) == 0) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_bin_sem_create(csp_bin_sem_handle_t * sem) {
csp_log_lock("Semaphore init: %p", sem);
if (sem_init(sem, 0, 1) == 0) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}
int csp_bin_sem_remove(csp_bin_sem_handle_t * sem) {
if (sem_destroy(sem) == 0)
return CSP_SEMAPHORE_OK;
else
return CSP_SEMAPHORE_ERROR;
}
int csp_bin_sem_wait(csp_bin_sem_handle_t * sem, uint32_t timeout) {
int ret;
struct timespec ts;
uint32_t sec, nsec;
csp_log_lock("Wait: %p timeout %"PRIu32, sem, timeout);
if (timeout == CSP_INFINITY) {
ret = sem_wait(sem);
} else {
if (clock_gettime(CLOCK_REALTIME, &ts))
return CSP_SEMAPHORE_ERROR;
sec = timeout / 1000;
nsec = (timeout - 1000 * sec) * 1000000;
ts.tv_sec += sec;
if (ts.tv_nsec + nsec >= 1000000000)
ts.tv_sec++;
ts.tv_nsec = (ts.tv_nsec + nsec) % 1000000000;
ret = sem_timedwait(sem, &ts);
}
if (ret != 0)
return CSP_SEMAPHORE_ERROR;
return CSP_SEMAPHORE_OK;
}
int csp_bin_sem_post(csp_bin_sem_handle_t * sem) {
CSP_BASE_TYPE dummy = 0;
return csp_bin_sem_post_isr(sem, &dummy);
}
int csp_bin_sem_post_isr(csp_bin_sem_handle_t * sem, CSP_BASE_TYPE * task_woken) {
csp_log_lock("Post: %p", sem);
*task_woken = 0;
int value;
sem_getvalue(sem, &value);
if (value > 0)
return CSP_SEMAPHORE_OK;
if (sem_post(sem) == 0) {
return CSP_SEMAPHORE_OK;
} else {
return CSP_SEMAPHORE_ERROR;
}
}

View File

@ -0,0 +1,131 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdio.h>
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <sys/sysinfo.h>
#include <sys/reboot.h>
#include <linux/reboot.h>
#include <csp/csp.h>
#include <csp/csp_error.h>
#include <csp/arch/csp_system.h>
int csp_sys_tasklist(char * out) {
strcpy(out, "Tasklist not available on POSIX");
return CSP_ERR_NONE;
}
int csp_sys_tasklist_size(void) {
return 100;
}
uint32_t csp_sys_memfree(void) {
uint32_t total = 0;
struct sysinfo info;
sysinfo(&info);
total = info.freeram * info.mem_unit;
return total;
}
int csp_sys_reboot(void) {
#ifdef CSP_USE_INIT_SHUTDOWN
/* Let init(1) handle the reboot */
int ret = system("reboot");
(void) ret; /* Silence warning */
#else
int magic = LINUX_REBOOT_CMD_RESTART;
/* Sync filesystem before reboot */
sync();
reboot(magic);
#endif
/* If reboot(2) returns, it is an error */
csp_log_error("Failed to reboot: %s", strerror(errno));
return CSP_ERR_INVAL;
}
int csp_sys_shutdown(void) {
#ifdef CSP_USE_INIT_SHUTDOWN
/* Let init(1) handle the shutdown */
int ret = system("halt");
(void) ret; /* Silence warning */
#else
int magic = LINUX_REBOOT_CMD_HALT;
/* Sync filesystem before reboot */
sync();
reboot(magic);
#endif
/* If reboot(2) returns, it is an error */
csp_log_error("Failed to shutdown: %s", strerror(errno));
return CSP_ERR_INVAL;
}
void csp_sys_set_color(csp_color_t color) {
unsigned int color_code, modifier_code;
switch (color & COLOR_MASK_COLOR) {
case COLOR_BLACK:
color_code = 30; break;
case COLOR_RED:
color_code = 31; break;
case COLOR_GREEN:
color_code = 32; break;
case COLOR_YELLOW:
color_code = 33; break;
case COLOR_BLUE:
color_code = 34; break;
case COLOR_MAGENTA:
color_code = 35; break;
case COLOR_CYAN:
color_code = 36; break;
case COLOR_WHITE:
color_code = 37; break;
case COLOR_RESET:
default:
color_code = 0; break;
}
switch (color & COLOR_MASK_MODIFIER) {
case COLOR_BOLD:
modifier_code = 1; break;
case COLOR_UNDERLINE:
modifier_code = 2; break;
case COLOR_BLINK:
modifier_code = 3; break;
case COLOR_HIDE:
modifier_code = 4; break;
case COLOR_NORMAL:
default:
modifier_code = 0; break;
}
printf("\033[%u;%um", modifier_code, color_code);
}

View File

@ -0,0 +1,55 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <pthread.h>
#include <limits.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_thread.h>
int csp_thread_create(csp_thread_return_t (* routine)(void *), const char * const thread_name, unsigned short stack_depth, void * parameters, unsigned int priority, csp_thread_handle_t * handle) {
pthread_attr_t attributes, *attr_ref;
int return_code;
if( pthread_attr_init(&attributes) == 0 )
{
unsigned int stack_size = PTHREAD_STACK_MIN;// use at least one memory page
while(stack_size < stack_depth)// must reach at least the provided size
{
stack_size += PTHREAD_STACK_MIN;// keep memory page boundary (some systems may fail otherwise))
}
attr_ref = &attributes;
pthread_attr_setdetachstate(attr_ref, PTHREAD_CREATE_DETACHED);// do not waste memory on each call
pthread_attr_setstacksize(attr_ref, stack_size);
}
else
{
attr_ref = NULL;
}
return_code = pthread_create(handle, attr_ref, routine, parameters);
if( attr_ref != NULL ) pthread_attr_destroy(attr_ref);
return return_code;
}

View File

@ -0,0 +1,54 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <pthread.h>
#include <time.h>
#include <sys/time.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/arch/csp_time.h>
uint32_t csp_get_ms(void) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
return (uint32_t)(ts.tv_sec*1000+ts.tv_nsec/1000000);
else
return 0;
}
uint32_t csp_get_ms_isr(void) {
return csp_get_ms();
}
uint32_t csp_get_s(void) {
struct timespec ts;
if (clock_gettime(CLOCK_MONOTONIC, &ts) == 0)
return (uint32_t)ts.tv_sec;
else
return 0;
}
uint32_t csp_get_s_isr(void) {
return csp_get_s();
}

View File

@ -0,0 +1,243 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/*
Inspired by c-pthread-queue by Matthew Dickinson
http://code.google.com/p/c-pthread-queue/
*/
#include <pthread.h>
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <stdint.h>
#include <sys/time.h>
/* CSP includes */
#include <csp/arch/posix/pthread_queue.h>
static inline int get_deadline(struct timespec *ts, uint32_t timeout_ms)
{
int ret = clock_gettime(CLOCK_MONOTONIC, ts);
if (ret < 0) {
return ret;
}
uint32_t sec = timeout_ms / 1000;
uint32_t nsec = (timeout_ms - 1000 * sec) * 1000000;
ts->tv_sec += sec;
if (ts->tv_nsec + nsec >= 1000000000) {
ts->tv_sec++;
}
ts->tv_nsec = (ts->tv_nsec + nsec) % 1000000000;
return ret;
}
static inline int init_cond_clock_monotonic(pthread_cond_t * cond)
{
int ret;
pthread_condattr_t attr;
pthread_condattr_init(&attr);
ret = pthread_condattr_setclock(&attr, CLOCK_MONOTONIC);
if (ret == 0) {
ret = pthread_cond_init(cond, &attr);
}
pthread_condattr_destroy(&attr);
return ret;
}
pthread_queue_t * pthread_queue_create(int length, size_t item_size) {
pthread_queue_t * q = malloc(sizeof(pthread_queue_t));
if (q != NULL) {
q->buffer = malloc(length*item_size);
if (q->buffer != NULL) {
q->size = length;
q->item_size = item_size;
q->items = 0;
q->in = 0;
q->out = 0;
if (pthread_mutex_init(&(q->mutex), NULL) || init_cond_clock_monotonic(&(q->cond_full)) || init_cond_clock_monotonic(&(q->cond_empty))) {
free(q->buffer);
free(q);
q = NULL;
}
} else {
free(q);
q = NULL;
}
}
return q;
}
void pthread_queue_delete(pthread_queue_t * q) {
if (q == NULL)
return;
free(q->buffer);
free(q);
return;
}
static inline int wait_slot_available(pthread_queue_t * queue, struct timespec *ts) {
int ret;
while (queue->items == queue->size) {
if (ts != NULL) {
ret = pthread_cond_timedwait(&(queue->cond_full), &(queue->mutex), ts);
} else {
ret = pthread_cond_wait(&(queue->cond_full), &(queue->mutex));
}
if (ret != 0 && errno != EINTR) {
return PTHREAD_QUEUE_FULL; //Timeout
}
}
return PTHREAD_QUEUE_OK;
}
int pthread_queue_enqueue(pthread_queue_t * queue, void * value, uint32_t timeout) {
int ret;
struct timespec ts;
struct timespec *pts = NULL;
/* Calculate timeout */
if (timeout != CSP_MAX_DELAY) {
if (get_deadline(&ts, timeout) != 0) {
return PTHREAD_QUEUE_ERROR;
}
pts = &ts;
} else {
pts = NULL;
}
/* Get queue lock */
pthread_mutex_lock(&(queue->mutex));
ret = wait_slot_available(queue, pts);
if (ret == PTHREAD_QUEUE_OK) {
/* Copy object from input buffer */
memcpy(queue->buffer+(queue->in * queue->item_size), value, queue->item_size);
queue->items++;
queue->in = (queue->in + 1) % queue->size;
}
pthread_mutex_unlock(&(queue->mutex));
if (ret == PTHREAD_QUEUE_OK) {
/* Nofify blocked threads */
pthread_cond_broadcast(&(queue->cond_empty));
}
return ret;
}
static inline int wait_item_available(pthread_queue_t * queue, struct timespec *ts) {
int ret;
while (queue->items == 0) {
if (ts != NULL) {
ret = pthread_cond_timedwait(&(queue->cond_empty), &(queue->mutex), ts);
} else {
ret = pthread_cond_wait(&(queue->cond_empty), &(queue->mutex));
}
if (ret != 0 && errno != EINTR) {
return PTHREAD_QUEUE_EMPTY; //Timeout
}
}
return PTHREAD_QUEUE_OK;
}
int pthread_queue_dequeue(pthread_queue_t * queue, void * buf, uint32_t timeout) {
int ret;
struct timespec ts;
struct timespec *pts;
/* Calculate timeout */
if (timeout != CSP_MAX_DELAY) {
if (get_deadline(&ts, timeout) != 0) {
return PTHREAD_QUEUE_ERROR;
}
pts = &ts;
} else {
pts = NULL;
}
/* Get queue lock */
pthread_mutex_lock(&(queue->mutex));
ret = wait_item_available(queue, pts);
if (ret == PTHREAD_QUEUE_OK) {
/* Coby object to output buffer */
memcpy(buf, queue->buffer+(queue->out * queue->item_size), queue->item_size);
queue->items--;
queue->out = (queue->out + 1) % queue->size;
}
pthread_mutex_unlock(&(queue->mutex));
if (ret == PTHREAD_QUEUE_OK) {
/* Nofify blocked threads */
pthread_cond_broadcast(&(queue->cond_full));
}
return ret;
}
int pthread_queue_items(pthread_queue_t * queue) {
pthread_mutex_lock(&(queue->mutex));
int items = queue->items;
pthread_mutex_unlock(&(queue->mutex));
return items;
}

View File

@ -0,0 +1,18 @@
This directory contains files specific to the windows port of libcsp.
To compile and create a static library, execute:
python waf configure --with-os=windows build
from the root of this project. Note python must be in PATH.
The build requirements are:
* Windows Vista SP1
* A recent version of MinGW _or_ MinGW-w64
* Windows API headers
* cPython 2.5 or newer
What provides the Windows API headers depends on the development environment:
Using MinGW: Headers provided by w32api package. windows_glue.h header is needed because these headers do not declare condition variables.
Using MinGW-w64: Headers should be available in the default configuration. You may have to compile the distribution from source. windows_glue.h should not be needed.

View File

@ -0,0 +1,9 @@
#include <stdlib.h>
void * csp_malloc(size_t size) {
return malloc(size);
}
void csp_free(void * ptr) {
free(ptr);
}

View File

@ -0,0 +1,40 @@
#include <stdint.h>
#include <csp/csp.h>
#include <csp/arch/csp_queue.h>
#include "windows_queue.h"
csp_queue_handle_t csp_queue_create(int length, size_t item_size) {
return windows_queue_create(length, item_size);
}
void csp_queue_remove(csp_queue_handle_t queue) {
windows_queue_delete(queue);
}
int csp_queue_enqueue(csp_queue_handle_t handle, void *value, uint32_t timeout) {
return windows_queue_enqueue(handle, value, timeout);
}
int csp_queue_enqueue_isr(csp_queue_handle_t handle, void * value, CSP_BASE_TYPE * task_woken) {
if( task_woken != NULL )
*task_woken = 0;
return windows_queue_enqueue(handle, value, 0);
}
int csp_queue_dequeue(csp_queue_handle_t handle, void *buf, uint32_t timeout) {
return windows_queue_dequeue(handle, buf, timeout);
}
int csp_queue_dequeue_isr(csp_queue_handle_t handle, void * buf, CSP_BASE_TYPE * task_woken) {
if( task_woken != NULL )
*task_woken = 0;
return windows_queue_dequeue(handle, buf, 0);
}
int csp_queue_size(csp_queue_handle_t handle) {
return windows_queue_items(handle);
}
int csp_queue_size_isr(csp_queue_handle_t handle) {
return windows_queue_items(handle);
}

View File

@ -0,0 +1,74 @@
#include <Windows.h>
#include <csp/csp.h>
#include <csp/arch/csp_semaphore.h>
int csp_mutex_create(csp_mutex_t * mutex) {
HANDLE mutexHandle = CreateMutex(NULL, FALSE, FALSE);
if( mutexHandle == NULL ) {
return CSP_MUTEX_ERROR;
}
*mutex = mutexHandle;
return CSP_MUTEX_OK;
}
int csp_mutex_remove(csp_mutex_t * mutex) {
if( !CloseHandle(*mutex) ) {
return CSP_MUTEX_ERROR;
}
return CSP_MUTEX_OK;
}
int csp_mutex_lock(csp_mutex_t * mutex, uint32_t timeout) {
if(WaitForSingleObject(*mutex, timeout) == WAIT_OBJECT_0) {
return CSP_MUTEX_OK;
}
return CSP_MUTEX_ERROR;
}
int csp_mutex_unlock(csp_mutex_t * mutex) {
if( !ReleaseMutex(*mutex) ) {
return CSP_MUTEX_ERROR;
}
return CSP_MUTEX_OK;
}
int csp_bin_sem_create(csp_bin_sem_handle_t * sem) {
HANDLE semHandle = CreateSemaphore(NULL, 1, 1, NULL);
if( semHandle == NULL ) {
return CSP_SEMAPHORE_ERROR;
}
*sem = semHandle;
return CSP_SEMAPHORE_OK;
}
int csp_bin_sem_remove(csp_bin_sem_handle_t * sem) {
if( !CloseHandle(*sem) ) {
return CSP_SEMAPHORE_ERROR;
}
return CSP_SEMAPHORE_OK;
}
int csp_bin_sem_wait(csp_bin_sem_handle_t * sem, uint32_t timeout) {
if( WaitForSingleObject(*sem, timeout) == WAIT_OBJECT_0 ) {
return CSP_SEMAPHORE_OK;
}
return CSP_SEMAPHORE_ERROR;
}
int csp_bin_sem_post(csp_bin_sem_handle_t * sem) {
if( !ReleaseSemaphore(*sem, 1, NULL) ) {
return CSP_SEMAPHORE_ERROR;
}
return CSP_SEMAPHORE_OK;
}
int csp_bin_sem_post_isr(csp_bin_sem_handle_t * sem, CSP_BASE_TYPE * task_woken) {
if( task_woken != NULL ) {
*task_woken = 0;
}
return csp_bin_sem_post(sem);
}

View File

@ -0,0 +1,60 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 Gomspace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <stdint.h>
#include <string.h>
#include <Windows.h>
#include <csp/csp.h>
#include <csp/csp_error.h>
#include <csp/arch/csp_system.h>
int csp_sys_tasklist(char * out) {
strcpy(out, "Tasklist not available on Windows");
return CSP_ERR_NONE;
}
uint32_t csp_sys_memfree(void) {
MEMORYSTATUSEX statex;
statex.dwLength = sizeof(statex);
GlobalMemoryStatusEx(&statex);
DWORDLONG freePhysicalMem = statex.ullAvailPhys;
size_t total = (size_t) freePhysicalMem;
return (uint32_t)total;
}
int csp_sys_reboot(void) {
/* TODO: Fix reboot on Windows */
csp_log_error("Failed to reboot");
return CSP_ERR_INVAL;
}
int csp_sys_shutdown(void) {
/* TODO: Fix shutdown on Windows */
csp_log_error("Failed to shutdown");
return CSP_ERR_INVAL;
}
void csp_sys_set_color(csp_color_t color) {
/* TODO: Add Windows color output here */
}

View File

@ -0,0 +1,11 @@
#include <Windows.h>
#include <process.h>
#include <csp/arch/csp_thread.h>
int csp_thread_create(csp_thread_return_t (* routine)(void *)__attribute__((stdcall)), const char * const thread_name, unsigned short stack_depth, void * parameters, unsigned int priority, csp_thread_handle_t * handle) {
HANDLE taskHandle = (HANDLE) _beginthreadex(NULL, stack_depth, routine, parameters, 0, 0);
if( taskHandle == 0 )
return CSP_ERR_NOMEM; // Failure
*handle = taskHandle;
return CSP_ERR_NONE;
}

View File

@ -0,0 +1,20 @@
#include <Windows.h>
#include <stdint.h>
#include <csp/arch/csp_time.h>
uint32_t csp_get_ms(void) {
return (uint32_t)GetTickCount();
}
uint32_t csp_get_ms_isr(void) {
return csp_get_ms();
}
uint32_t csp_get_s(void) {
uint32_t time_ms = csp_get_ms();
return time_ms/1000;
}
uint32_t csp_get_s_isr(void) {
return csp_get_s();
}

View File

@ -0,0 +1,23 @@
#ifndef WINDOWS_GLUE_H
#define WINDOWS_GLUE_H
#include <Windows.h>
#undef interface
#if (_WIN32_WINNT >= 0x0600)
#define RTL_CONDITION_VARIABLE_INIT 0
#define RTL_CONDITION_VARIABLE_LOCKMODE_SHARED 1
#define CONDITION_VARIABLE_INIT RTL_CONDITION_VARIABLE_INIT
#define CONDITION_VARIABLE_LOCKMODE_SHARED RTL_CONDITION_VARIABLE_LOCKMODE_SHARED
typedef PVOID RTL_CONDITION_VARIABLE;
typedef RTL_CONDITION_VARIABLE CONDITION_VARIABLE, *PCONDITION_VARIABLE;
WINBASEAPI VOID WINAPI InitializeConditionVariable(PCONDITION_VARIABLE ConditionVariable);
WINBASEAPI WINBOOL WINAPI SleepConditionVariableCS(PCONDITION_VARIABLE ConditionVariable, PCRITICAL_SECTION CriticalSection, DWORD dwMilliseconds);
WINBASEAPI VOID WINAPI WakeAllConditionVariable(PCONDITION_VARIABLE ConditionVariable);
WINBASEAPI VOID WINAPI WakeConditionVariable(PCONDITION_VARIABLE ConditionVariable);
#endif // _WIN#"_WINNT
#endif

View File

@ -0,0 +1,91 @@
#include "windows_queue.h"
#include "windows_glue.h"
#include <Windows.h>
static int queueFull(windows_queue_t * queue) {
return queue->items == queue->size;
}
static int queueEmpty(windows_queue_t * queue) {
return queue->items == 0;
}
windows_queue_t * windows_queue_create(int length, size_t item_size) {
windows_queue_t *queue = (windows_queue_t*)malloc(sizeof(windows_queue_t));
if(queue == NULL)
goto queue_malloc_failed;
queue->buffer = malloc(length*item_size);
if(queue->buffer == NULL)
goto buffer_malloc_failed;
queue->size = length;
queue->item_size = item_size;
queue->items = 0;
queue->head_idx = 0;
InitializeCriticalSection(&(queue->mutex));
InitializeConditionVariable(&(queue->cond_full));
InitializeConditionVariable(&(queue->cond_empty));
goto queue_init_success;
buffer_malloc_failed:
free(queue);
queue = NULL;
queue_malloc_failed:
queue_init_success:
return queue;
}
void windows_queue_delete(windows_queue_t * q) {
if(q==NULL) return;
DeleteCriticalSection(&(q->mutex));
free(q->buffer);
free(q);
}
int windows_queue_enqueue(windows_queue_t * queue, void * value, int timeout) {
int offset;
EnterCriticalSection(&(queue->mutex));
while(queueFull(queue)) {
int ret = SleepConditionVariableCS(&(queue->cond_full), &(queue->mutex), timeout);
if( !ret ) {
LeaveCriticalSection(&(queue->mutex));
return ret == WAIT_TIMEOUT ? WINDOWS_QUEUE_FULL : WINDOWS_QUEUE_ERROR;
}
}
offset = ((queue->head_idx+queue->items) % queue->size) * queue->item_size;
memcpy((unsigned char*)queue->buffer + offset, value, queue->item_size);
queue->items++;
LeaveCriticalSection(&(queue->mutex));
WakeAllConditionVariable(&(queue->cond_empty));
return WINDOWS_QUEUE_OK;
}
int windows_queue_dequeue(windows_queue_t * queue, void * buf, int timeout) {
EnterCriticalSection(&(queue->mutex));
while(queueEmpty(queue)) {
int ret = SleepConditionVariableCS(&(queue->cond_empty), &(queue->mutex), timeout);
if( !ret ) {
LeaveCriticalSection(&(queue->mutex));
return ret == WAIT_TIMEOUT ? WINDOWS_QUEUE_EMPTY : WINDOWS_QUEUE_ERROR;
}
}
memcpy(buf, (unsigned char*)queue->buffer+(queue->head_idx%queue->size*queue->item_size), queue->item_size);
queue->items--;
queue->head_idx = (queue->head_idx + 1) % queue->size;
LeaveCriticalSection(&(queue->mutex));
WakeAllConditionVariable(&(queue->cond_full));
return WINDOWS_QUEUE_OK;
}
int windows_queue_items(windows_queue_t * queue) {
int items;
EnterCriticalSection(&(queue->mutex));
items = queue->items;
LeaveCriticalSection(&(queue->mutex));
return items;
}

View File

@ -0,0 +1,41 @@
#ifndef _WINDOWS_QUEUE_H_
#define _WINDOWS_QUEUE_H_
#ifdef __cplusplus
extern "C" {
#endif
#include <Windows.h>
#include "windows_glue.h"
#undef interface
#include <csp/arch/csp_queue.h>
#define WINDOWS_QUEUE_ERROR CSP_QUEUE_ERROR
#define WINDOWS_QUEUE_EMPTY CSP_QUEUE_ERROR
#define WINDOWS_QUEUE_FULL CSP_QUEUE_ERROR
#define WINDOWS_QUEUE_OK CSP_QUEUE_OK
typedef struct windows_queue_s {
void * buffer;
int size;
int item_size;
int items;
int head_idx;
CRITICAL_SECTION mutex;
CONDITION_VARIABLE cond_full;
CONDITION_VARIABLE cond_empty;
} windows_queue_t;
windows_queue_t * windows_queue_create(int length, size_t item_size);
void windows_queue_delete(windows_queue_t * q);
int windows_queue_enqueue(windows_queue_t * queue, void * value, int timeout);
int windows_queue_dequeue(windows_queue_t * queue, void * buf, int timeout);
int windows_queue_items(windows_queue_t * queue);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif // _WINDOWS_QUEUE_H_

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,202 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Hash-based Message Authentication Code - based on code from libtom.org */
#include <stdint.h>
#include <string.h>
#include <stdbool.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/crypto/csp_hmac.h>
#include <csp/crypto/csp_sha1.h>
#ifdef CSP_USE_HMAC
#define HMAC_KEY_LENGTH 16
/* HMAC key */
static uint8_t csp_hmac_key[HMAC_KEY_LENGTH];
/* HMAC state structure */
typedef struct {
csp_sha1_state md;
uint8_t key[SHA1_BLOCKSIZE];
} hmac_state;
static int csp_hmac_init(hmac_state * hmac, const uint8_t * key, uint32_t keylen) {
uint32_t i;
uint8_t buf[SHA1_BLOCKSIZE];
/* NULL pointer and key check */
if (!hmac || !key || keylen < 1)
return CSP_ERR_INVAL;
/* Make sure we have a large enough key */
if(keylen > SHA1_BLOCKSIZE) {
csp_sha1_memory(key, keylen, hmac->key);
if(SHA1_DIGESTSIZE < SHA1_BLOCKSIZE)
memset((hmac->key) + SHA1_DIGESTSIZE, 0, (size_t)(SHA1_BLOCKSIZE - SHA1_DIGESTSIZE));
} else {
memcpy(hmac->key, key, (size_t)keylen);
if(keylen < SHA1_BLOCKSIZE)
memset((hmac->key) + keylen, 0, (size_t)(SHA1_BLOCKSIZE - keylen));
}
/* Create the initial vector */
for(i = 0; i < SHA1_BLOCKSIZE; i++)
buf[i] = hmac->key[i] ^ 0x36;
/* Prepend to the hash data */
csp_sha1_init(&hmac->md);
csp_sha1_process(&hmac->md, buf, SHA1_BLOCKSIZE);
return CSP_ERR_NONE;
}
static int csp_hmac_process(hmac_state * hmac, const uint8_t * in, uint32_t inlen) {
/* NULL pointer check */
if (!hmac || !in)
return CSP_ERR_INVAL;
/* Process data */
csp_sha1_process(&hmac->md, in, inlen);
return CSP_ERR_NONE;
}
static int csp_hmac_done(hmac_state * hmac, uint8_t * out) {
uint32_t i;
uint8_t buf[SHA1_BLOCKSIZE];
uint8_t isha[SHA1_DIGESTSIZE];
if (!hmac || !out)
return CSP_ERR_INVAL;
/* Get the hash of the first HMAC vector plus the data */
csp_sha1_done(&hmac->md, isha);
/* Create the second HMAC vector vector */
for(i = 0; i < SHA1_BLOCKSIZE; i++)
buf[i] = hmac->key[i] ^ 0x5C;
/* Now calculate the outer hash */
csp_sha1_init(&hmac->md);
csp_sha1_process(&hmac->md, buf, SHA1_BLOCKSIZE);
csp_sha1_process(&hmac->md, isha, SHA1_DIGESTSIZE);
csp_sha1_done(&hmac->md, buf);
/* Copy to output */
for (i = 0; i < SHA1_DIGESTSIZE; i++)
out[i] = buf[i];
return CSP_ERR_NONE;
}
int csp_hmac_memory(const uint8_t * key, uint32_t keylen, const uint8_t * data, uint32_t datalen, uint8_t * hmac) {
hmac_state state;
/* NULL pointer check */
if (!key || !data || !hmac)
return CSP_ERR_INVAL;
/* Init HMAC state */
if (csp_hmac_init(&state, key, keylen) != 0)
return CSP_ERR_INVAL;
/* Process data */
if (csp_hmac_process(&state, data, datalen) != 0)
return CSP_ERR_INVAL;
/* Output HMAC */
if (csp_hmac_done(&state, hmac) != 0)
return CSP_ERR_INVAL;
return CSP_ERR_NONE;
}
int csp_hmac_set_key(char * key, uint32_t keylen) {
/* Use SHA1 as KDF */
uint8_t hash[SHA1_DIGESTSIZE];
csp_sha1_memory((uint8_t *)key, keylen, hash);
/* Copy key */
memcpy(csp_hmac_key, hash, HMAC_KEY_LENGTH);
return CSP_ERR_NONE;
}
int csp_hmac_append(csp_packet_t * packet, bool include_header) {
/* NULL pointer check */
if (packet == NULL)
return CSP_ERR_INVAL;
uint8_t hmac[SHA1_DIGESTSIZE];
/* Calculate HMAC */
if (include_header) {
csp_hmac_memory(csp_hmac_key, HMAC_KEY_LENGTH, (uint8_t *) &packet->id, packet->length + sizeof(packet->id), hmac);
} else {
csp_hmac_memory(csp_hmac_key, HMAC_KEY_LENGTH, packet->data, packet->length, hmac);
}
/* Truncate hash and copy to packet */
memcpy(&packet->data[packet->length], hmac, CSP_HMAC_LENGTH);
packet->length += CSP_HMAC_LENGTH;
return CSP_ERR_NONE;
}
int csp_hmac_verify(csp_packet_t * packet, bool include_header) {
/* NULL pointer check */
if (packet == NULL)
return CSP_ERR_INVAL;
uint8_t hmac[SHA1_DIGESTSIZE];
/* Calculate HMAC */
if (include_header) {
csp_hmac_memory(csp_hmac_key, HMAC_KEY_LENGTH, (uint8_t *) &packet->id, packet->length + sizeof(packet->id) - CSP_HMAC_LENGTH, hmac);
} else {
csp_hmac_memory(csp_hmac_key, HMAC_KEY_LENGTH, packet->data, packet->length - CSP_HMAC_LENGTH, hmac);
}
/* Compare calculated HMAC with packet header */
if (memcmp(&packet->data[packet->length] - CSP_HMAC_LENGTH, hmac, CSP_HMAC_LENGTH) != 0) {
/* HMAC failed */
return CSP_ERR_HMAC;
} else {
/* Strip HMAC */
packet->length -= CSP_HMAC_LENGTH;
return CSP_ERR_NONE;
}
}
#endif // CSP_USE_HMAC

View File

@ -0,0 +1,217 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Code originally from Python's SHA1 Module, who based it on libtom.org */
#include <stdint.h>
#include <string.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/crypto/csp_sha1.h>
#if defined(CSP_USE_HMAC) || defined(CSP_USE_XTEA)
/* Rotate left macro */
#define ROL(x,y) (((x) << (y)) | ((x) >> (32-y)))
/* Endian Neutral macros that work on all platforms */
#define STORE32H(x, y) do { (y)[0] = (uint8_t)(((x) >> 24) & 0xff); \
(y)[1] = (uint8_t)(((x) >> 16) & 0xff); \
(y)[2] = (uint8_t)(((x) >> 8) & 0xff); \
(y)[3] = (uint8_t)(((x) >> 0) & 0xff); } while (0)
#define LOAD32H(x, y) do { (x) = ((uint32_t)((y)[0] & 0xff) << 24) | \
((uint32_t)((y)[1] & 0xff) << 16) | \
((uint32_t)((y)[2] & 0xff) << 8) | \
((uint32_t)((y)[3] & 0xff) << 0); } while (0)
#define STORE64H(x, y) do { (y)[0] = (uint8_t)(((x) >> 56) & 0xff); \
(y)[1] = (uint8_t)(((x) >> 48) & 0xff); \
(y)[2] = (uint8_t)(((x) >> 40) & 0xff); \
(y)[3] = (uint8_t)(((x) >> 32) & 0xff); \
(y)[4] = (uint8_t)(((x) >> 24) & 0xff); \
(y)[5] = (uint8_t)(((x) >> 16) & 0xff); \
(y)[6] = (uint8_t)(((x) >> 8) & 0xff); \
(y)[7] = (uint8_t)(((x) >> 0) & 0xff); } while (0)
#define MIN(x, y) (((x) < (y)) ? (x) : (y))
/* SHA1 macros */
#define F0(x,y,z) (z ^ (x & (y ^ z)))
#define F1(x,y,z) (x ^ y ^ z)
#define F2(x,y,z) ((x & y) | (z & (x | y)))
#define F3(x,y,z) (x ^ y ^ z)
#define FF_0(a, b, c, d, e, i) do {e = (ROL(a, 5) + F0(b,c,d) + e + W[i] + 0x5a827999UL); b = ROL(b, 30);} while (0)
#define FF_1(a, b, c, d, e, i) do {e = (ROL(a, 5) + F1(b,c,d) + e + W[i] + 0x6ed9eba1UL); b = ROL(b, 30);} while (0)
#define FF_2(a, b, c, d, e, i) do {e = (ROL(a, 5) + F2(b,c,d) + e + W[i] + 0x8f1bbcdcUL); b = ROL(b, 30);} while (0)
#define FF_3(a, b, c, d, e, i) do {e = (ROL(a, 5) + F3(b,c,d) + e + W[i] + 0xca62c1d6UL); b = ROL(b, 30);} while (0)
static void csp_sha1_compress(csp_sha1_state * sha1, const uint8_t * buf) {
uint32_t a, b, c, d, e, W[80], i;
/* Copy the state into 512-bits into W[0..15] */
for (i = 0; i < 16; i++)
LOAD32H(W[i], buf + (4*i));
/* Copy state */
a = sha1->state[0];
b = sha1->state[1];
c = sha1->state[2];
d = sha1->state[3];
e = sha1->state[4];
/* Expand it */
for (i = 16; i < 80; i++)
W[i] = ROL(W[i-3] ^ W[i-8] ^ W[i-14] ^ W[i-16], 1);
/* Compress */
i = 0;
/* Round one */
for (; i < 20;) {
FF_0(a, b, c, d, e, i++);
FF_0(e, a, b, c, d, i++);
FF_0(d, e, a, b, c, i++);
FF_0(c, d, e, a, b, i++);
FF_0(b, c, d, e, a, i++);
}
/* Round two */
for (; i < 40;) {
FF_1(a, b, c, d, e, i++);
FF_1(e, a, b, c, d, i++);
FF_1(d, e, a, b, c, i++);
FF_1(c, d, e, a, b, i++);
FF_1(b, c, d, e, a, i++);
}
/* Round three */
for (; i < 60;) {
FF_2(a, b, c, d, e, i++);
FF_2(e, a, b, c, d, i++);
FF_2(d, e, a, b, c, i++);
FF_2(c, d, e, a, b, i++);
FF_2(b, c, d, e, a, i++);
}
/* Round four */
for (; i < 80;) {
FF_3(a, b, c, d, e, i++);
FF_3(e, a, b, c, d, i++);
FF_3(d, e, a, b, c, i++);
FF_3(c, d, e, a, b, i++);
FF_3(b, c, d, e, a, i++);
}
/* Store */
sha1->state[0] += a;
sha1->state[1] += b;
sha1->state[2] += c;
sha1->state[3] += d;
sha1->state[4] += e;
}
void csp_sha1_init(csp_sha1_state * sha1) {
sha1->state[0] = 0x67452301UL;
sha1->state[1] = 0xefcdab89UL;
sha1->state[2] = 0x98badcfeUL;
sha1->state[3] = 0x10325476UL;
sha1->state[4] = 0xc3d2e1f0UL;
sha1->curlen = 0;
sha1->length = 0;
}
void csp_sha1_process(csp_sha1_state * sha1, const uint8_t * in, uint32_t inlen) {
uint32_t n;
while (inlen > 0) {
if (sha1->curlen == 0 && inlen >= SHA1_BLOCKSIZE) {
csp_sha1_compress(sha1, in);
sha1->length += SHA1_BLOCKSIZE * 8;
in += SHA1_BLOCKSIZE;
inlen -= SHA1_BLOCKSIZE;
} else {
n = MIN(inlen, (SHA1_BLOCKSIZE - sha1->curlen));
memcpy(sha1->buf + sha1->curlen, in, (size_t)n);
sha1->curlen += n;
in += n;
inlen -= n;
if (sha1->curlen == SHA1_BLOCKSIZE) {
csp_sha1_compress(sha1, sha1->buf);
sha1->length += 8*SHA1_BLOCKSIZE;
sha1->curlen = 0;
}
}
}
}
void csp_sha1_done(csp_sha1_state * sha1, uint8_t * out) {
uint32_t i;
/* Increase the length of the message */
sha1->length += sha1->curlen * 8;
/* Append the '1' bit */
sha1->buf[sha1->curlen++] = 0x80;
/* If the length is currently above 56 bytes we append zeros
* then compress. Then we can fall back to padding zeros and length
* encoding like normal.
*/
if (sha1->curlen > 56) {
while (sha1->curlen < 64)
sha1->buf[sha1->curlen++] = 0;
csp_sha1_compress(sha1, sha1->buf);
sha1->curlen = 0;
}
/* Pad up to 56 bytes of zeroes */
while (sha1->curlen < 56)
sha1->buf[sha1->curlen++] = 0;
/* Store length */
STORE64H(sha1->length, sha1->buf + 56);
csp_sha1_compress(sha1, sha1->buf);
/* Copy output */
for (i = 0; i < 5; i++)
STORE32H(sha1->state[i], out + (4 * i));
}
void csp_sha1_memory(const uint8_t * msg, uint32_t len, uint8_t * hash) {
csp_sha1_state md;
csp_sha1_init(&md);
csp_sha1_process(&md, msg, len);
csp_sha1_done(&md, hash);
}
#endif // CSP_USE_HMAC

View File

@ -0,0 +1,134 @@
/*
Cubesat Space Protocol - A small network-layer protocol designed for Cubesats
Copyright (C) 2012 GomSpace ApS (http://www.gomspace.com)
Copyright (C) 2012 AAUSAT3 Project (http://aausat3.space.aau.dk)
This library 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 2.1 of the License, or (at your option) any later version.
This library 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
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/* Simple implementation of XTEA in CTR mode */
#include <stdint.h>
#include <string.h>
/* CSP includes */
#include <csp/csp.h>
#include <csp/csp_endian.h>
#include <csp/crypto/csp_sha1.h>
#include <csp/crypto/csp_xtea.h>
#ifdef CSP_USE_XTEA
#define XTEA_BLOCKSIZE 8
#define XTEA_ROUNDS 32
#define XTEA_KEY_LENGTH 16
/* XTEA key */
static uint32_t csp_xtea_key[XTEA_KEY_LENGTH/sizeof(uint32_t)] __attribute__ ((aligned(sizeof(uint32_t))));
#define STORE32L(x, y) do { (y)[3] = (uint8_t)(((x) >> 24) & 0xff); \
(y)[2] = (uint8_t)(((x) >> 16) & 0xff); \
(y)[1] = (uint8_t)(((x) >> 8) & 0xff); \
(y)[0] = (uint8_t)(((x) >> 0) & 0xff); } while (0)
#define LOAD32L(x, y) do { (x) = ((uint32_t)((y)[3] & 0xff) << 24) | \
((uint32_t)((y)[2] & 0xff) << 16) | \
((uint32_t)((y)[1] & 0xff) << 8) | \
((uint32_t)((y)[0] & 0xff) << 0); } while (0)
/* This function takes 64 bits of data in block and the 128 bits key in key */
static inline void csp_xtea_encrypt_block(uint8_t *block, uint8_t const *key) {
uint32_t i, v0, v1, delta = 0x9E3779B9, sum = 0, k[4];
LOAD32L(k[0], &key[0]);
LOAD32L(k[1], &key[4]);
LOAD32L(k[2], &key[8]);
LOAD32L(k[3], &key[12]);
LOAD32L(v0, &block[0]);
LOAD32L(v1, &block[4]);
for (i = 0; i < XTEA_ROUNDS; i++) {
v0 += (((v1 << 4) ^ (v1 >> 5)) + v1) ^ (sum + k[sum & 3]);
sum += delta;
v1 += (((v0 << 4) ^ (v0 >> 5)) + v0) ^ (sum + k[(sum >> 11) & 3]);
}
STORE32L(v0, &block[0]);
STORE32L(v1, &block[4]);
}
static inline void csp_xtea_xor_byte(uint8_t * dst, uint8_t * src, uint32_t len) {
unsigned int i;
for (i = 0; i < len; i++)
dst[i] ^= src[i];
}
int csp_xtea_set_key(char * key, uint32_t keylen) {
/* Use SHA1 as KDF */
uint8_t hash[SHA1_DIGESTSIZE];
csp_sha1_memory((uint8_t *)key, keylen, hash);
/* Copy key */
memcpy(csp_xtea_key, hash, XTEA_KEY_LENGTH);
return CSP_ERR_NONE;
}
int csp_xtea_encrypt(uint8_t * plain, const uint32_t len, uint32_t iv[2]) {
unsigned int i;
uint32_t stream[2];
uint32_t blocks = (len + XTEA_BLOCKSIZE - 1)/ XTEA_BLOCKSIZE;
uint32_t remain;
/* Initialize stream */
stream[0] = csp_htobe32(iv[0]);
stream[1] = csp_htobe32(iv[1]);
for (i = 0; i < blocks; i++) {
/* Create stream */
csp_xtea_encrypt_block((uint8_t *)stream, (uint8_t *)csp_xtea_key);
/* Calculate remaining bytes */
remain = len - i * XTEA_BLOCKSIZE;
/* XOR plain text with stream to generate cipher text */
csp_xtea_xor_byte(&plain[len - remain], (uint8_t *)stream, remain < XTEA_BLOCKSIZE ? remain : XTEA_BLOCKSIZE);
/* Increment counter */
stream[0] = csp_htobe32(iv[0]);
stream[1] = csp_htobe32(iv[1]++);
}
return CSP_ERR_NONE;
}
int csp_xtea_decrypt(uint8_t * cipher, const uint32_t len, uint32_t iv[2]) {
/* Since we use counter mode, we can reuse the encryption function */
return csp_xtea_encrypt(cipher, len, iv);
}
#endif // CSP_USE_XTEA

Some files were not shown because too many files have changed in this diff Show More