read temperature test

This commit is contained in:
Jakob Meier 2020-11-28 13:41:30 +01:00
parent 6bd55e7c22
commit fa58479b34
171 changed files with 19670 additions and 14 deletions

View File

@ -323,3 +323,20 @@ 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

View File

@ -6,6 +6,8 @@ CSRC += $(wildcard $(CURRENTPATH)/libcsp/src/crypto/*.c)
CSRC += $(wildcard $(CURRENTPATH)/libcsp/src/arch/posix/*.c)
CSRC += $(wildcard $(CURRENTPATH)/libcsp/src/transport/*.c)
CSRC += $(wildcard $(CURRENTPATH)/p60-dock_client/src/*.c)
CSRC += $(wildcard $(CURRENTPATH)/libutil/src/*.c)
CSRC += $(wildcard $(CURRENTPATH)/libutil/src/linux/*.c)
CSRC += $(wildcard $(CURRENTPATH)/libparam_client/src/*.c)
CSRC += $(wildcard $(CURRENTPATH)/libparam_client/src/rparam/*.c)
@ -16,4 +18,5 @@ INCLUDES += $(CURRENTPATH)/p60-dock_client/include/gs/p60-dock/param
INCLUDES += $(CURRENTPATH)/libparam_client/include
INCLUDES += $(CURRENTPATH)/libparam_client/include/deprecated
INCLUDES += $(CURRENTPATH)/libp60_client/include
INCLUDES += $(CURRENTPATH)/libutil/include
INCLUDES += $(CURRENTPATH)/libutil/include
INCLUDES += $(CURRENTPATH)/libgscsp/include

View File

@ -0,0 +1,65 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_ADDRESS_H
#define LIBGSCSP_INCLUDE_GS_CSP_ADDRESS_H
/* Copyright (c) 2013-2017 GomSpace A/S. All rights reserved. */
/**
@file
Default CSP addresses for nodes in the satellite - often changed for each project.
*/
#ifdef __cplusplus
extern "C" {
#endif
/**
Default address for OBC (On Board Computer).
Example: a3200-sdk.
*/
#define GS_CSP_ADDR_OBC 1
/**
Power supply.
Example: nano-power.
*/
#define GS_CSP_ADDR_EPS 2
/**
Payload address.
*/
#define GS_CSP_ADDR_PAYLOAD_3 3
/**
Default address for ADCS.
Example: a3200-adcs.
*/
#define GS_CSP_ADDR_ADCS 4
/**
Default address for radio.
Example: nanocom-ax.
*/
#define GS_CSP_ADDR_NANOCOM 5
/**
Payload address.
*/
#define GS_CSP_ADDR_PAYLOAD_6 6
/**
Battery pack.
Example: nano-power-bpx.
*/
#define GS_CSP_ADDR_BPX 7
/**
Payload address.
*/
#define GS_CSP_ADDR_PAYLOAD_8 8
/**
Reaction wheels.
Example: gsw-600.
*/
#define GS_CSP_ADDR_GSW600 9
/**
Antenna module.
Example: ant2150.
*/
#define GS_CSP_ADDR_ANT2150 10
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,25 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_COMMAND_H
#define LIBGSCSP_INCLUDE_GS_CSP_COMMAND_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
CSP commands.
*/
#include <gs/util/error.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Register CSP commands.
@return_gs_error_t
*/
gs_error_t gs_csp_register_commands(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,26 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_CONN_H
#define LIBGSCSP_INCLUDE_GS_CSP_CONN_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
Extensions to standard libcsp connection interface.
*/
#include <gs/util/types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Return number of open connections.
@return number of open connections.
*/
size_t gs_csp_conn_get_open(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,202 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_CSP_H
#define LIBGSCSP_INCLUDE_GS_CSP_CSP_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
Extensions to standard libcsp.
*/
#include <gs/csp/error.h>
#include <gs/csp/port.h>
#include <gs/csp/rtable.h>
#include <csp/csp.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Default CSP timeout (mS).
Default timeout value for communicating with a satellite, based on round-trip time of approximately 500 mS.
*/
#define GS_CSP_TIMEOUT 3000
/**
Check if address is a valid CSP adddress.
@param[in] address CSP address to verify
@return \a true if address is valid.
*/
bool gs_csp_is_address_valid(uint8_t address);
/**
gscsp and csp configuration.
*/
typedef struct {
/**
Forward CSP logs to GomSpace log (libutil).
*/
bool use_gs_log;
/**
Use command line options.
Configure interfaces specified on the command line.
@note Only supported on Linux - ignored on platforms without command line options.
*/
bool use_command_line_options;
/**
Size of a CSP buffer (in bytes).
@see csp_buffer_init().
*/
size_t csp_buffer_size;
/**
Number of CSP buffers to allocate.
@see csp_buffer_init().
*/
size_t csp_buffers;
/**
CSP address of the system
*/
uint8_t address;
/**
Host name, returned by the #CSP_CMP_IDENT request.
@note String must remain valid as long as the application is running.
*/
const char *hostname;
/**
Model, returned by the #CSP_CMP_IDENT request.
@note String must remain valid as long as the application is running.
*/
const char *model;
/**
Revision, returned by the #CSP_CMP_IDENT request
@note String must remain valid as long as the application is running.
*/
const char *revision;
} gs_csp_conf_t;
/**
Get default CSP configuration for server systems.
@param[in] conf user supplied configuration struct.
*/
void gs_csp_conf_get_defaults_server(gs_csp_conf_t * conf);
/**
Get default CSP configuration for embedded systems.
@param[in] conf user supplied configuration struct.
*/
void gs_csp_conf_get_defaults_embedded(gs_csp_conf_t * conf);
/**
Initialize CSP.
Wraps initialization of libcsp, by calling following functions
- hooks CSP log system into GomSpace log system.
- initializes CSP buffers by calling csp_buffer_init()
- initializes CSP by calling csp_init()
- configure interfaces specificed on command line
- configure routing table specificed on command line, or default if only one interface is present.
@param[in] conf configuration.
@return_gs_error_t
*/
gs_error_t gs_csp_init(const gs_csp_conf_t * conf);
/**
Perform an entire request/reply transaction,
Copies both input buffer and reply to output buffer.
Also makes the connection and closes it again
Differ from 'csp_transaction()' by limiting input buffer size when input length is unknown
@param[in] prio CSP Prio
@param[in] dest CSP Dest
@param[in] port CSP Port
@param[in] timeout timeout in ms
@param[in] tx_buf pointer to outgoing data buffer
@param[in] tx_len length of request to send
@param[out] rx_buf pointer to incoming data buffer
@param[in] rx_max_len length of expected reply (input buffer size)
@param[out] rx_len pointer to length of reply
@param[in] opts connection options.
@return GS_ERROR_OVERFLOW when input length larger than buffer - it still updates rx_buf
@return GS_ERROR_IO when 'csp_send()' or 'csp_read()' fails
@return GS_ERROR_ALLOC when 'csp_get_buffer()' fails
@return_gs_error_t
*/
gs_error_t gs_csp_transaction2(uint8_t prio,
uint8_t dest,
uint8_t port,
uint32_t timeout,
const void * tx_buf,
size_t tx_len,
void * rx_buf,
size_t rx_max_len,
size_t * rx_len,
uint32_t opts);
/**
Perform an entire request/reply transaction,
@param[in] prio CSP Prio
@param[in] dest CSP Dest
@param[in] port CSP Port
@param[in] timeout timeout in ms
@param[in] tx_buf pointer to outgoing data buffer
@param[in] tx_len length of request to send
@param[out] rx_buf pointer to incoming data buffer
@param[in] rx_max_len length of expected reply (input buffer size)
@param[out] rx_len pointer to length of reply
@return GS_ERROR_OVERFLOW when input length larger than buffer - it still updates rx_buf
@return GS_ERROR_IO when 'csp_send()' or 'csp_read()' fails
@return GS_ERROR_ALLOC when 'csp_get_buffer()' fails
@return_gs_error_t
@see gs_csp_transaction2()
*/
static inline gs_error_t gs_csp_transaction(uint8_t prio,
uint8_t dest,
uint8_t port,
uint32_t timeout,
const void * tx_buf,
size_t tx_len,
void * rx_buf,
size_t rx_max_len,
size_t * rx_len)
{
return gs_csp_transaction2(prio, dest, port, timeout, tx_buf, tx_len, rx_buf, rx_max_len, rx_len, 0);
}
/**
Use an existing connection to perform a transaction.
This is only possible if the next packet is on the same port and destination!
Differ from 'csp_transaction_persistent()' by limiting input buffer size when input length is unknown
@param[in] conn pointer to connection structure
@param[in] timeout timeout in ms
@param[in] tx_buf pointer to outgoing data buffer
@param[in] tx_len length of request to send
@param[out] rx_buf pointer to incoming data buffer
@param[in] rx_max_len length of expected reply (input buffer size)
@param[out] rx_len pointer to length of reply
@return GS_ERROR_OVERFLOW when input length larger than buffer - it still updates rx_buf
@return GS_ERROR_IO when 'csp_send()' or 'csp_read()' fails
@return GS_ERROR_ALLOC when 'csp_get_buffer()' fails
@return_gs_error_t
*/
gs_error_t gs_csp_transaction_persistent(csp_conn_t * conn,
uint32_t timeout,
const void * tx_buf,
size_t tx_len,
void * rx_buf,
size_t rx_max_len,
size_t * rx_len);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,54 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_DRIVERS_CAN_CAN_H
#define LIBGSCSP_INCLUDE_GS_CSP_DRIVERS_CAN_CAN_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
GomSpace CAN API for CSP.
*/
#include <gs/util/error.h>
#include <csp/csp_types.h>
#include <csp/interfaces/csp_if_can.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Default CAN interface name.
*/
#define GS_CSP_CAN_DEFAULT_IF_NAME "CAN"
/**
Initialize CSP for CAN device.
@param[in] device CAN device
@param[in] csp_addr CSP address.
@param[in] mtu MTU, normally CSP_CAN_MTU.
@param[in] name name of CSP interface, if NULL #GS_CSP_CAN_DEFAULT_IF_NAME will be used.
@param[in] set_default_route if \a true, the device will be set as default route.
@param[out] csp_if the added CSP interface.
@return #GS_ERROR_EXIST if device already exists.
@return_gs_error_t
*/
gs_error_t gs_csp_can_init2(uint8_t device, uint8_t csp_addr, uint32_t mtu, const char * name, bool set_default_route, csp_iface_t ** csp_if);
/**
Initialize CSP for CAN device.
@param[in] device CAN device
@param[in] csp_addr CSP address.
@param[in] mtu MTU, normally CSP_CAN_MTU.
@param[in] name name of CSP interface, if NULL #GS_CSP_CAN_DEFAULT_IF_NAME will be used.
@param[out] csp_if the added CSP interface.
@return #GS_ERROR_EXIST if device already exists.
@return_gs_error_t
@see gs_csp_can_init2()
*/
gs_error_t gs_csp_can_init(uint8_t device, uint8_t csp_addr, uint32_t mtu, const char * name, csp_iface_t ** csp_if);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,29 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_DRIVERS_I2C_I2C_H
#define LIBGSCSP_INCLUDE_GS_CSP_DRIVERS_I2C_I2C_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
GomSpace I2C API for CSP.
*/
#include <gs/util/error.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Initialize CSP for I2C device.
@note I2C device must be initialized allready with the same I2C address as the CSP address.
@param[in] device I2C device.
@param[in] csp_addr CSP address.
@return_gs_error_t
*/
gs_error_t gs_csp_i2c_init(uint8_t device, uint8_t csp_addr);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,30 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_DRIVERS_KISS_KISS_H
#define LIBGSCSP_INCLUDE_GS_CSP_DRIVERS_KISS_KISS_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
GomSpace KISS API for CSP.
*/
#include <gs/util/error.h>
#include <csp/interfaces/csp_if_kiss.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Initialize CSP for KISS device.
@note KISS/UART device must be initialized all ready.
@param[in] device KISS/UART device.
@return_gs_error_t
*/
gs_error_t gs_csp_kiss_init(uint8_t device);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,28 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_ERROR_H
#define LIBGSCSP_INCLUDE_GS_CSP_ERROR_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
Converting CSP error codes to #gs_error_t
*/
#include <csp/csp_error.h>
#include <gs/util/error.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Convert CSP error.
@param[in] csp_error CSP error
@return GS error code representing the CSP error.
*/
gs_error_t gs_csp_error(int csp_error);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,24 @@
#ifndef GS_CSP_LINUX_COMMAND_LINE_H
#define GS_CSP_LINUX_COMMAND_LINE_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
Command line support.
*/
#include <gs/util/linux/argp.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Command line options.
*/
extern const struct argp_child gs_csp_command_line_options;
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,27 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_LOG_H
#define LIBGSCSP_INCLUDE_GS_CSP_LOG_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
CSP log hook.
*/
#include <gs/util/error.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Hook into CSP log system.
All CSP logs will be logged through Log (libutil).
@return_gs_error_t
*/
gs_error_t gs_csp_log_init(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,111 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_PORT_H
#define LIBGSCSP_INCLUDE_GS_CSP_PORT_H
/* Copyright (c) 2013-2017 GomSpace A/S. All rights reserved. */
/**
@file
Port definitions for standard CSP and GomSpace services.
*/
#include <csp/csp_types.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Port definitions for standard CSP and GomSpace services.
*/
typedef enum {
/**
CSP Management Protocol - standard CSP service.
*/
GS_CSP_CMP = CSP_CMP, // 0
/**
Ping - standard CSP service.
*/
GS_CSP_PING = CSP_PING, // 1
/**
Show process status - standard CSP service.
*/
GS_CSP_PS = CSP_PS, // 2
/**
Show memory free - standard CSP service.
*/
GS_CSP_MEM_FREE = CSP_MEMFREE, // 3
GS_CSP_MEMFREE = GS_CSP_MEM_FREE,
/**
Reboot/reset request - standard CSP service.
*/
GS_CSP_REBOOT = CSP_REBOOT, // 4
/**
Show number of free CSP buffers - standard CSP service.
*/
GS_CSP_BUF_FREE = CSP_BUF_FREE, // 5
/**
Show uptime (time since last reset) - standard CSP service.
*/
GS_CSP_UPTIME = CSP_UPTIME, // 6
/**
Parameter service (libparam)
*/
GS_CSP_PORT_RPARAM = 7,
/**
File Transfer Service (libftp)
*/
GS_CSP_PORT_FTP = 9,
/**
Remote log service (liblog)
*/
GS_CSP_PORT_RLOG = 11,
/**
Remote GOSH service (librgosh)
*/
GS_CSP_PORT_RGOSH = 12,
/**
AIS command port (libais).
*/
GS_CSP_PORT_AIS = 13,
/**
ADS-B command port (libadsb).
*/
GS_CSP_PORT_ADSB = 14,
/**
GomSpace Sensor Bus (libgssb).
*/
GS_CSP_PORT_GSSB = 16,
/**
Flight Planner (libfp).
*/
GS_CSP_PORT_FP = 18,
/**
ADCS (libadcs).
*/
GS_CSP_PORT_ADCS = 20,
/**
House Keeping (libhk).
*/
GS_CSP_PORT_HK = 21,
/**
G(omSpace) script service (libgosh)
*/
GS_CSP_PORT_GSCRIPT = 22,
/**
Remote shell (libgosh).
Executes shell commands (linux server only).
Requires CSP_O_RDP.
*/
GS_CSP_PORT_REMOTE_SHELL = 27,
/**
House keeping beacon port (libhk).
Default port for sending beacons from satellite to ground (configurable).
*/
GS_CSP_PORT_HK_BEACON = 30,
} gs_csp_port_t;
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,36 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_ROUTER_H
#define LIBGSCSP_INCLUDE_GS_CSP_ROUTER_H
/* Copyright (c) 2013-2017 GomSpace A/S. All rights reserved. */
/**
@file
CSP router task, with support for stopping/terminating router task.
*/
#include <gs/util/thread.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Start CSP router (task/thread).
@param[in] stack_size stack size in bytes, minimum 300 bytes.
@param[in] priority task priority, normally GS_THREAD_PRIORITY_HIGH.
@return_gs_error_t
*/
gs_error_t gs_csp_router_task_start(size_t stack_size, gs_thread_priority_t priority);
/**
Stop CSP router task (for testing).
Signal stop to the router and waits for it to terminate (join).
@note Join is performed, which may hang forever if the router doesn't respond to the stop request.
@return_gs_error_t
*/
gs_error_t gs_csp_router_task_stop(void);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,31 @@
#ifndef GS_CSP_RTABLE_H
#define GS_CSP_RTABLE_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
CSP routing table support.
*/
#include <gs/csp/csp.h>
#include <csp/csp_rtable.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
Load routing table.
Extension to csp_rtable_load().
@param[in] rtable string containing the routing table to set/load.
@param[in] set_default_route if \a true, sets a default route if no routing table specified and only one interface configured.
@param[in] use_command_line_option if \a true (and command line supported), use command line options to configure routing.
@return_gs_error_t
*/
gs_error_t gs_csp_rtable_load(const char * rtable, bool set_default_route, bool use_command_line_option);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,124 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_SERVICE_DISPATCHER_H
#define LIBGSCSP_INCLUDE_GS_CSP_SERVICE_DISPATCHER_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
CSP Service Dispatcher.
The dispatcher is a task/thread, listening on a configured number of ports and forwards the the incoming connection
to a configured CSP service handler.
The dispatcher touches a software watchdog for every handled connection.
*/
#include <gs/csp/service_handler.h>
#include <gs/csp/port.h>
#include <gs/util/thread.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
CSP service dispatcher configuration.
*/
typedef struct {
/**
Name of dispatcher.
*/
const char * name;
/**
Array of service handlers - index'ed by CSP port number.
*/
const gs_csp_service_handler_t * handler_array;
/**
Array size of \a handler_array.
*/
unsigned int handler_array_size;
/**
Bind to any unbound ports (CSP_ANY).
Only one task/dispatcher can bind to any ports. This can be used to log unexpected incoming connections.
*/
bool bind_any;
/**
Disable watchdog.
The watchdog is created with a fixed timeout of 20 seconds.
*/
bool disable_watchdog;
/**
CSP connection backlog.
If 0 (zero), the backlog is set to 10.
*/
size_t listen_backlog;
/**
Callback after timeout or processsed connection.
The return value is the next timeout in milli seconds.
Return UINT32_MAX to use default timeout.
*/
unsigned int (*callback)(void);
/**
Socket options.
*/
uint32_t socket_options;
} gs_csp_service_dispatcher_conf_t;
/**
Basic CSP service handlers.
Can be used to configure handlers for all basic CSP services.
*/
#define GS_CSP_BASIC_SERVICE_HANDLERS \
[GS_CSP_CMP] = gs_csp_cmp_service_handler, \
[GS_CSP_PING] = gs_csp_ping_service_handler, \
[GS_CSP_PS] = gs_csp_ps_service_handler, \
[GS_CSP_MEMFREE] = gs_csp_mem_free_service_handler, \
[GS_CSP_REBOOT] = gs_csp_reboot_service_handler, \
[GS_CSP_BUF_FREE] = gs_csp_buf_free_service_handler, \
[GS_CSP_UPTIME] = gs_csp_uptime_service_handler
/**
Service dispatcher handle.
@see gs_csp_service_dispatcher_create(), gs_csp_service_dispatcher_close()
*/
typedef struct gs_csp_service_dispatcher * gs_csp_service_dispatcher_t;
/**
Create service dispatcher (task/thread).
@param[in] conf configuration - must remain valid as long as the dispatcher is running.
@param[in] stack_size thread stack size.
@param[in] priority thread priority.
@param[out] return_handle created dispatcher - use NULL if not used.
@return_gs_error_t
*/
gs_error_t gs_csp_service_dispatcher_create(const gs_csp_service_dispatcher_conf_t * conf,
size_t stack_size,
gs_thread_priority_t priority,
gs_csp_service_dispatcher_t * return_handle);
/**
Wake up service dispatcher.
This will cause the disapther to wake up (from listing for new connections), and invoke the configured \a callback function,
before listing for new connections.
@param[in] handle dispatcher.
@return_gs_error_t
*/
gs_error_t gs_csp_service_dispatcher_wake_up(gs_csp_service_dispatcher_t handle);
/**
Destroy/close service dispatcher (for testing).
Signal stop to the dispatcher and waits for it to terminate (join).
@note Join is performed, which may hang forever if the dispatcher doesn't respond to the stop request.
@param[in] handle dispatcher.
@return_gs_error_t
*/
gs_error_t gs_csp_service_dispatcher_destroy(gs_csp_service_dispatcher_t handle);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,102 @@
#ifndef LIBGSCSP_INCLUDE_GS_CSP_SERVICE_HANDLER_H
#define LIBGSCSP_INCLUDE_GS_CSP_SERVICE_HANDLER_H
/* Copyright (c) 2013-2018 GomSpace A/S. All rights reserved. */
/**
@file
CSP Service handler.
*/
#include <csp/csp.h>
#include <gs/util/error.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
CSP Service handler.
It is the handler's responsibility to process all pakcets on the connection and close the connection when done - even if a failure
is returned.
@param[in] conn incoming connection.
@return_gs_error_t
*/
typedef gs_error_t (*gs_csp_service_handler_t)(csp_conn_t * conn);
/**
Service handler for CSP Management Protocol.
Invokes standard libcsp service handler.
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_cmp_service_handler(csp_conn_t * conn);
/**
Service handler for ping.
Invokes standard libcsp service handler.
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_ping_service_handler(csp_conn_t * conn);
/**
Service handler for getting process list.
Invokes standard libcsp service handler.
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_ps_service_handler(csp_conn_t * conn);
/**
Service handler for getting memory free.
Invokes GomSpace handler, which doesn't use malloc() to determine \a free memory.
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_mem_free_service_handler(csp_conn_t * conn);
/**
Service handler for reboot (reset) of node.
Invokes standard libcsp service handler.
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_reboot_service_handler(csp_conn_t * conn);
/**
Service handler for getting free CSP buffers.
Invokes standard libcsp service handler.
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_buf_free_service_handler(csp_conn_t * conn);
/**
Service handler for getting uptime (in seconds).
Invokes GomSpace handler (works on Linux).
@param[in] conn incoming connection.
@return_gs_error_t
*/
gs_error_t gs_csp_uptime_service_handler(csp_conn_t * conn);
#ifdef __cplusplus
}
#endif
#endif

View File

@ -0,0 +1,113 @@
libcsp 1.4, 07-05-2015
----------------------
- new: General rtable interface with support for STATIC or CIDR format
- new: CIDR (classless interdomain routing) route table format with netmasks
- new: Bridge capability
- new: Added routing table (de)serialization functions for load/save
- new: Automatic packet deduplication using CRC32 (compile time option)
- new: Autogenerated python bindings using ctypesgen
- new: Task-less operation with router invocation from external scheduler function
- api: Refactor route_if_add to csp_iflist_add
- api: Refactor route_set and friends to rtable_set
- api: Refactor csp_fifo_qos to csp_qfifo
- api: Added defined to be backwards compatible with 1.x
- interfaces: Drop packets on LOOP interface not for own address (blackhole)
- interfaces: New ZMQHUB interface (using zeroMQ over TCP)
- other: Increase stack size from 250 to 1100 for csp_can_rx_task
- other: Cleanup in csp_route.c
- other: Show incoming interface name in debug message
- other: Remove newlines from debug calls
- improvement: Reduce debug hook function complexity with valist passing
- fix: csp_sleep_ms did not work
libcsp 1.3, 07-05-2015
----------------------
- new: Split long process lists into multiple packets
- new: Added posix csp_clock.h
- new: cmp clock functions (requires that you provide csp_clock.h implementation)
- new: Added SFP (Small fragmentation protocol) for larger data chunks
- fix: csp_if_fifo example
- fix: NULL char at the end of rps
- doc: Updated mtu documentation
- other: Tested with FreeRTOS 8.0
- other: Added disable-stlib option to build only object files
libcsp 1.2, 25-10-2013
----------------------
- Feature release
- New: CMP service for peek and poke of memory
- New: CMP interface statistics struct is now packed
- New: Faster O(1) buffer system with reference counting and automatic alignment
- New: Thread safe KISS driver with support for multiple interfaces
- New: CSP interface struct now holds an opaque pointer to driver handle
- New: removed TXBUF from KISS driver entirely to minimize stack usage, added TX lock instead
- New: Pre-calculated CRC table .romem or PROGMEM on __avr__
- New: Added buffer overflow protection to KISS interface
- New: Allow posting null pointers on conn RX queues
- New: Lower memory usage on AVR8
- New: csp_route_save and csp_route_load functions
- New: option --disable-verbose to disable filenames and linenumber on debug
- Protocol: KISS uses csp_crc32 instead of it own embedded crc32
- Improvement: Use buffer clone function to copy promisc packets
- Bugfix: Fix pointer size (32/16bit) in cmp_peek/poke
- Bugfix: Issue with double free in KISS fixed
- Bugfix: Change rdp_send timeout from packet to connection timeout to make sending task block longer
- Bugfix: Fix conn pool leak when using security check and discarding new packets
- Bugfix: Add packet too short check for CRC32
- Bugfix: Accept CRC32 responses from nodes without CRC support
- Bugfix: Ensure csp_ping works for packets > 256 bytes
- Bugfix: Cleanup printf inside ISR functions
- Bugfix: Do not add forwarded packets to promisc queue twice
- Bugfix: Fix return value bug of csp_buffer_get when out of buffers
- Bugfix: Always post null pointer with lowest priority, not highest
- Bugfix: Add check on debug level before calling do_csp_debug, fixes #35
- Other: Export csp/arch include files
- Other: Remove the use of bool type from csp_debug
- Other: Moved csp debug functions to csp_debug.h instead of csp.h
- Other: Ensure assignment of id happens using the uint32_t .ext value of the union, quenches warning
libcsp 1.1, 24-08-2012
----------------------
- Feature release
- Defacto stable since Feb 2012
- New: I2C interface
- New: KISS interface
- New: USART drivers for Linux, Mac and Windows
- New: Windows/MinGW support
- New: MacOSX support
- New: Interface register function
- New: Interface search function
- New: CMP service for remote route updating
- New: CMP service for interface statistics
- Improvement: Better QoS support
- Improvement: Send RDP control messages with high priority
- Improvement: WAF distcheck now works
- Improvement: Automatic endian discovery
- Improvement: Accept packets with CRC32 checksum if compiled without CRC32 support
- Improvement: Do not wake the router task if RDP is not enabled
- Improvement: Save 102 bytes of RAM by packing route entries
- Cleanup: Simplify CAN configuration
- Cleanup: Move architecture specific code to src/arch
- Bugfix: CSP_MEMFREE gives wrong answer on freertos AVR due to truncation
- Bugfix: Fixed wrong 64-bit size_t in csp_service_handler
- Bugfix: Fixed problem in csp_if_kiss when out of buffers
- Bigfix: Handle bus-off CAN IRQ for AT90CAN128
libcsp 1.0.1, 30-10-2011
------------------------
- Hotfix release
- Bugfix: missing extern in csp_if_lo.h
libcsp 1.0, 24-10-2011
----------------------
- First official release
- New: CSP 32-bit header 1.0
- Features: Network Router with promiscous mode, broadcast and QoS
- Features: Connection-oriented transport protocol w. flow-control
- Features: Connection-less "UDP" like transport
- Features: Encryption, Authentication and message check
- Features: Loopback interface
- Features: Python Bindings
- Features: CAN interface w. drivers for several chips
- Features: CSP-services (ping, reboot, uptime, memfree, buffree, ident)

View File

@ -0,0 +1,3 @@
Jeppe Ledet-Pedersen <jeppe@ledets.dk>
Johan De Claville Christiansen <johan@gomspace.com>
Dan Erik Holmstrøm <holmstro@stud.ntnu.no>

View File

@ -0,0 +1,503 @@
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 Free Software Foundation, Inc.
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
not price. Our General Public Licenses are designed to make sure that
you have the freedom to distribute copies of free software (and charge
for this service if you wish); that you receive source code or can get
it if you want it; that you can change the software and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, complete source code means
all the source code for all modules it contains, plus any associated
interface definition files, plus the scripts used to control compilation
and installation of the library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete source code as you receive it, in any medium, provided that
you conspicuously and appropriately publish on each copy an
appropriate copyright notice and disclaimer of warranty; keep intact
all the notices that refer to this License and to the absence of any
warranty; and distribute a copy of this License along with the
Library.
You may charge a fee for the physical act of transferring a copy,
and you may at your option offer warranty protection in exchange for a
fee.
2. You may modify your copy or copies of the Library or any portion
of it, thus forming a work based on the Library, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Library, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote
it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you accompany
it with the complete corresponding machine-readable source code, which
must be distributed under the terms of Sections 1 and 2 above on a
medium customarily used for software interchange.
If distribution of object code is made by offering access to copy
from a designated place, then offering equivalent access to copy the
source code from the same place satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be distributed need not include anything that is
normally distributed (in either source or binary form) with the major
components (compiler, kernel, and so on) of the operating system on
which the executable runs, unless that component itself accompanies
the executable.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library is void, and will automatically terminate your
rights under this License. However, parties who have received copies,
or rights, from you under this License will not have their licenses
terminated so long as such parties remain in full compliance.
9. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
subject to these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties with
this License.
11. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Library.
If any portion of this section is held invalid or unenforceable under any
particular circumstance, the balance of the section is intended to apply,
and the section as a whole is intended to apply in other circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library under this License may add
an explicit geographical distribution limitation excluding those countries,
so that distribution is permitted only in or among countries not thus
excluded. In such case, this License incorporates the limitation as if
written in the body of this License.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser General Public License from time to time.
Such new versions will be similar in spirit to the present version,
but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Library
specifies a version number of this License which applies to it and
"any later version", you have the option of following the terms and
conditions either of that version or of any later version published by
the Free Software Foundation. If the Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
write to the author to ask for permission. For software which is
copyrighted by the Free Software Foundation, write to the Free
Software Foundation; we sometimes make exceptions for this. Our
decision will be guided by the two goals of preserving the free status
of all derivatives of our free software and of promoting the sharing
and reuse of software generally.
NO WARRANTY
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. It is
safest to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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
Also add information on how to contact you by electronic and paper mail.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!

View File

@ -0,0 +1,30 @@
How to install LibCSP
=====================
CSP uses the `waf` build system (http://code.google.com/p/waf/). In order to
compile CSP, you first need to configure the toolchain, what operating system
to compile for, the location of required libraries and whether to enable
certain optional features.
To configure CSP to build with the AVR32 toolchain for FreeRTOS and output
the compiled libcsp.a and header files to the install directory, issue:
.. code-block:: bash
./waf configure --toolchain=avr32- --with-os=freertos --prefix=install
When compiling for FreeRTOS, the path to the FreeRTOS header files must be
specified with `--with-freertos=PATH.`
A number of optional features can be enabled by from the configure script.
Support for XTEA encryption can e.g. be enabled with `--enable-xtea`. Run
`./waf configure --help` to list the available configure options.
The CAN drivers can be enabled by appending the configure option `--with-driver-can=CHIP`,
where CHIP is one of 'socketcan', 'at91sam7a1', 'at91sam7a3' or 'at90can128'.
To build and copy the library to the location specified with --prefix, use:
.. code-block:: bash
./waf build install

View File

@ -0,0 +1,41 @@
The Cubesat Space Protocol
==========================
Cubesat Space Protocol (CSP) is a small protocol stack written in C. CSP is designed to ease communication between distributed embedded systems in smaller networks, such as Cubesats. The design follows the TCP/IP model and includes a transport protocol, a routing protocol and several MAC-layer interfaces. The core of libcsp includes a router, a socket buffer pool and a connection oriented socket API.
The protocol is based on a 32-bit header containing both transport and network-layer information. Its 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 GNU C and is currently ported to run on FreeRTOS or POSIX operating systems such as Linux.
The idea is to give sub-system developers of cubesats the same features of a TCP/IP stack, but without adding the huge overhead of the IP header. The small footprint and simple implementation allows a small 8-bit system with less than 4 kB of RAM to be fully connected on the network. This allows all subsystems to provide their services on the same network level, without any master node required. Using a service oriented architecture has several advantages compared to the traditional mater/slave topology used on many cubesats.
* Standardised network protocol: All subsystems can communicate with eachother
* Service loose coupling: Services maintain a relationship that minimizes dependencies between subsystems
* Service abstraction: Beyond descriptions in the service contract, services hide logic from the outside world
* Service reusability: Logic is divided into services with the intention of promoting reuse.
* Service autonomy: Services have control over the logic they encapsulate.
* Service Redundancy: Easily add redundant services to the bus
* Reduces single point of failure: The complexity is moved from a single master node to several well defines services on the network
The implementation of LibCSP is written with simplicity in mind, but it's compile time configuration allows it to have some rather advanced features as well:
Features
--------
* Thread safe Socket API
* Router task with Quality of Services
* Connection-oriented operation (RFC 908 and 1151).
* Connection-less operation (similar to UDP)
* ICMP-like requests such as ping and buffer status.
* Loopback interface
* Very Small Footprint 48 kB code and less that 1kB ram required on ARM
* Zero-copy buffer and queue system
* Modular network interface system
* Modular OS interface, ported to FreeRTOS, windows (cygwin) and Linux
* Broadcast traffic
* Promiscuous mode
* Encrypted packets with XTEA in CTR mode
* Truncated HMAC-SHA1 Authentication (RFC 2104)
LGPL Software license
---------------------
The source code is available under an LGPL 2.1 license. See COPYING for the license text.

View File

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

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
}

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

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

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

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.

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.

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
============================= =========================================================================

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;
}

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)

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_

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,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_ */

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;
}

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