added cooja; 'The Contiki OS Java Simulator'

This commit is contained in:
fros4943 2006-08-21 12:11:16 +00:00
parent fbd527bc8f
commit e81861a0cd
148 changed files with 23162 additions and 0 deletions

View file

@ -0,0 +1,122 @@
## The COOJA Simulator - cooja platform makefile
##
## This makefile's main purpose is to compile source files
## generated by the COOJA Simulator and should
## only be called from inside the simulator...
##
## However, it can also be used as a shortcut to startup the
## simulator from a customized user platform.
## See the user platform examples.
###########################################################
ifndef COMPILE_MAIN # << shortcut, startup simulator >>
# The COOJA Simulator jar-file location (default)
ifndef COOJA_JAR
COOJA_JAR=$(CONTIKI)/tools/cooja/dist/cooja.jar
endif
# Java binary (default)
ifndef JAVA
JAVA=java
endif
ifndef WINDIR
ifdef OS
ifneq (,$(findstring Windows,$(OS)))
WINDIR := Windows
endif
endif
endif
ifndef WINDIR
# This settings are for UNIX
SEPARATOR=:
else
# These setting are for MS-DOS/Windows 95/Windows NT
SEPARATOR=;
endif
# Command to start simulator with a source file argument
COMMAND = $(JAVA) -DPATH_CONTIKI=$(CONTIKI) -DQUICKSTART_APP=$@ \
-cp "$(COOJA_JAR)$(SEPARATOR)$(COOJA_JAVA)" se.sics.cooja.GUI $(CLASS_CONFIGS)
# Delete pre-defined project sourcefiles (messes up make execution)
PROJECT_SOURCEFILES = # OBS! Ugly fix
%:
@echo "Starting simulator (using shortcut)"
$(COMMAND)
###########################################################
else # << compile generated source file >>
### Check/create COOJA parameters (output files)
ifndef CONTIKI
$(error CONTIKI not defined!)
endif
ifndef TYPEID
$(error TYPEID not defined!)
endif
OUTPUT_DIR = obj_cooja
LIBFILE = $(OUTPUT_DIR)/$(TYPEID).library
DEPFILE = $(OUTPUT_DIR)/$(TYPEID).a
MAPFILE = $(OUTPUT_DIR)/$(TYPEID).map
MAINFILE = $(OUTPUT_DIR)/$(TYPEID).co
COOJA = $(CONTIKI)/platform/$(TARGET)
CONTIKI_TARGET_DIRS = . dev lib sys
COOJA_APPS = testbutton.c testetimer.c testserial.c cooyah.c
COOJA_DEV = $(patsubst $(COOJA)/dev/%.c,%.c,$(wildcard $(COOJA)/dev/*.c))
COOJA_LIB = $(patsubst $(COOJA)/lib/%.c,%.c,$(wildcard $(COOJA)/lib/*.c))
COOJA_SYS = $(patsubst $(COOJA)/sys/%.c,%.c,$(wildcard $(COOJA)/sys/*.c))
CORE_FILES = random.c sensors.c leds.c serial.c
CONTIKI_TARGET_SOURCEFILES = \
$(COOJA_APPS) $(COOJA_DEV) $(COOJA_LIB) $(COOJA_SYS) $(CORE_FILES)
CONTIKI_SOURCEFILES += $(CONTIKI_TARGET_SOURCEFILES)
.SUFFIXES:
### Define the CPU directory
CONTIKI_CPU=$(CONTIKI)/cpu/x86
### Compiler definitions (search contiki core last)
CC = gcc
LD = ld
AS = as
OBJCOPY = objcopy
STRIP = strip
CFLAGSNO = -I. -I$(CONTIKI_CPU) \
$(EXTRA_CC_ARGS) \
-I$(COOJA) \
-I$(CONTIKI)/core \
-DWITH_UIP -DWITH_ASCII \
-Wall -g -I. -I/usr/local/include
CFLAGS = $(CFLAGSNO)
### Setup directory search path for source files
CONTIKI_TARGET_DIRS_CONCAT = ${addprefix $(COOJA)/, \
$(CONTIKI_TARGET_DIRS)}
vpath %.c $(PROJECTDIRS) \
$(CONTIKIDIRS) $(APPDIRS) $(CONTIKI_TARGET_DIRS_CONCAT) \
$(CONTIKI_CPU)
$(LIBFILE): $(MAINFILE) $(PROJECT_OBJECTFILES) $(DEPFILE)
$(LD) -Map=$(MAPFILE) -shared $(LD_ARGS_1) -o $@ $^ $(LD_ARGS_2)
$(DEPFILE): ${addprefix $(OBJECTDIR)/, $(CONTIKI_SOURCEFILES:.c=.o)}
$(AR) rcf $@ $^
endif ## END OF 'COMPILE GENERATED CONTIKI MAIN SOURCE FILE'

View file

@ -0,0 +1,296 @@
#ifndef __CONTIKI_CONF_H__
#define __CONTIKI_CONF_H__
/*
* Copyright (c) 2005, Adam Dunkels.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* 3. The name of the author may not be used to endorse or promote
* products derived from this software without specific prior
* written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* This file is part of the Contiki desktop OS
*
* $Id: contiki-conf.h,v 1.1 2006/08/21 12:11:17 fros4943 Exp $
*
*/
#define CC_CONF_REGISTER_ARGS 1
#define CC_CONF_FUNCTION_POINTER_ARGS 1
#define CC_CONF_FASTCALL
#define CC_CONF_VA_ARGS 1
/*------------------------------------------------------------------------------*/
/**
* \defgroup uipopttypedef uIP type definitions
* @{
*/
#include <inttypes.h>
/**
* The 8-bit unsigned data type.
*
* This may have to be tweaked for your particular compiler. "unsigned
* char" works for most compilers.
*/
typedef uint8_t u8_t;
/**
* The 16-bit unsigned data type.
*
* This may have to be tweaked for your particular compiler. "unsigned
* short" works for most compilers.
*/
typedef uint16_t u16_t;
/**
* The 32-bit unsigned data type.
*
* This may have to be tweaked for your particular compiler. "unsigned
* short" works for most compilers.
*/
typedef uint32_t u32_t;
/**
* The statistics data type.
*
* This datatype determines how high the statistics counters are able
* to count.
*/
typedef unsigned short uip_stats_t;
/** @} */
/*------------------------------------------------------------------------------*/
typedef unsigned long clock_time_t;
#define CLOCK_CONF_SECOND 1000
/*------------------------------------------------------------------------------*/
#include "ctk/ctk-vncarch.h"
/*
* This file is used for setting various compile time settings for the
* CTK GUI toolkit.
*/
/* Toggles mouse support (must have support functions in the
architecture specific files to work). */
#define CTK_CONF_MOUSE_SUPPORT 1
/* Defines which key that is to be used for activating the menus */
#define CTK_CONF_MENU_KEY CH_F1
/* Defines which key that is to be used for switching the frontmost
window. */
#define CTK_CONF_WINDOWSWITCH_KEY CH_F3
/* Defines which key that is to be used for switching to the next
widget. */
#define CTK_CONF_WIDGETDOWN_KEY CH_TAB
/* Defines which key that is to be used for switching to the prevoius
widget. */
#define CTK_CONF_WIDGETUP_KEY CH_F5
/* Toggles support for icons. */
#define CTK_CONF_ICONS 1 /* 107 bytes */
/* Toggles support for icon bitmaps. */
#define CTK_CONF_ICON_BITMAPS 1
/* Toggles support for icon textmaps. */
#define CTK_CONF_ICON_TEXTMAPS 1
/* Toggles support for movable windows. */
#define CTK_CONF_WINDOWMOVE 1 /* 333 bytes */
/* Toggles support for closable windows. */
#define CTK_CONF_WINDOWCLOSE 1 /* 14 bytes */
/* Toggles support for menus. */
#define CTK_CONF_MENUS 1 /* 1384 bytes */
/* Defines the default width of a menu. */
#define CTK_CONF_MENUWIDTH 16
/* The maximum number of menu items in each menu. */
#define CTK_CONF_MAXMENUITEMS 10
#define CTK_CONF_WIDGET_FLAGS 1
/*------------------------------------------------------------------------------*/
#define COLOR_BLACK 0
#define COLOR_WHITE 1
#define BORDERCOLOR COLOR_BLACK
#define SCREENCOLOR COLOR_BLACK
#define WINDOWCOLOR_FOCUS COLOR_WHITE
#define WINDOWCOLOR COLOR_WHITE
#define DIALOGCOLOR COLOR_WHITE
#define WIDGETCOLOR_HLINK COLOR_WHITE
#define WIDGETCOLOR_FWIN COLOR_WHITE
#define WIDGETCOLOR COLOR_WHITE
#define WIDGETCOLOR_DIALOG COLOR_WHITE
#define WIDGETCOLOR_FOCUS COLOR_WHITE
#define MENUCOLOR COLOR_WHITE
#define OPENMENUCOLOR COLOR_WHITE
#define ACTIVEMENUITEMCOLOR COLOR_WHITE
/*------------------------------------------------------------------------------*/
/* Maximum number of clients to the telnet server */
#define CTK_TERM_CONF_MAX_TELNET_CLIENTS 3
/* Telnet server port */
#define CTK_TERM_CONF_TELNET_PORT 23
/* Serial server output buffer size */
#define CTK_TERM_CONF_SERIAL_BUFFER_SIZE 300
/* Maximum number of clients to the terminal module.
Should be set to CTK_TERM_CONF_MAX_TELNET_CLIENTS or
CTK_TERM_CONF_MAX_TELNET_CLIENTS+1 if the serial server is used too
*/
#define CTK_TERM_CONF_MAX_CLIENTS (CTK_TERM_CONF_MAX_TELNET_CLIENTS+1)
/*------------------------------------------------------------------------------*/
#define CTK_VNCSERVER_CONF_NUMCONNS 10
#define CTK_VNCSERVER_CONF_MAX_ICONS 16
/*------------------------------------------------------------------------------*/
#define EMAIL_CONF_WIDTH 36
#define EMAIL_CONF_HEIGHT 16
/*------------------------------------------------------------------------------*/
#define IRC_CONF_WIDTH 78
#define IRC_CONF_HEIGHT 21
#define IRC_CONF_SYSTEM_STRING "GTK simulation"
/*------------------------------------------------------------------------------*/
#define LIBCONIO_CONF_SCREEN_WIDTH 80
#define LIBCONIO_CONF_SCREEN_HEIGHT 45
/*------------------------------------------------------------------------------*/
#define LOG_CONF_ENABLED 1
/*------------------------------------------------------------------------------*/
#define PROGRAM_HANDLER_CONF_MAX_NUMDSCS 10
/*------------------------------------------------------------------------------*/
#define SHELL_GUI_CONF_XSIZE 46
#define SHELL_GUI_CONF_YSIZE 22
/*------------------------------------------------------------------------------*/
#define TELNETD_CONF_LINELEN 80
#define TELNETD_CONF_NUMLINES 16
/*------------------------------------------------------------------------------*/
#define UIP_CONF_MAX_CONNECTIONS 40
#define UIP_CONF_MAX_LISTENPORTS 40
#define UIP_CONF_BUFFER_SIZE 420
#define UIP_CONF_BYTE_ORDER LITTLE_ENDIAN
#define UIP_CONF_BROADCAST 1
#define UIP_CONF_TCP_SPLIT 1
#define UIP_CONF_LOGGING 0
#define UIP_CONF_UDP_CHECKSUMS 0
/*------------------------------------------------------------------------------*/
#define VNC_CONF_VIEWPORT_WIDTH (32*8)
#define VNC_CONF_VIEWPORT_HEIGHT (16*8)
#define VNC_CONF_REFRESH_ROWS 8
/*------------------------------------------------------------------------------*/
/* The size of the HTML viewing area. */
#define WWW_CONF_WEBPAGE_WIDTH 76
#define WWW_CONF_WEBPAGE_HEIGHT 30
/* The size of the "Back" history. */
#define WWW_CONF_HISTORY_SIZE 40
/* Defines the maximum length of an URL */
#define WWW_CONF_MAX_URLLEN 200
/* The maxiumum number of widgets (i.e., hyperlinks, form elements) on
a page. */
#define WWW_CONF_MAX_NUMPAGEWIDGETS 80
/* Turns <center> support on or off; must be on for forms to work. */
#define WWW_CONF_RENDERSTATE 1
/* Toggles support for HTML forms. */
#define WWW_CONF_FORMS 1
/* Maximum lengths for various HTML form parameters. */
#define WWW_CONF_MAX_FORMACTIONLEN 200
#define WWW_CONF_MAX_FORMNAMELEN 200
#define WWW_CONF_MAX_INPUTNAMELEN 200
#define WWW_CONF_MAX_INPUTVALUELEN 240
#define WWW_CONF_PAGEVIEW 1
#define LOADER_CONF_ARCH "loader/dlloader.h"
#endif /* __CONTIKI_CONF_H__ */

89
platform/cooja/cooyah.c Normal file
View file

@ -0,0 +1,89 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: cooyah.c,v 1.1 2006/08/21 12:11:16 fros4943 Exp $
*/
#include <stdio.h>
#include <stdlib.h>
#include "net/uip.h"
#include "lib/sensors.h"
#include "dev/leds.h"
#include "dev/button-sensor.h"
#include "sys/log.h"
#include "node-id.h"
#define COOYAH_PORT 1234
PROCESS(cooyah_example_process, "Example process for report");
AUTOSTART_PROCESSES(&cooyah_example_process);
static struct uip_udp_conn *broadcast_conn;
/*---------------------------------------------------------------------*/
PROCESS_THREAD(cooyah_example_process, ev, data)
{
PROCESS_BEGIN();
log_message("Example process started", "");
broadcast_conn = udp_broadcast_new(COOYAH_PORT , NULL);
button_sensor.activate();
while(1) {
PROCESS_WAIT_EVENT();
log_message("An event occured: ", "");
if(ev == PROCESS_EVENT_EXIT) {
log_message("shutting down\n", "");
break;
}
if(ev == sensors_event && data == &button_sensor && button_sensor.value(0)) {
log_message("the button is pressed, sending packet\n", "");
tcpip_poll_udp(broadcast_conn);
PROCESS_WAIT_UNTIL(ev == tcpip_event && uip_poll());
uip_send("cooyah COOJA", 12);
}
if(ev == sensors_event && data == &button_sensor && !button_sensor.value(0)) {
log_message("the button was released again, doing nothing\n", "");
}
if(ev == tcpip_event && uip_newdata()) {
log_message("a packet was received, turning on leds\n", "");
log_message("PACKET DATA: ", uip_appdata);
leds_on(LEDS_ALL);
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------*/

107
platform/cooja/dev/beep.c Normal file
View file

@ -0,0 +1,107 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: beep.c,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#include "dev/beep.h"
#include "lib/simEnvChange.h"
const struct simInterface beep_interface;
// COOJA variables
char simBeeped;
/*-----------------------------------------------------------------------------------*/
void
beep_alarm(int alarmmode, int len)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep_beep(int i)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep(void)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep_down(int d)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep_on(void)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep_off(void)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep_spinup(void)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void
beep_quick(int n)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
void beep_long(clock_time_t len)
{
simBeeped = 1;
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(beep_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

61
platform/cooja/dev/beep.h Normal file
View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: beep.h,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#ifndef __BEEP_H__
#define __BEEP_H__
#include "sys/clock.h"
#define BEEP_ON 1
#define BEEP_OFF 0
#define BEEP_ALARM1 1
#define BEEP_ALARM2 2
void beep_beep(int len);
void beep_alarm(int alarmmode, int len);
void beep(void);
void beep_down(int len);
void beep_on(void);
void beep_off(void);
void beep_spinup(void);
void beep_long(clock_time_t len);
void beep_quick(int num);
#endif /* __BEEP_H__ */

View file

@ -0,0 +1,115 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: button-sensor.c,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#include "lib/sensors.h"
#include "dev/button-sensor.h"
#include "lib/simEnvChange.h"
const struct simInterface button_interface;
const struct sensors_sensor button_sensor;
// COOJA variables
char simButtonChanged;
char simButtonIsDown;
char simButtonIsActive;
/*---------------------------------------------------------------------------*/
static void
init(void)
{
simButtonIsActive = 1;
}
/*---------------------------------------------------------------------------*/
static int
irq(void)
{
return 1;
}
/*---------------------------------------------------------------------------*/
static void
activate(void)
{
simButtonIsActive = 1;
}
/*---------------------------------------------------------------------------*/
static void
deactivate(void)
{
simButtonIsActive = 0;
}
/*---------------------------------------------------------------------------*/
static int
active(void)
{
return simButtonIsActive;
}
/*---------------------------------------------------------------------------*/
static unsigned int
value(int type)
{
return simButtonIsDown;
}
/*---------------------------------------------------------------------------*/
static int
configure(int type, void *c)
{
return 0;
}
/*---------------------------------------------------------------------------*/
static void *
status(int type)
{
return 0;
}
/*---------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
// Check if button value has changed
if (simButtonChanged && simButtonIsActive) {
sensors_changed(&button_sensor);
simButtonChanged = 0;
}
}
/*---------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*---------------------------------------------------------------------------*/
SIM_INTERFACE(button_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);
SENSORS_SENSOR(button_sensor, BUTTON_SENSOR,
init, irq, activate, deactivate, active,
value, configure, status);

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: button-sensor.h,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#ifndef __BUTTON_H__
#define __BUTTON_H__
extern const struct sensors_sensor button_sensor;
#define BUTTON_SENSOR "Button"
#endif /* __BUTTON_H__ */

67
platform/cooja/dev/ip.c Normal file
View file

@ -0,0 +1,67 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ip.c,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#include "dev/ip.h"
#include "lib/simEnvChange.h"
#include "net/uip.h"
const struct simInterface ip_interface;
// COOJA variables
char simIPa;
char simIPb;
char simIPc;
char simIPd;
char simIPChanged;
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
uip_ipaddr_t hostaddr;
if (simIPChanged) {
uip_ipaddr(&hostaddr, simIPa, simIPb, simIPc, simIPd);
uip_sethostaddr(&hostaddr);
simIPChanged = 0;
}
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(ip_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

35
platform/cooja/dev/ip.h Normal file
View file

@ -0,0 +1,35 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ip.h,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#ifndef __IP_H__
#define __IP_H__
#endif /* __IP_H__ */

36
platform/cooja/dev/irq.c Normal file
View file

@ -0,0 +1,36 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: irq.c,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
void
irq_init(void)
{
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: leds-arch.c,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
#include "dev/leds.h"
#include "lib/simEnvChange.h"
const struct simInterface leds_interface;
// COOJA variables
unsigned char simLedsValue;
/*-----------------------------------------------------------------------------------*/
void leds_arch_init() {
simLedsValue = 0;
}
/*-----------------------------------------------------------------------------------*/
unsigned char leds_arch_get() {
return simLedsValue;
}
/*-----------------------------------------------------------------------------------*/
void leds_arch_set(unsigned char leds) {
if(leds != simLedsValue) {
simLedsValue = leds;
}
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(leds_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

View file

@ -0,0 +1,60 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: moteid.c,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#include "dev/moteid.h"
#include "lib/simEnvChange.h"
#include "lib/random.h"
const struct simInterface moteid_interface;
// COOJA variables
int simMoteID;
char simMoteIDChanged;
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
if (simMoteIDChanged) {
simMoteIDChanged = 0;
random_init((simMoteID+1) * 100 % 99);
}
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(moteid_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

View file

@ -0,0 +1,37 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: moteid.h,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#ifndef __MOTEID_H__
#define __MOTEID_H__
extern int simMoteID;
#endif /* __MOTEID_H__ */

View file

@ -0,0 +1,117 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: pir-sensor.c,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#include "lib/sensors.h"
#include "dev/pir-sensor.h"
#include "lib/simEnvChange.h"
const struct simInterface pir_interface;
const struct sensors_sensor pir_sensor;
// COOJA variables
char simPirChanged;
char simPirIsActive;
char simPirValue = 0;
/*---------------------------------------------------------------------------*/
static void
init(void)
{
simPirIsActive = 1;
}
/*---------------------------------------------------------------------------*/
static int
irq(void)
{
return 0;
}
/*---------------------------------------------------------------------------*/
static void
activate(void)
{
simPirIsActive = 1;
}
/*---------------------------------------------------------------------------*/
static void
deactivate(void)
{
simPirIsActive = 0;
}
/*---------------------------------------------------------------------------*/
static int
active(void)
{
return simPirIsActive;
}
/*---------------------------------------------------------------------------*/
static unsigned int
value(int type)
{
return simPirValue;
}
/*---------------------------------------------------------------------------*/
static int
configure(int type, void *c)
{
return 0;
}
/*---------------------------------------------------------------------------*/
static void *
status(int type)
{
return NULL;
}
/*---------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
// Check if PIR value has changed
if (simPirIsActive && simPirChanged) {
simPirValue = !simPirValue;
sensors_changed(&pir_sensor);
simPirChanged = 0;
}
}
/*---------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*---------------------------------------------------------------------------*/
SIM_INTERFACE(pir_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);
SENSORS_SENSOR(pir_sensor, PIR_SENSOR,
init, irq, activate, deactivate, active,
value, configure, status);

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: pir-sensor.h,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#ifndef __PIR_H__
#define __PIR_H__
extern const struct sensors_sensor pir_sensor;
#define PIR_SENSOR "PIR"
#endif /* __PIR_H__ */

View file

@ -0,0 +1,205 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: radio-arch.c,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
#include "dev/radio-arch.h"
#include "dev/radio.h"
#include "lib/simEnvChange.h"
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "net/uip.h"
#include "net/uip-fw.h"
#include "sys/etimer.h"
#include "sys/log.h"
const struct simInterface radio_interface;
// COOJA variables
char simReceivedPacket;
char simSentPacket;
char simReceivedPacketData[UIP_BUFSIZE];
char simSentPacketData[UIP_BUFSIZE];
int simSentPacketSize;
int simReceivedPacketSize;
char simEtherBusy;
int retryCounter;
char simRadioHWOn = 1;
// Ether process
PROCESS(ether_process, "Simulated Ether");
PROCESS_THREAD(ether_process, ev, data)
{
static struct etimer send_timer;
PROCESS_BEGIN();
// All outgoing messages pass through this process
// By using the COOJA variables simEtherBusy and !!!!TODO signalstrength!!!!
// this may be used to imitate a simple MAC protocol.
while(1) {
PROCESS_WAIT_EVENT();
// MAC protocol imitiation
// (this process is polled from simDoSend())
// Confirm we actually have data to send and radio hardware is on
if (simRadioHWOn && simSentPacketSize > 0) {
// Wait some random time to avoid initial collisions
// MAC uses external random generator to get stochastic radio behaviour
etimer_set(&send_timer, rand() % 20);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&send_timer));
retryCounter = 0;
while (simEtherBusy && retryCounter < 5) {
retryCounter++;
// Wait some random time hoping ether will free
// MAC uses external random generator to get stochastic radio behaviour
etimer_set(&send_timer, rand() % 20);
PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&send_timer));
}
if (simEtherBusy) {
log_message("MAC layer skipping packet", "");
} else {
// Tell COOJA about our new packet
simSentPacket = 1;
}
}
}
PROCESS_END();
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
// Handle incoming network packets if any
if (simReceivedPacket) {
// If hardware is turned off, just remove packet
if (!simRadioHWOn) {
simReceivedPacket = 0;
simReceivedPacketSize = 0;
return;
}
// Reset flag
simReceivedPacket = 0;
if (simReceivedPacketSize == 0) {
fprintf(stderr, "simReceivedPacketSize == 0: Didn't I receive a packet?\n");
return;
}
// Copy incoming data to correct buffers and call handling routines
uip_len = simReceivedPacketSize;
if(uip_len > UIP_BUFSIZE) {
fprintf(stderr, "doInterfaceActionsBeforeTick>> uip_len too large - dropping\n");
uip_len = 0;
} else {
memcpy(&uip_buf[UIP_LLH_LEN], &simReceivedPacketData[0], simReceivedPacketSize);
simReceivedPacketSize = 0;
// Handle new packet
tcpip_input();
}
}
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
// Nothing to do
}
/*-----------------------------------------------------------------------------------*/
u8_t
simDoSend(void)
{
// If hardware is turned off, just remove packet
if (!simRadioHWOn) {
// Should we reset uip_len if radio is off?
uip_len = 0;
return UIP_FW_DROPPED;
}
// If outgoing data, but too large, drop it
if(uip_len > UIP_BUFSIZE) {
fprintf(stderr, "simDoSend>> uip_len too large - dropping\n");
uip_len = 0;
return UIP_FW_TOOLARGE;
}
// If outgoing data, back it up, and wake ether process
if (uip_len > 0) {
// Backup packet data/size
memcpy(&simSentPacketData[0], &uip_buf[UIP_LLH_LEN], uip_len);
simSentPacketSize = uip_len;
process_poll(&ether_process);
return UIP_FW_OK;
}
return UIP_FW_ZEROLEN;
}
/*-----------------------------------------------------------------------------------*/
/**
* \brief Turn radio on.
*
* This function turns the radio hardware on.
*/
void
radio_on(void) {
simRadioHWOn = 1;
}
/*-----------------------------------------------------------------------------------*/
/**
* \brief Turn radio off.
*
* This function turns the radio hardware off.
*/
void radio_off(void) {
simRadioHWOn = 0;
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(radio_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

View file

@ -0,0 +1,41 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: radio-arch.h,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#ifndef __RADIO_ARCH_H__
#define __RADIO_ARCH_H__
#include "contiki.h"
#include "net/uip.h"
PROCESS_NAME(ether_process);
u8_t simDoSend(void);
#endif /* __RADIO_ARCH_H__ */

109
platform/cooja/dev/rs232.c Normal file
View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: rs232.c,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
#include "lib/sensors.h"
#include "dev/rs232.h"
#include "dev/serial.h"
#include "lib/simEnvChange.h"
#include <string.h>
#include <stdio.h>
const struct simInterface rs232_interface;
#define SERIAL_BUF_SIZE 1024
// COOJA variables
char simSerialReceivingData[SERIAL_BUF_SIZE];
int simSerialReceivingLength;
char simSerialReceivingFlag;
char simSerialSendingData[SERIAL_BUF_SIZE];
int simSerialSendingLength;
char simSerialSendingFlag;
static int (* input_handler)(unsigned char) = NULL;
/*-----------------------------------------------------------------------------------*/
void rs232_init(void) { }
/*-----------------------------------------------------------------------------------*/
void rs232_set_speed(unsigned char speed) { }
/*-----------------------------------------------------------------------------------*/
void
rs232_set_input(int (*f)(unsigned char))
{
input_handler = f;
}
/*-----------------------------------------------------------------------------------*/
void rs232_send(char c) {
simSerialSendingData[simSerialSendingLength] = c;
simSerialSendingLength += 1;
simSerialSendingFlag = 1;
}
/*-----------------------------------------------------------------------------------*/
void
rs232_print(char *message)
{
memcpy(&simSerialSendingData[0] + simSerialSendingLength, &message[0], strlen(message));
simSerialSendingLength += strlen(message);
simSerialSendingFlag = 1;
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
int i;
// Check if this mote has received data on RS232
if (simSerialReceivingFlag && simSerialReceivingLength > 0) {
// Tell user specified poll function
if(input_handler != NULL)
for (i=0; i < simSerialReceivingLength; i++)
input_handler(simSerialReceivingData[i]);
// Tell serial process
for (i=0; i < simSerialReceivingLength; i++)
serial_input_byte(simSerialReceivingData[i]);
serial_input_byte(0x0a);
simSerialReceivingLength = 0;
simSerialReceivingFlag = 0;
}
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(rs232_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

118
platform/cooja/dev/rs232.h Normal file
View file

@ -0,0 +1,118 @@
/*
* Copyright (c) 2005, Swedish Institute of Computer Science
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Contiki operating system.
*
* @(#)$Id: rs232.h,v 1.1 2006/08/21 12:11:19 fros4943 Exp $
*/
/** \addtogroup esb
* @{ */
/**
* \defgroup esbrs232 ESB RS232
*
* @{
*/
/**
* \file
* Header file for MSP430 RS232 driver.
* \author Adam Dunkels <adam@sics.se>
*
*/
#ifndef __RS232_H__
#define __RS232_H__
#define RS232_19200 1
#define RS232_38400 2
#define RS232_57600 3
#define RS232_115200 4
/**
* \brief Initialize the RS232 module
*
* This function is called from the boot up code to
* initalize the RS232 module.
*/
void rs232_init(void);
/**
* \brief Set an input handler for incoming RS232 data
* \param f A pointer to a byte input handler
*
* This function sets the input handler for incoming RS232
* data. The input handler function is called for every
* incoming data byte. The function is called from the
* RS232 interrupt handler, so care must be taken when
* implementing the input handler to avoid race
* conditions.
*
* The return value of the input handler affects the sleep
* mode of the CPU: if the input handler returns non-zero
* (true), the CPU is awakened to let other processing
* take place. If the input handler returns zero, the CPU
* is kept sleeping.
*/
void rs232_set_input(int (* f)(unsigned char));
/**
* \brief Configure the speed of the RS232 hardware
* \param speed The speed
*
* This function configures the speed of the RS232
* hardware. The allowed parameters are RS232_19200,
* RS232_38400, RS232_57600, and RS232_115200.
*/
void rs232_set_speed(unsigned char speed);
/**
* \brief Print a text string on RS232
* \param str A pointer to the string that is to be printed
*
* This function prints a string to RS232. The string must
* be terminated by a null byte. The RS232 module must be
* correctly initalized and configured for this function
* to work.
*/
void rs232_print(char *text);
/**
* \brief Print a character on RS232
* \param c The character to be printed
*
* This function prints a character to RS232. The RS232
* module must be correctly initalized and configured for
* this function to work.
*/
void rs232_send(char c);
#endif /* __RS232_H__ */
/** @} */ /** @} */

View file

@ -0,0 +1,117 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: vib-sensor.c,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#include "lib/sensors.h"
#include "dev/vib-sensor.h"
#include "lib/simEnvChange.h"
const struct simInterface vib_interface;
const struct sensors_sensor vib_sensor;
// COOJA variables
char simVibChanged;
char simVibIsActive;
char simVibValue = 0;
/*---------------------------------------------------------------------------*/
static void
init(void)
{
simVibIsActive = 1;
}
/*---------------------------------------------------------------------------*/
static int
irq(void)
{
return 0;
}
/*---------------------------------------------------------------------------*/
static void
activate(void)
{
simVibIsActive = 1;
}
/*---------------------------------------------------------------------------*/
static void
deactivate(void)
{
simVibIsActive = 0;
}
/*---------------------------------------------------------------------------*/
static int
active(void)
{
return simVibIsActive;
}
/*---------------------------------------------------------------------------*/
static unsigned int
value(int type)
{
return simVibValue;
}
/*---------------------------------------------------------------------------*/
static int
configure(int type, void *c)
{
return 0;
}
/*---------------------------------------------------------------------------*/
static void *
status(int type)
{
return NULL;
}
/*---------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
// Check if Vib value has changed
if (simVibIsActive && simVibChanged) {
simVibValue = !simVibValue;
sensors_changed(&vib_sensor);
simVibChanged = 0;
}
}
/*---------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*---------------------------------------------------------------------------*/
SIM_INTERFACE(vib_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);
SENSORS_SENSOR(vib_sensor, VIB_SENSOR,
init, irq, activate, deactivate, active,
value, configure, status);

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: vib-sensor.h,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#ifndef __VIB_H__
#define __VIB_H__
extern const struct sensors_sensor vib_sensor;
#define VIB_SENSOR "Vibration sensor"
#endif /* __VIB_H__ */

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: simEnvChange.c,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
#include <stdio.h>
#include <string.h>
#include "lib/simEnvChange.h"
// All registered interfaces
extern const struct simInterface *simInterfaces[];
int simProcessRunValue;
int simEtimerPending;
int simNextExpirationTime;
void doActionsBeforeTick() {
// Poll all interfaces to do their thing before the tick
int i;
for(i = 0; simInterfaces[i] != NULL; ++i) {
simInterfaces[i]->doActionsBeforeTick();
}
}
void doActionsAfterTick() {
// Poll all interfaces to do their thing after the tick
int i;
for(i = 0; simInterfaces[i] != NULL; ++i) {
simInterfaces[i]->doActionsAfterTick();
}
}

View file

@ -0,0 +1,62 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: simEnvChange.h,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
#ifndef __SIMENVCHANGE_H__
#define __SIMENVCHANGE_H__
// Simulation interface structure
struct simInterface {
void (* doActionsBeforeTick) (void);
void (* doActionsAfterTick) (void);
};
// Variable for keeping the last process_run() return value
extern int simProcessRunValue;
extern int simEtimerPending;
extern int simNextExpirationTime;
// Definition for registering an interface
#define SIM_INTERFACE(name, doActionsBeforeTick, doActionsAfterTick) \
const struct simInterface name = { doActionsBeforeTick, doActionsAfterTick }
// Definition for getting access to simulation interface
#define SIM_INTERFACE_NAME(name) \
extern const struct simInterface name
// Definition for creating all interface (from main file)
#define SIM_INTERFACES(...) \
const struct simInterface *simInterfaces[] = {__VA_ARGS__, NULL};
// Functions which polls all interfaces
void doActionsBeforeTick();
void doActionsAfterTick();
#endif /* __SIMENVCHANGE_H__ */

49
platform/cooja/node-id.h Normal file
View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2005, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* This file is part of the Configurable Sensor Network Application
* Architecture for sensor nodes running the Contiki operating system.
*
* $Id: node-id.h,v 1.1 2006/08/21 12:11:16 fros4943 Exp $
*
* -----------------------------------------------------------------
*
* Author : Adam Dunkels, Joakim Eriksson, Niclas Finne
* Created : 2005-12-09
* Updated : $Date: 2006/08/21 12:11:16 $
* $Revision: 1.1 $
*/
#ifndef __NODE_ID_H__
#define __NODE_ID_H__
#include "dev/moteid.h"
#define node_id simMoteID
#endif /* __NODE_ID_H__ */

View file

@ -0,0 +1,70 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: clock.c,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
#include "sys/clock.h"
#include "lib/simEnvChange.h"
const struct simInterface clock_interface;
// COOJA variables
clock_time_t simCurrentTime;
/*-----------------------------------------------------------------------------------*/
void
clock_init(void)
{
}
/*-----------------------------------------------------------------------------------*/
clock_time_t
clock_time(void)
{
return simCurrentTime;
}
/*-----------------------------------------------------------------------------------*/
void
clock_delay(unsigned int delay_time)
{
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(clock_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

74
platform/cooja/sys/log.c Normal file
View file

@ -0,0 +1,74 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: log.c,v 1.1 2006/08/21 12:11:20 fros4943 Exp $
*/
#include "sys/log.h"
#include "lib/simEnvChange.h"
#include <string.h>
const struct simInterface simlog_interface;
// COOJA variables
char simLoggedData[1024];
int simLoggedLength;
char simLoggedFlag;
void simlog(const char *message);
/*-----------------------------------------------------------------------------------*/
void
log_message(const char *part1, const char *part2)
{
simlog(part1);
simlog(part2);
}
/*-----------------------------------------------------------------------------------*/
void
simlog(const char *message)
{
memcpy(&simLoggedData[0] + simLoggedLength, &message[0], strlen(message));
simLoggedLength += strlen(message);
simLoggedFlag = 1;
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
}
/*-----------------------------------------------------------------------------------*/
SIM_INTERFACE(simlog_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

View file

@ -0,0 +1,72 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: testbutton.c,v 1.1 2006/08/21 12:11:16 fros4943 Exp $
*/
#include "contiki.h"
#include "sys/loader.h"
#include <stdio.h>
#include "lib/list.h"
#include "lib/random.h"
#include "net/uip.h"
#include "lib/sensors.h"
#include "sys/log.h"
#include "dev/button-sensor.h"
PROCESS(button_process, "Button test process");
PROCESS_THREAD(button_process, ev, data)
{
static int custom_counter = 0;
static char logMess[100];
PROCESS_BEGIN();
sprintf(logMess, "Starting Button test process (counter=%i)\n", custom_counter);
log_message(logMess, "");
while(1) {
PROCESS_WAIT_EVENT();
if (button_sensor.value(0)) {
custom_counter++;
sprintf(logMess, "button> Button pressed (counter=%i)\n", custom_counter);
log_message(logMess, "");
}
}
PROCESS_END();
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: testbutton.h,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#ifndef __BUTTON_TEST_H__
#define __BUTTON_TEST_H__
#include "contiki.h"
PROCESS_NAME(button_test_process);
#endif /* __BUTTON_TEST_H__ */

View file

@ -0,0 +1,78 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: testetimer.c,v 1.1 2006/08/21 12:11:17 fros4943 Exp $
*/
#include <stdio.h>
#include "contiki.h"
#include "sys/loader.h"
#include "lib/list.h"
#include "lib/random.h"
#include "net/uip.h"
#include "sys/etimer.h"
#include "sys/clock.h"
#include "lib/sensors.h"
#include "sys/log.h"
PROCESS(etimer_test_process, "ETimer test process");
PROCESS_THREAD(etimer_test_process, ev, data)
{
static struct etimer mytimer;
static int custom_counter = 0;
static char logMess[100];
PROCESS_BEGIN();
etimer_set(&mytimer, 1111);
sprintf(logMess, "Starting ETimer test process (counter=%i)\n", custom_counter);
log_message(logMess, "");
while(1) {
PROCESS_WAIT_EVENT();
if (etimer_expired(&mytimer)) {
custom_counter++;
sprintf(logMess, "etimer> Timed out(counter=%i)\n", custom_counter);
log_message(logMess, "");
etimer_restart(&mytimer);
}
}
PROCESS_END();
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: testetimer.h,v 1.1 2006/08/21 12:11:17 fros4943 Exp $
*/
#ifndef __ETIMER_TEST_H__
#define __ETIMER_TEST_H__
#include "contiki.h"
PROCESS_NAME(etimer_test_process);
#endif /* __ETIMER_TEST_H__ */

View file

@ -0,0 +1,81 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: testserial.c,v 1.1 2006/08/21 12:11:16 fros4943 Exp $
*/
#include "contiki.h"
#include "sys/loader.h"
#include <stdio.h>
#include "lib/list.h"
#include "lib/random.h"
#include "net/uip.h"
#include "lib/sensors.h"
#include "sys/log.h"
#include "dev/serial.h"
#include "dev/rs232.h"
PROCESS(serial_test_process, "Serial test process");
AUTOSTART_PROCESSES(&serial_test_process);
PROCESS_THREAD(serial_test_process, ev, data)
{
static struct etimer mytimer;
PROCESS_BEGIN();
etimer_set(&mytimer, CLOCK_SECOND);
/* Starts the serial process among other */
serial_init();
log_message("serial> Starting test process\n", "");
while(1) {
PROCESS_WAIT_EVENT();
if (etimer_expired(&mytimer)) {
log_message("serial> Sending serial data now\n", "");
etimer_restart(&mytimer);
rs232_print("GNU's not Unix\n");
}
if(ev == serial_event_message) {
log_message("serial> Message received: ", data);
}
}
PROCESS_END();
}

View file

@ -0,0 +1,39 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: testserial.h,v 1.1 2006/08/21 12:11:18 fros4943 Exp $
*/
#ifndef __BUTTON_TEST_H__
#define __BUTTON_TEST_H__
#include "contiki.h"
PROCESS_NAME(button_test_process);
#endif /* __BUTTON_TEST_H__ */

88
tools/cooja/build.xml Normal file
View file

@ -0,0 +1,88 @@
<?xml version="1.0"?>
<project name="COOJA Simulator" default="help" basedir=".">
<property name="java" location="java"/>
<property name="build" location="build"/>
<property name="javadoc" location="javadoc"/>
<property name="config" location="config"/>
<property name="dist" location="dist"/>
<property name="lib" location="lib"/>
<property name="args" value="" />
<target name="help">
<echo>
The COOJA Simulator
> ant run
Starts COOJA simulator
</echo>
</target>
<target name="init">
<tstamp/>
</target>
<target name="javadoc" depends="init">
<delete dir="${javadoc}" quiet="true"/>
<mkdir dir="${javadoc}/"/>
<javadoc destdir="${javadoc}">
<fileset dir="${java}/" includes="**/*.java"/>
<classpath>
<pathelement location="lib/jdom.jar"/>
<pathelement location="lib/log4j.jar"/>
</classpath>
</javadoc>
</target>
<target name="compile" depends="init">
<mkdir dir="${build}"/>
<javac srcdir="${java}" destdir="${build}">
<classpath>
<pathelement path="."/>
<pathelement location="lib/jdom.jar"/>
<pathelement location="lib/log4j.jar"/>
</classpath>
</javac>
</target>
<target name="copy configs" depends="init">
<mkdir dir="${build}"/>
<copy todir="${build}">
<fileset dir="${config}"/>
</copy>
</target>
<target name="clean" depends="init">
<delete dir="${build}"/>
<delete dir="${dist}"/>
</target>
<target name="run" depends="init, compile, copy configs">
<java fork="yes" dir="${build}" classname="se.sics.cooja.GUI">
<arg line="${args}"/>
<env key="LD_LIBRARY_PATH" value="."/>
<classpath>
<pathelement path="${build}"/>
<pathelement location="lib/jdom.jar"/>
<pathelement location="lib/log4j.jar"/>
</classpath>
</java>
</target>
<target name="jar" depends="clean, init, compile, copy configs">
<mkdir dir="${dist}"/>
<jar destfile="${dist}/cooja.jar" basedir="${build}">
<fileset dir="${build}"/>
<manifest>
<attribute name="Main-Class" value="se.sics.cooja.GUI"/>
<attribute name="Class-Path" value=". lib/log4j.jar lib/jdom.jar"/>
</manifest>
</jar>
<mkdir dir="${dist}/lib"/>
<copy todir="${dist}/lib">
<fileset dir="${lib}"/>
</copy>
</target>
</project>

View file

@ -0,0 +1,219 @@
/**
* \defgroup coojacore COOJA Simulator Core
* @{
*/
/**
* \file
* C code template for generating contiki source code files from COOJA
* Simulator. This file should not be compiled directly.
* \author
* Fredrik Osterlind <fros@sics.se>
*/
/*---------------------------------------------------------------------------*/
/**
* \page coojacore COOJA Simulator Core
*
* COOJA Simulator Core ("the Core") represents the entire C code part of COOJA
* Simulator.
* This part shortly consists of simulated sensors and actuators and code for
* communicating with the Java part.
*
* Communication with the Core should always be handled via dedicated classes
* (MoteType), and never directly. MoteType works as an interface giving access
* to variable's values given their name (through CoreComm->Lib?).
*
*/
#include <jni.h>
#include <stdio.h>
#include <string.h>
#include "contiki.h"
#include "contiki-net.h"
#include "contiki-lib.h"
#include "contiki-conf.h"
#include "sys/clock.h"
#include "lib/simEnvChange.h"
#include "lib/sensors.h"
#include "net/uip.h"
#include "dev/radio-arch.h"
#include "sys/etimer.h"
/* Declare all initialization processes */
[PROCESS_DEFINITIONS]
/* Declare all sensors */
[SENSOR_DEFINITIONS]
/* Declare all simulation interfaces */
[INTERFACE_DEFINITIONS]
/* Create initialization process array */
[PROCESS_ARRAY]
/* Create sensor array */
[SENSOR_ARRAY]
/* Create simulation interfaces array */
[INTERFACE_ARRAY]
// Default network interface
static struct uip_fw_netif simNetworkIF =
{UIP_FW_NETIF(0,0,0,0, 0,0,0,0, simDoSend)};
/*
* referenceVar is used for comparing absolute and process relative memory.
* (this must not be static due to memory locations)
*/
int referenceVar;
extern unsigned long _end;
/*---------------------------------------------------------------------------*/
/**
* \brief Initialize a mote by starting processes etc.
*
* This function initializes a mote by starting certain
* processes and setting up the environment.
*
* This is a JNI function and should only be called via the
* responsible Java part (MoteType.java).
*/
JNIEXPORT void JNICALL
Java_se_sics_cooja_corecomm_[CLASS_NAME]_init(JNIEnv *env, jobject obj)
{
/* Initialize random generator */
random_init(0);
/* Start process handler */
process_init();
/* Start Contiki processes */
procinit_init();
/* Initialize uIP */
uip_init();
uip_fw_init();
/* Register network interface */
uip_fw_default(&simNetworkIF);
/* Start user applications */
autostart_start((struct process **) autostart_processes);
}
/*---------------------------------------------------------------------------*/
/**
* \brief Get a segment from the process memory.
* \param start Start address of segment
* \param length Size of memory segment
* \return Java byte array containing a copy of memory segment.
*
* Fetches a memory segment from the process memory starting at
* (start), with size (length). This function does not perform
* ANY error checking, and the process may crash if addresses are
* not available/readable.
*
* This is a JNI function and should only be called via the
* responsible Java part (MoteType.java).
*/
JNIEXPORT jbyteArray JNICALL
Java_se_sics_cooja_corecomm_[CLASS_NAME]_getMemory(JNIEnv *env, jobject obj, jint start, jint length)
{
jbyteArray ret=(*env)->NewByteArray(env, length);
(*env)->SetByteArrayRegion(env, ret, 0, (size_t) length, (jbyte *) start);
return (ret);
}
/*---------------------------------------------------------------------------*/
/**
* \brief Replace a segment of the process memory with given byte array.
* \param start Start address of segment
* \param length Size of memory segment
* \param mem_arr Byte array contaning new memory
*
* Replaces a process memory segment with given byte array.
* This function does not perform ANY error checking, and the
* process may crash if addresses are not available/writable.
*
* This is a JNI function and should only be called via the
* responsible Java part (MoteType.java).
*/
JNIEXPORT void JNICALL
Java_se_sics_cooja_corecomm_[CLASS_NAME]_setMemory(JNIEnv *env, jobject obj, jint start, jint length, jbyteArray mem_arr)
{
jbyte *mem = (*env)->GetByteArrayElements(env, mem_arr, 0);
memcpy((void *) start, mem, length);
(*env)->ReleaseByteArrayElements(env, mem_arr, mem, 0);
}
/*---------------------------------------------------------------------------*/
/**
* \brief Let mote execute one "block" of code (tick mote).
*
* Let mote defined by the active contiki processes and current
* process memory execute some program code. This code must not block
* or else this function will never return. A typical contiki
* process will return when it executes PROCESS_WAIT..() statements.
*
* Before the control is left to contiki processes, any messages
* from the Java part are handled. These may for example be
* incoming network data. After the contiki processes return control,
* messages to the Java part are also handled (those which may need
* special attention).
*
* This is a JNI function and should only be called via the
* responsible Java part (MoteType.java).
*/
JNIEXPORT void JNICALL
Java_se_sics_cooja_corecomm_[CLASS_NAME]_tick(JNIEnv *env, jobject obj)
{
/* Let all simulation interfaces act first */
doActionsBeforeTick();
/* Check if any e-timers are pending (save result for state decisions) */
if (etimer_pending()) {
/* Poll etimers */
etimer_request_poll();
simEtimerPending = 1;
} else {
simEtimerPending = 0;
}
/* Execute the contiki code (save process_run return value for state decisions) */
simProcessRunValue = process_run();
/* Let all simulation interfaces act before returning to java */
doActionsAfterTick();
/* Look for new e-timers */
if (!simEtimerPending && etimer_pending()) {
/* Poll etimers */
etimer_request_poll();
simEtimerPending = 1;
}
/* Save nearest event timer expiration time (0 if no timers) */
simNextExpirationTime = etimer_next_expiration_time();
}
/*---------------------------------------------------------------------------*/
/**
* \brief Get the absolute memory address of a special variable.
* \return Absolute memory address.
*
* Returns the absolute memory address of a special variable
* "referenceVar". By comparing this address with the relative
* address (from the map file) for referenceVar, an runtime offset
* can be calculated.
*
* This is a JNI function and should only be called via the
* responsible Java part (MoteType.java).
*/
JNIEXPORT jint JNICALL
Java_se_sics_cooja_corecomm_[CLASS_NAME]_getReferenceAbsAddr(JNIEnv *env, jobject obj)
{
return (jint) &referenceVar;
}
/** @} */

View file

@ -0,0 +1,34 @@
se.sics.cooja.interfaces.Battery.INFINITE_ENERGY_bool = false
se.sics.cooja.interfaces.Battery.INITIAL_ENERGY_mQ = 13500000
se.sics.cooja.interfaces.Battery.CPU_AWAKE_mA = 1.49
se.sics.cooja.interfaces.Battery.CPU_LPM_mA = 1.34
se.sics.cooja.contikimote.interfaces.ContikiRS232.CONSUMPTION_PER_CHAR_mQ = 1
se.sics.cooja.contikimote.interfaces.ContikiRS232.EXTERNAL_INTERRUPT_bool = true
se.sics.cooja.contikimote.interfaces.ContikiLED.GREEN_LED_CONSUMPTION_mA = 5.69
se.sics.cooja.contikimote.interfaces.ContikiLED.YELLOW_LED_CONSUMPTION_mA = 5.69
se.sics.cooja.contikimote.interfaces.ContikiLED.RED_LED_CONSUMPTION_mA = 5.69
se.sics.cooja.contikimote.interfaces.ContikiButton.EXTERNAL_INTERRUPT_bool = true
se.sics.cooja.contikimote.interfaces.ContikiBeeper.BEEP_CONSUMPTION_mQ = 1.669
se.sics.cooja.contikimote.interfaces.ContikiPIR.ACTIVE_CONSUMPTION_mA = 0.4
se.sics.cooja.contikimote.interfaces.ContikiPIR.EXTERNAL_INTERRUPT_bool = true
se.sics.cooja.contikimote.interfaces.ContikiRadio.ACTIVE_CONSUMPTION_mA = 5
se.sics.cooja.contikimote.interfaces.ContikiRadio.EXTERNAL_INTERRUPT_bool = true
se.sics.cooja.contikimote.interfaces.ContikiVib.ACTIVE_CONSUMPTION_mA = 1.58
se.sics.cooja.contikimote.interfaces.ContikiVib.EXTERNAL_INTERRUPT_bool = true
se.sics.cooja.contikimote.ContikiMoteType.MOTE_INTERFACES = se.sics.cooja.interfaces.Position se.sics.cooja.interfaces.Battery se.sics.cooja.contikimote.interfaces.ContikiVib se.sics.cooja.contikimote.interfaces.ContikiMoteID se.sics.cooja.contikimote.interfaces.ContikiRS232 se.sics.cooja.contikimote.interfaces.ContikiBeeper se.sics.cooja.contikimote.interfaces.ContikiIPAddress se.sics.cooja.contikimote.interfaces.ContikiRadio se.sics.cooja.contikimote.interfaces.ContikiButton se.sics.cooja.contikimote.interfaces.ContikiPIR se.sics.cooja.contikimote.interfaces.ContikiClock se.sics.cooja.contikimote.interfaces.ContikiLED se.sics.cooja.contikimote.interfaces.ContikiLog
se.sics.cooja.contikimote.ContikiMoteType.C_SOURCES =
se.sics.cooja.GUI.MOTETYPES = se.sics.cooja.contikimote.ContikiMoteType se.sics.cooja.motes.DummyMoteType
se.sics.cooja.GUI.PLUGINS = se.sics.cooja.plugins.VisState se.sics.cooja.plugins.VisBattery se.sics.cooja.plugins.VisTraffic se.sics.cooja.plugins.LogListener se.sics.cooja.plugins.MoteInformation se.sics.cooja.plugins.MoteInterfaceViewer se.sics.cooja.plugins.VariableWatcher
se.sics.cooja.GUI.IP_DISTRIBUTORS = se.sics.cooja.ipdistributors.RandomIPDistributor se.sics.cooja.ipdistributors.SpatialIPDistributor se.sics.cooja.ipdistributors.IdIPDistributor
se.sics.cooja.GUI.POSITIONERS = se.sics.cooja.positioners.RandomPositioner se.sics.cooja.positioners.LinearPositioner se.sics.cooja.positioners.EllipsePositioner
se.sics.cooja.GUI.RADIOMEDIUMS = se.sics.cooja.radiomediums.StandardRadioMedium se.sics.cooja.radiomediums.SilentRadioMedium

View file

@ -0,0 +1,17 @@
PATH_CONTIKI = ../../..
PATH_COOJA_CORE_RELATIVE = /platform/cooja
PATH_MAKE = make
PATH_LINKER = ld
PATH_SHELL = sh
PATH_C_COMPILER = gcc
CMD_GREP_PROCESSES = grep "^PROCESS_THREAD([^,]*,[^,]*,[^)]*)" -o -H
REGEXP_PARSE_PROCESSES = ([^/]*.c):PROCESS_THREAD\\(([^,]*),[^,]*,[^)]*\\)
CMD_GREP_INTERFACES = grep "^SIM_INTERFACE([^,]*," -o -d skip -D skip -H -r
REGEXP_PARSE_INTERFACES = ([^/]*.c):SIM_INTERFACE\\(([^,]*),
CMD_GREP_SENSORS = grep "^SENSORS_SENSOR([^,]*," -o -d skip -D skip -H -r
REGEXP_PARSE_SENSORS = ([^/]*.c):SENSORS_SENSOR\\(([^,]*),
LINKER_ARGS_1 =
LINKER_ARGS_2 =
COMPILER_ARGS =
CONTIKI_STANDARD_PROCESSES = sensors_process;etimer_process;tcpip_process;ether_process;uip_fw_process
CONTIKI_MAIN_TEMPLATE_FILENAME = code_main_template

View file

@ -0,0 +1,17 @@
PATH_CONTIKI = ../../..
PATH_COOJA_CORE_RELATIVE = /platform/cooja
PATH_MAKE = make
PATH_LINKER = ld
PATH_SHELL = sh
PATH_C_COMPILER = gcc
CMD_GREP_PROCESSES = grep '^PROCESS_THREAD([^,]*,[^,]*,[^)]*)' -o -d skip -D skip -H -r
REGEXP_PARSE_PROCESSES = ([^/]*.c):PROCESS_THREAD\\(([^,]*),[^,]*,[^)]*\\)
CMD_GREP_INTERFACES = grep '^SIM_INTERFACE([^,]*,' -o -d skip -D skip -H -r
REGEXP_PARSE_INTERFACES = ([^/]*.c):SIM_INTERFACE\\(([^,]*),
CMD_GREP_SENSORS = grep '^SENSORS_SENSOR([^,]*,' -o -d skip -D skip -H -r
REGEXP_PARSE_SENSORS = ([^/]*.c):SENSORS_SENSOR\\(([^,]*),
LINKER_ARGS_1 = --add-stdcall-alias /usr/lib/mingw/dllcrt2.o
LINKER_ARGS_2 = -L/usr/lib/mingw -lmingw32 -lmingwex -lmsvcrt
COMPILER_ARGS = -mno-cygwin -I'C:/Program Files/Java/jdk1.5.0_06/include' -I'C:/Program Files/Java/jdk1.5.0_06/include/win32'
CONTIKI_STANDARD_PROCESSES = sensors_process;etimer_process;tcpip_process;ether_process;uip_fw_process
CONTIKI_MAIN_TEMPLATE_FILENAME = code_main_template

View file

@ -0,0 +1,25 @@
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="logfile" class="org.apache.log4j.FileAppender">
<param name="File" value="COOJA.log"/>
<param name="Append" value="false"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="[%d{HH:mm:ss} - %t] [%F:%L] [%p] - %m%n"/>
</layout>
</appender>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%5p [%t] (%F:%L) - %m%n"/>
</layout>
</appender>
<root>
<priority value="debug"/>
<appender-ref ref="logfile"/>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>

View file

@ -0,0 +1,153 @@
<?xml version="1.0"?>
<project name="COOJA Simulator - JNI Tests" default="about" basedir=".">
<!-- Properties used inside the COOJA Simulator -->
<property name="PATH_C_COMPILER" value="gcc"/>
<property name="COMPILER_ARGS" value=""/>
<property name="PATH_LINKER" value="ld"/>
<property name="LINKER_ARGS_1" value=""/>
<property name="LINKER_ARGS_2" value=""/>
<target name="help">
<echo>
Win32 cygwin users may try:
COMPILER_ARGS= -mno-cygwin -I....../jdk1.5.0/include -I....../jdk1.5.0/include/win32
LINKER_ARGS_1 = --add-stdcall-alias /usr/lib/mingw/dllcrt2.o
LINKER_ARGS_2 = -L/usr/lib/mingw -lmingw32 -lmingwex -lmsvcrt
Only for level 1, try the following compiler arguments:
COMPILER_ARGS= -mno-cygwin -I....../jdk1.5.0/include -I....../jdk1.5.0/include/win32 -Wl,--add-stdcall
</echo>
</target>
<target name="about">
<echo>
The COOJA Simulator - JNI Tests
There examples may help understand errors during compilation from inside COOJA.
For some examples; "ant help".
ant level1
Runs JNI test level 1:
[compilation test]
Compiles level1.c to level1.library, using only c compiler.
Java class loads the library and calls a simple native function.
ant level2
Runs JNI test level 2:
[compilation test]
Compiles level2.c to level2.library, using both c compiler and linker.
Java class loads the library and calls a simple native function.
ant level3
Runs JNI test level 3:
[map file parsing test]
Compiles java + c.
The map file is parsed, and information about data+bss sections is outputted.
ant level4
Runs JNI test level 4:
[fetching reference var]
Calculates offset between relative (mapfile) and absolute memory.
A simple native function increases two counters (from both data and bss sections).
ant level5
Runs JNI test level 5:
[fetches and restores memory segments - the final test]
A simple native function increases two counters (from both data and bss sections).
The current memory (data+bss sections) is fetched and restored between function calls.
The counters should be restored with the memory!
</echo>
</target>
<target name="clean">
<delete>
<fileset dir="." includes="**/*.class" />
<fileset dir="." includes="**/*.library" />
<fileset dir="." includes="**/*.o" />
<fileset dir="." includes="**/*.map" />
</delete>
</target>
<target name="init">
<tstamp/>
</target>
<target name="level1_compile_c" depends="init">
<echo message="EXECUTING: ${PATH_C_COMPILER} ${COMPILER_ARGS} -o level1.library -shared level1.c"/>
<exec dir="level1" executable="${PATH_C_COMPILER}" failonerror="true">
<arg line="${COMPILER_ARGS} -o level1.library -shared level1.c"/>
</exec>
</target>
<target name="level1" depends="init, level1_compile_c">
<javac srcdir="level1" destdir="level1"/>
<java fork="yes" dir="level1" classname="Level1"/>
</target>
<target name="level2_compile_c" depends="init">
<echo message="EXECUTING: ${PATH_C_COMPILER} ${COMPILER_ARGS} -c -o level2.o -shared level2.c"/>
<exec dir="level2" executable="${PATH_C_COMPILER}" failonerror="true">
<arg line="${COMPILER_ARGS} -c -o level2.o -shared level2.c"/>
</exec>
<echo message="EXECUTING: ${PATH_LINKER} -Map=level2.map -shared ${LINKER_ARGS_1} -o level2.library level2.o ${LINKER_ARGS_2}"/>
<exec dir="level2" executable="${PATH_LINKER}" failonerror="true">
<arg line="-Map=level2.map -shared ${LINKER_ARGS_1} -o level2.library level2.o ${LINKER_ARGS_2}"/>
</exec>
</target>
<target name="level2" depends="init, level2_compile_c">
<javac srcdir="level2" destdir="level2"/>
<java fork="yes" dir="level2" classname="Level2"/>
</target>
<target name="level3_compile_c" depends="init">
<echo message="EXECUTING: ${PATH_C_COMPILER} ${COMPILER_ARGS} -c -o level3.o -shared level3.c"/>
<exec dir="level3" executable="${PATH_C_COMPILER}" failonerror="true">
<arg line="${COMPILER_ARGS} -c -o level3.o -shared level3.c"/>
</exec>
<echo message="EXECUTING: ${PATH_LINKER} -Map=level3.map -shared ${LINKER_ARGS_1} -o level3.library level3.o ${LINKER_ARGS_2}"/>
<exec dir="level3" executable="${PATH_LINKER}" failonerror="true">
<arg line="-Map=level3.map -shared ${LINKER_ARGS_1} -o level3.library level3.o ${LINKER_ARGS_2}"/>
</exec>
</target>
<target name="level3" depends="init, level3_compile_c">
<javac srcdir="level3" destdir="level3"/>
<java fork="yes" dir="level3" classname="Level3"/>
</target>
<target name="level4_compile_c" depends="init">
<echo message="EXECUTING: ${PATH_C_COMPILER} ${COMPILER_ARGS} -c -o level4.o -shared level4.c"/>
<exec dir="level4" executable="${PATH_C_COMPILER}" failonerror="true">
<arg line="${COMPILER_ARGS} -c -o level4.o -shared level4.c"/>
</exec>
<echo message="EXECUTING: ${PATH_LINKER} -Map=level4.map -shared ${LINKER_ARGS_1} -o level4.library level4.o ${LINKER_ARGS_2}"/>
<exec dir="level4" executable="${PATH_LINKER}" failonerror="true">
<arg line="-Map=level4.map -shared ${LINKER_ARGS_1} -o level4.library level4.o ${LINKER_ARGS_2}"/>
</exec>
</target>
<target name="level4" depends="init, level4_compile_c">
<javac srcdir="level4" destdir="level4"/>
<java fork="yes" dir="level4" classname="Level4"/>
</target>
<target name="level5_compile_c" depends="init">
<echo message="EXECUTING: ${PATH_C_COMPILER} ${COMPILER_ARGS} -c -o level5.o -shared level5.c"/>
<exec dir="level5" executable="${PATH_C_COMPILER}" failonerror="true">
<arg line="${COMPILER_ARGS} -c -o level5.o -shared level5.c"/>
</exec>
<echo message="EXECUTING: ${PATH_LINKER} -Map=level5.map -shared ${LINKER_ARGS_1} -o level5.library level5.o ${LINKER_ARGS_2}"/>
<exec dir="level5" executable="${PATH_LINKER}" failonerror="true">
<arg line="-Map=level5.map -shared ${LINKER_ARGS_1} -o level5.library level5.o ${LINKER_ARGS_2}"/>
</exec>
</target>
<target name="level5" depends="init, level5_compile_c">
<javac srcdir="level5" destdir="level5"/>
<java fork="yes" dir="level5" classname="Level5"/>
</target>
</project>

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Level1.java,v 1.1 2006/08/21 12:13:06 fros4943 Exp $
*/
import java.io.*;
public class Level1 {
static {
System.err.println("JAVA Level1 static> loading library now");
System.load(new File("level1.library").getAbsolutePath());
System.err.println("JAVA Level1 static> done loading library");
}
private native void test();
public Level1() {
System.err.println("JAVA Level1 constructor()> running native test function");
test();
}
public static void main(String[] args) {
new Level1();
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: level1.c,v 1.1 2006/08/21 12:13:06 fros4943 Exp $
*/
#include <jni.h>
#include <stdio.h>
JNIEXPORT void JNICALL
Java_Level1_test(JNIEnv *env, jobject obj)
{
fprintf(stderr, "C test()> Level 1 OK!\n");
fflush(stderr);
}

View file

@ -0,0 +1,53 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Level2.java,v 1.1 2006/08/21 12:13:00 fros4943 Exp $
*/
import java.io.*;
public class Level2 {
static {
System.err.println("JAVA Level2 static> loading library now");
System.load(new File("level2.library").getAbsolutePath());
System.err.println("JAVA Level2 static> done loading library");
}
private native void test();
public Level2() {
System.err.println("JAVA Level2 constructor()> running native test function");
test();
}
public static void main(String[] args) {
new Level2();
}
}

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: level2.c,v 1.1 2006/08/21 12:13:00 fros4943 Exp $
*/
#include <jni.h>
#include <stdio.h>
JNIEXPORT void JNICALL
Java_Level2_test(JNIEnv *env, jobject obj)
{
fprintf(stderr, "C test()> Level 2 OK!\n");
fflush(stderr);
}

View file

@ -0,0 +1,152 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Level3.java,v 1.1 2006/08/21 12:13:01 fros4943 Exp $
*/
import java.io.*;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Level3 {
final static private String bssSectionAddrRegExp =
"^.bss[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String bssSectionSizeRegExp =
"^.bss[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String dataSectionAddrRegExp =
"^.data[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String dataSectionSizeRegExp =
"^.data[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
static {
System.load(new File("level3.library").getAbsolutePath());
}
private native void test();
public Level3() {
File mapFile = new File("level3.map");
// Check that map file exists
if (!mapFile.exists()) {
System.err.println("No map file could be loaded");
System.exit(1);
}
System.err.println("Loading map file");
Vector<String> mapContents = loadMapFile(mapFile);
System.err.println("Parsing map file");
int relDataSectionAddr = loadRelDataSectionAddr(mapContents);
int dataSectionSize = (int) loadDataSectionSize(mapContents);
int relBssSectionAddr = loadRelBssSectionAddr(mapContents);
int bssSectionSize = (int) loadBssSectionSize(mapContents);
System.err.println("Found relative data section address: 0x" + Integer.toHexString(relDataSectionAddr));
System.err.println("Found data section size: 0x" + Integer.toHexString(dataSectionSize));
System.err.println("Found relative bss section address: 0x" + Integer.toHexString(relBssSectionAddr));
System.err.println("Found bss section address: 0x" + Integer.toHexString(bssSectionSize));
test();
}
private static Vector<String> loadMapFile(File mapFile) {
Vector<String> mapContents = new Vector<String>();
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(
new FileInputStream(mapFile)));
while (in.ready())
{
mapContents.add(in.readLine());
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e);
return null;
} catch (IOException e) {
System.err.println("IO error: " + e);
return null;
}
return mapContents;
}
private static int loadRelDataSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadDataSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadRelBssSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadBssSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static String getFirstMatchGroup(Vector<String> lines, String regexp, int groupNr) {
Pattern pattern = Pattern.compile(regexp);
for (int i=0; i < lines.size(); i++) {
Matcher matcher = pattern.matcher(lines.elementAt(i));
if (matcher.find()) {
return matcher.group(groupNr);
}
}
return null;
}
public static void main(String[] args) {
new Level3();
}
}

View file

@ -0,0 +1,43 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: level3.c,v 1.1 2006/08/21 12:13:01 fros4943 Exp $
*/
#include <jni.h>
#include <stdio.h>
int initialized_counter=1;
int uninitialized_counter;
JNIEXPORT void JNICALL
Java_Level3_test(JNIEnv *env, jobject obj)
{
fprintf(stderr, "C test()> Level 3 OK!\n");
fflush(stderr);
}

View file

@ -0,0 +1,177 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Level4.java,v 1.1 2006/08/21 12:12:59 fros4943 Exp $
*/
import java.io.*;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Level4 {
static {
System.load(new File("level4.library").getAbsolutePath());
}
final static private String bssSectionAddrRegExp =
"^.bss[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String bssSectionSizeRegExp =
"^.bss[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String dataSectionAddrRegExp =
"^.data[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String dataSectionSizeRegExp =
"^.data[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String varAddressRegExpPrefix =
"^[ \t]*0x([0-9A-Fa-f]*)[ \t]*";
final static private String varAddressRegExpSuffix =
"[ \t]*$";
final static private String varNameRegExp =
"^[ \t]*(0x[0-9A-Fa-f]*)[ \t]*([^ ]*)[ \t]*$";
final static private String varSizeRegExpPrefix =
"^";
final static private String varSizeRegExpSuffix =
"[ \t]*(0x[0-9A-Fa-f]*)[ \t]*[^ ]*[ \t]*$";
private native void doCount();
private native int getRefAddress();
public Level4() {
File mapFile = new File("level4.map");
// Check that map file exists
if (!mapFile.exists()) {
System.err.println("No map file could be loaded");
System.exit(1);
}
Vector<String> mapContents = loadMapFile(mapFile);
int relDataSectionAddr = loadRelDataSectionAddr(mapContents);
int dataSectionSize = (int) loadDataSectionSize(mapContents);
int relBssSectionAddr = loadRelBssSectionAddr(mapContents);
int bssSectionSize = (int) loadBssSectionSize(mapContents);
int referenceAddress = getRefAddress();
System.err.println("Reference address: 0x" + Integer.toHexString(referenceAddress));
int offsetRelToAbs = referenceAddress - getRelVarAddr(mapContents, "ref_var");
System.err.println("Offset relative-absolute: 0x" + Integer.toHexString(offsetRelToAbs));
doCount();
doCount();
doCount();
doCount();
doCount();
System.err.println("Level 4 OK!");
}
private static int getRelVarAddr(Vector<String> mapContents, String varName) {
String regExp = varAddressRegExpPrefix + varName + varAddressRegExpSuffix;
String retString = getFirstMatchGroup(mapContents, regExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static Vector<String> loadMapFile(File mapFile) {
Vector<String> mapContents = new Vector<String>();
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(
new FileInputStream(mapFile)));
while (in.ready())
{
mapContents.add(in.readLine());
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e);
return null;
} catch (IOException e) {
System.err.println("IO error: " + e);
return null;
}
return mapContents;
}
private static int loadRelDataSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadDataSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadRelBssSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadBssSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static String getFirstMatchGroup(Vector<String> lines, String regexp, int groupNr) {
Pattern pattern = Pattern.compile(regexp);
for (int i=0; i < lines.size(); i++) {
Matcher matcher = pattern.matcher(lines.elementAt(i));
if (matcher.find()) {
return matcher.group(groupNr);
}
}
return null;
}
public static void main(String[] args) {
new Level4();
}
}

View file

@ -0,0 +1,50 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: level4.c,v 1.1 2006/08/21 12:12:59 fros4943 Exp $
*/
#include <jni.h>
#include <stdio.h>
int ref_var;
int initialized_counter=1;
int uninitialized_counter;
JNIEXPORT void JNICALL
Java_Level4_doCount(JNIEnv *env, jobject obj)
{
fprintf(stderr, ">> DATA_counter=\t%i\tBSS_counter=\t%i\n", initialized_counter++, uninitialized_counter++);
fflush(stderr);
}
JNIEXPORT jint JNICALL
Java_Level4_getRefAddress(JNIEnv *env, jobject obj)
{
return (jint) &ref_var;
}

View file

@ -0,0 +1,205 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Level5.java,v 1.1 2006/08/21 12:13:10 fros4943 Exp $
*/
import java.io.*;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Level5 {
static {
System.load(new File("level5.library").getAbsolutePath());
}
final static private String bssSectionAddrRegExp =
"^.bss[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String bssSectionSizeRegExp =
"^.bss[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String dataSectionAddrRegExp =
"^.data[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String dataSectionSizeRegExp =
"^.data[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String varAddressRegExpPrefix =
"^[ \t]*0x([0-9A-Fa-f]*)[ \t]*";
final static private String varAddressRegExpSuffix =
"[ \t]*$";
final static private String varNameRegExp =
"^[ \t]*(0x[0-9A-Fa-f]*)[ \t]*([^ ]*)[ \t]*$";
final static private String varSizeRegExpPrefix =
"^";
final static private String varSizeRegExpSuffix =
"[ \t]*(0x[0-9A-Fa-f]*)[ \t]*[^ ]*[ \t]*$";
private native void doCount();
private native int getRefAddress();
private native byte[] getMemory(int start, int length);
private native void setMemory(int start, int length, byte[] mem);
public Level5() {
File mapFile = new File("level5.map");
// Check that map file exists
if (!mapFile.exists()) {
System.err.println("No map file could be loaded");
System.exit(1);
}
Vector<String> mapContents = loadMapFile(mapFile);
int relDataSectionAddr = loadRelDataSectionAddr(mapContents);
int dataSectionSize = (int) loadDataSectionSize(mapContents);
int relBssSectionAddr = loadRelBssSectionAddr(mapContents);
int bssSectionSize = (int) loadBssSectionSize(mapContents);
int referenceAddress = getRefAddress();
int offsetRelToAbs = referenceAddress - getRelVarAddr(mapContents, "ref_var");
System.err.println("\n\n--- RUNNING DO_COUNT 5 TIMES ---");
doCount();
doCount();
doCount();
doCount();
doCount();
System.err.println("\n\n--- FETCHING AND SAVING MEMORY ---");
byte[] savedDataSection = getMemory(relDataSectionAddr + offsetRelToAbs, dataSectionSize);
byte[] savedBssSection = getMemory(relBssSectionAddr + offsetRelToAbs, bssSectionSize);
System.err.println("data section size:\t" + savedDataSection.length + " = " + "0x" + Integer.toHexString(savedDataSection.length));
System.err.println("bss section size:\t" + savedBssSection.length + " = " + "0x" + Integer.toHexString(savedBssSection.length));
System.err.println("\n\n--- RUNNING DO_COUNT 3 TIMES ---");
doCount();
doCount();
doCount();
System.err.println("\n\n--- RESTORING MEMORY: DATA ---");
setMemory(relDataSectionAddr + offsetRelToAbs, dataSectionSize, savedDataSection);
System.err.println("\n\n--- RUNNING DO_COUNT 3 TIMES ---");
doCount();
doCount();
doCount();
System.err.println("\n\n--- RESTORING MEMORY: BSS ---");
setMemory(relBssSectionAddr + offsetRelToAbs, bssSectionSize, savedBssSection);
System.err.println("\n\n--- RUNNING DO_COUNT 3 TIMES ---");
doCount();
doCount();
doCount();
System.err.println("Level 5 OK!");
}
private static int getRelVarAddr(Vector<String> mapContents, String varName) {
String regExp = varAddressRegExpPrefix + varName + varAddressRegExpSuffix;
String retString = getFirstMatchGroup(mapContents, regExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static Vector<String> loadMapFile(File mapFile) {
Vector<String> mapContents = new Vector<String>();
try {
BufferedReader in =
new BufferedReader(
new InputStreamReader(
new FileInputStream(mapFile)));
while (in.ready())
{
mapContents.add(in.readLine());
}
} catch (FileNotFoundException e) {
System.err.println("File not found: " + e);
return null;
} catch (IOException e) {
System.err.println("IO error: " + e);
return null;
}
return mapContents;
}
private static int loadRelDataSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadDataSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadRelBssSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static int loadBssSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else return 0;
}
private static String getFirstMatchGroup(Vector<String> lines, String regexp, int groupNr) {
Pattern pattern = Pattern.compile(regexp);
for (int i=0; i < lines.size(); i++) {
Matcher matcher = pattern.matcher(lines.elementAt(i));
if (matcher.find()) {
return matcher.group(groupNr);
}
}
return null;
}
public static void main(String[] args) {
new Level5();
}
}

View file

@ -0,0 +1,68 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: level5.c,v 1.1 2006/08/21 12:13:10 fros4943 Exp $
*/
#include <jni.h>
#include <stdio.h>
#include <string.h>
int ref_var;
int initialized_counter=1;
int uninitialized_counter;
JNIEXPORT void JNICALL
Java_Level5_doCount(JNIEnv *env, jobject obj)
{
fprintf(stderr, ">> DATA_counter=\t%i\tBSS_counter=\t%i\n", initialized_counter++, uninitialized_counter++);
fflush(stderr);
}
JNIEXPORT jint JNICALL
Java_Level5_getRefAddress(JNIEnv *env, jobject obj)
{
return (jint) &ref_var;
}
JNIEXPORT jbyteArray JNICALL
Java_Level5_getMemory(JNIEnv *env, jobject obj, jint start, jint length)
{
jbyteArray ret=(*env)->NewByteArray(env, length);
(*env)->SetByteArrayRegion(env, ret, 0, (size_t) length, (jbyte *) start);
return (ret);
}
JNIEXPORT void JNICALL
Java_Level5_setMemory(JNIEnv *env, jobject obj, jint start, jint length, jbyteArray mem_arr)
{
jbyte *mem = (*env)->GetByteArrayElements(env, mem_arr, 0);
memcpy((void *) start, mem, length);
(*env)->ReleaseByteArrayElements(env, mem_arr, mem, 0);
}

View file

@ -0,0 +1 @@
se.sics.cooja.GUI.PLUGINS = + MoteDebugger

View file

@ -0,0 +1,170 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MoteDebugger.java,v 1.1 2006/08/21 12:13:14 fros4943 Exp $
*/
import java.awt.event.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.*;
import org.apache.log4j.Logger;
import java.io.*;
import java.lang.management.*;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMote;
import se.sics.cooja.contikimote.ContikiMoteType;
/**
* Mote debugger lets a user debug a mote using an external debugger.
*
* It executes the external program 'gdb' and sets up breakpoints
* at the entry of the tick function.
*
* The selected mote is then set to state active and ticked.
*
* OBSERVE! Experimental code. Not fully tested yet!
*
* @author Fredrik Osterlind
*/
@ClassDescription("Debug using GDB")
@VisPluginType(VisPluginType.MOTE_PLUGIN)
public class MoteDebugger extends VisPlugin {;
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(MoteDebugger.class);
private ContikiMote moteToDebug;
/**
* Creates a new VisDebug.
* @param mote Contiki mote to debug next tick
*/
public MoteDebugger(Mote mote) {
super("VisDebug (" + mote + ")");
this.moteToDebug = (ContikiMote) mote;
JButton debugButton = new JButton("Debug now");
debugButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
logger.warn("OBSERVE! This is experimental code");
logger.info("Getting JVM pid");
RuntimeMXBean rt = ManagementFactory.getRuntimeMXBean();
String runtimeName = rt.getName();
int pid = 1;
String pidExtraction = "^([0-9]*)[^$]*$";
Pattern pattern = Pattern.compile(pidExtraction);
Matcher matcher = pattern.matcher(runtimeName);
if (!matcher.find()) {
logger.fatal("Could not determine pid, aborting");
return;
}
pid = Integer.parseInt(matcher.group(1));
if (pid <= 0) {
logger.fatal("Pid seems to be strange, aborting. pid=" + pid);
return;
}
logger.info("Extracted PID=" + pid);
logger.info("Checking that source code file exists..");
File sourceFile = new File("obj_cooja/" + moteToDebug.getType().getIdentifier() + ".c");
if (!sourceFile.exists()) {
logger.fatal("Can't find source file: " + sourceFile);
return;
}
logger.info("Source file ok: " + sourceFile);
logger.info("Determining function name to break at (entry of tick)");
String libName = ((ContikiMoteType) moteToDebug.getType()).getLibraryClassName();
String functionName = "Java." + CoreComm.class.getPackage().getName() + ".corecomm." + libName + ".tick";
functionName = functionName.replaceAll("\\.", "_");
logger.info("Function name is: " + functionName);
logger.info("Creating temporary file .tmp with initial commands");
File tmpFile = new File("obj_cooja/" + ".tmp");
if (tmpFile.exists()) {
tmpFile.delete();
}
try {
BufferedWriter tmpStream = new BufferedWriter(
new OutputStreamWriter(
new FileOutputStream(
tmpFile)));
tmpStream.write("break " + functionName + "\n");
tmpStream.write("cont\n");
tmpStream.close();
} catch (Exception ex) {
logger.fatal("Could not create temporary command file: " + tmpFile);
return;
}
logger.info("Command file created ok: " + tmpFile.getName());
logger.info("Starting external GDB");
logger.info("> GDB must be exited before control is returned to COOJA");
logger.info("> Use command 'quit' followed by y to exit GDB");
Process gdbProcess = null;
try {
gdbProcess = Runtime.getRuntime().exec("xterm -e gdb"
+ " -nw -quiet "
+ " --pid=" + pid
+ " -x " + "obj_cooja/" + tmpFile.getName()
);
logger.info("Sleeping 2500 ms while starting up GDB");
Thread.sleep(2500);
logger.info("Ticking chosen mote now! (setting state to active)");
moteToDebug.setState(Mote.STATE_ACTIVE);
moteToDebug.tick(GUI.currentSimulation.getSimulationTime());
gdbProcess.waitFor();
} catch (Exception ex) {
logger.fatal("Exception while starting gdb, aborting");
}
logger.debug("GDB terminated with exit code: " + gdbProcess.exitValue());
}
});
add(debugButton);
setSize(250, 80);
}
public void closePlugin() {
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: app1.c,v 1.1 2006/08/21 12:13:09 fros4943 Exp $
*/
#include "contiki.h"
#include "sys/loader.h"
#include <stdio.h>
#include "lib/list.h"
#include "lib/random.h"
#include "net/uip.h"
#include "lib/sensors.h"
#include "sys/log.h"
#include "dev/button-sensor.h"
PROCESS(dummy_process_1, "Dummy process 1");
PROCESS_THREAD(dummy_process_1, ev, data)
{
PROCESS_BEGIN();
log_message("Dummy process 1 started", "");
while(1) {
PROCESS_WAIT_EVENT();
log_message("Dummy process 1 received event", "");
}
PROCESS_END();
}

View file

@ -0,0 +1,61 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: app2.c,v 1.1 2006/08/21 12:13:09 fros4943 Exp $
*/
#include "contiki.h"
#include "sys/loader.h"
#include <stdio.h>
#include "lib/list.h"
#include "lib/random.h"
#include "net/uip.h"
#include "lib/sensors.h"
#include "sys/log.h"
#include "dev/button-sensor.h"
PROCESS(dummy_process_2, "Dummy process 2");
PROCESS_THREAD(dummy_process_2, ev, data)
{
PROCESS_BEGIN();
log_message("Dummy process 2 started", "");
while(1) {
PROCESS_WAIT_EVENT();
log_message("Dummy process 2 received event", "");
}
PROCESS_END();
}

View file

@ -0,0 +1 @@
se.sics.cooja.contikimote.ContikiMoteType.C_SOURCES = + app1.c app2.c

View file

@ -0,0 +1,2 @@
se.sics.cooja.contikimote.ContikiMoteType.MOTE_INTERFACES = + DummyInterface
se.sics.cooja.contikimote.ContikiMoteType.C_SOURCES = + dummy_intf.c

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: dummy_intf.c,v 1.1 2006/08/21 12:13:13 fros4943 Exp $
*/
#include "dummy_intf.h"
#include "lib/simEnvChange.h"
#include <stdio.h>
const struct simInterface beep_interface;
// COOJA variables (shared between Java and C)
char simDummyVar;
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsBeforeTick(void)
{
fprintf(stderr, "Core (C) dummy interface acts BEFORE mote tick\n");
}
/*-----------------------------------------------------------------------------------*/
static void
doInterfaceActionsAfterTick(void)
{
fprintf(stderr, "Core (C) dummy interface acts AFTER mote tick\n");
}
/*-----------------------------------------------------------------------------------*/
// Register this as an available interface
SIM_INTERFACE(dummy_interface,
doInterfaceActionsBeforeTick,
doInterfaceActionsAfterTick);

View file

@ -0,0 +1,40 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: dummy_intf.h,v 1.1 2006/08/21 12:13:13 fros4943 Exp $
*/
#ifndef __DUMMY_INTF_H__
#define __DUMMY_INTF_H__
// Interface needs to include something?
#define DUMMY_NR_1 1
#define DUMMY_NR_2 2
#endif /* __DUMMY_INTF_H__ */

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: DummyInterface.java,v 1.1 2006/08/21 12:13:13 fros4943 Exp $
*/
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
/**
* This is an example of how to implement new simulation interfaces.
*
* It needs read/write access to the following core variables:
* <ul>
* <li>char simDummyVar
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>dummy_interface
* </ul>
* <p>
* This observable never changes.
*
* @author Fredrik Osterlind
*/
@ClassDescription("Dummy Interface")
public class DummyInterface extends MoteInterface {
private static Logger logger = Logger.getLogger(DummyInterface.class);
public DummyInterface(Mote mote) {
}
public static String[] getCoreInterfaceDependencies() {
// I need the corresponding C dummy interface (in dummy_intf.c)
return new String[] { "dummy_interface" };
}
public void doActionsBeforeTick() {
logger.debug("Simulation (Java) dummy interface acts BEFORE mote tick");
}
public void doActionsAfterTick() {
logger.debug("Simulation (Java) dummy interface acts AFTER mote tick");
}
public JPanel getInterfaceVisualizer() {
return null; // No visualizer exists
}
public void releaseInterfaceVisualizer(JPanel panel) {
}
public double energyConsumptionPerTick() {
return 0.0; // I never require any energy
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1 @@
se.sics.cooja.GUI.PLUGINS = + MyDummyPlugin

View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MyDummyPlugin.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import se.sics.cooja.*;
/**
* This is an simple example plugin.
* It is a simulation plugin, which means that it depends on a single simulation.
*
* @author Fredrik Osterlind
*/
@ClassDescription("Dummy Plugin")
@VisPluginType(VisPluginType.SIM_PLUGIN)
public class MyDummyPlugin extends VisPlugin {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(MyDummyPlugin.class);
private Simulation mySimulation;
private Observer tickObserver;
/**
* Creates a new dummy plugin.
*
* @param simulationToVisualize Simulation to visualize
*/
public MyDummyPlugin(Simulation simulationToVisualize) {
super("This is my title!");
mySimulation = simulationToVisualize;
// Create and add a button
JButton button = new JButton("dummy button");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
logger.info("You just pressed my button");
}
});
add(button);
// Register as tickobserver
mySimulation.addTickObserver(tickObserver = new Observer() {
public void update(Observable obs, Object obj) {
logger.info("Another tick loop completed - simulation time is now:\t" + mySimulation.getSimulationTime());
}
});
setSize(300,100); // Set an initial size of this plugin
// Tries to select this plugin
try {
setSelected(true);
} catch (java.beans.PropertyVetoException e) {
// Could not select
}
}
public void closePlugin() {
mySimulation.deleteTickObserver(tickObserver);
}
}

View file

@ -0,0 +1 @@
se.sics.cooja.GUI.RADIOMEDIUMS = + DummyRadioMedium

View file

@ -0,0 +1,94 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: DummyRadioMedium.java,v 1.1 2006/08/21 12:13:00 fros4943 Exp $
*/
import java.util.Collection;
import java.util.Observer;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.interfaces.*;
/**
* Dummy radio medium. No data is ever transferred through this medium.
* It also outputs some dummy debug messages during usage.
*
* @author Fredrik Osterlind
*/
@ClassDescription("Dummy Radio Medium")
public class DummyRadioMedium extends RadioMedium {
private static Logger logger = Logger.getLogger(GUI.class);
public void registerMote(Mote mote, Simulation sim) {
// Do nothing
logger.debug("I'm a dummy. Nothing will be registered by me.");
}
public void unregisterMote(Mote mote, Simulation sim) {
// Do nothing
}
public void registerRadioInterface(Radio radio, Position position, Simulation sim) {
// Do nothing
logger.debug("I'm a dummy. Nothing will be registered by me.");
}
public void unregisterRadioInterface(Radio radio, Simulation sim) {
// Do nothing
}
public void addRadioMediumObserver(Observer observer) {
// Do nothing
logger.debug("I'm a dummy. I will never change.");
}
public void deleteRadioMediumObserver(Observer observer) {
// Do nothing
logger.debug("I'm a dummy. I will never change.");
}
public RadioConnection[] getLastTickConnections() {
return null;
}
public void setConnectionLogger(ConnectionLogger connection) {
// Do nothing
}
public Collection<Element> getConfigXML() {
return null;
}
public boolean setConfigXML(Collection<Element> configXML) {
return true;
}
}

View file

@ -0,0 +1,3 @@
se.sics.cooja.GUI.PLUGINS = + VisUAODV UAODVControl
se.sics.cooja.contikimote.ContikiMoteType.C_SOURCES = + uaodv-example.c

View file

@ -0,0 +1,158 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: UAODVControl.java,v 1.1 2006/08/21 12:13:01 fros4943 Exp $
*/
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.interfaces.ContikiRS232;
import se.sics.cooja.interfaces.*;
/**
* @author Fredrik Osterlind
*/
@ClassDescription("uAODV Control")
@VisPluginType(VisPluginType.SIM_PLUGIN)
public class UAODVControl extends VisPlugin {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(UAODVControl.class);
private Simulation mySimulation;
private JComboBox sourceComboBox;
private JComboBox destComboBox;
/**
* @param simulationToVisualize Current simulation
*/
public UAODVControl(Simulation simulationToVisualize) {
super("uAODV Control (uses RS232)");
mySimulation = simulationToVisualize;
Container mainPane = this.getContentPane();
mainPane.setLayout(new BoxLayout(mainPane, BoxLayout.Y_AXIS));
JLabel label;
JPanel smallPane;
// Create available nodes list
Vector<String> nodeDescs = new Vector<String>();
for (int i=0; i < mySimulation.getMotesCount(); i++) {
Mote currentMote = mySimulation.getMote(i);
nodeDescs.add("ID="
+ currentMote.getInterfaces().getMoteID().getMoteID()
+ ", IP="
+ currentMote.getInterfaces().getIPAddress().getIPString());
}
// Create source combo box
label = new JLabel("Select RREQ source");
sourceComboBox = new JComboBox(nodeDescs);
if (sourceComboBox.getItemCount() < 1) {
logger.warn("No nodes available");
} else
sourceComboBox.setSelectedIndex(0);
label.setLabelFor(sourceComboBox);
smallPane = new JPanel();
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(sourceComboBox);
mainPane.add(smallPane);
// Create destination combo box
label = new JLabel("Select RREQ destination");
destComboBox = new JComboBox(nodeDescs);
if (destComboBox.getItemCount() < 1) {
logger.warn("No nodes available");
} else
destComboBox.setSelectedIndex(0);
label.setLabelFor(destComboBox);
smallPane = new JPanel();
smallPane.add(label);
smallPane.add(Box.createHorizontalStrut(10));
smallPane.add(destComboBox);
mainPane.add(smallPane);
// Add set button
smallPane = new JPanel(new BorderLayout());
JButton setDestinationButton = new JButton("Set IP and send RREQ");
setDestinationButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
logger.debug("Sending RS232 command now");
Mote sourceMote = mySimulation.getMote(sourceComboBox.getSelectedIndex());
Mote destMote = mySimulation.getMote(destComboBox.getSelectedIndex());
if (sourceMote == null || destMote == null) {
logger.error("Error in mote selection");
return;
}
// Get destination IP
IPAddress destIP = destMote.getInterfaces().getIPAddress();
if (destIP == null) {
logger.error("Error when fetching destination IP");
return;
}
// Set destination and start sending by using RS232
ContikiRS232 rs232 = sourceMote.getInterfaces().getInterfaceOfType(ContikiRS232.class);
if (rs232 == null) {
logger.error("RS232 interface is null!");
return;
}
rs232.sendSerialMessage("SENDTO>" + destIP.getIPString());
}
});
smallPane.add(BorderLayout.EAST, setDestinationButton);
mainPane.add(smallPane);
pack();
// Tries to select this plugin
try {
setSelected(true);
} catch (java.beans.PropertyVetoException e) {
// Could not select
}
}
public void closePlugin() {
}
}

View file

@ -0,0 +1,108 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: VisUAODV.java,v 1.1 2006/08/21 12:13:01 fros4943 Exp $
*/
import java.awt.*;
import org.apache.log4j.Logger;
import se.sics.cooja.*;
import se.sics.cooja.interfaces.Position;
import se.sics.cooja.plugins.*;
/**
* VisUAODV is a 2D graphical visualizer for simulations with motes running
* UAODV protocol.
* RREQs are painted red, and RREPs green.
* The rest of sent data is painted black.
*
* Interactions with motes are available via registered mote plugins.
*
* @author Fredrik Osterlind
*/
@ClassDescription("uAODV Visualizer")
@VisPluginType(VisPluginType.SIM_PLUGIN)
public class VisUAODV extends VisTraffic {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(VisUAODV.class);
/**
* Creates a new VisUAODV visualizer.
* @param simulationToVisualize Simulation to visualize
*/
public VisUAODV(Simulation simulationToVisualize) {
super(simulationToVisualize);
setTitle("uAODV Visualizer");
}
protected void paintConnection(RadioConnection connection, Graphics g2d) {
Point sourcePixelPosition = transformPositionToPixel(connection.getSourcePosition());
for (Position destPosition: connection.getDestinationPositons()) {
Point destPixelPosition = transformPositionToPixel(destPosition);
g2d.setColor(getColorOf(connection));
if (isRouteReply(connection.getSourceData())) {
((Graphics2D) g2d).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1.0f));
}
g2d.drawLine(sourcePixelPosition.x, sourcePixelPosition.y,
destPixelPosition.x, destPixelPosition.y);
int hopCount = getHopCount(connection.getSourceData());
if (hopCount >= 0)
g2d.drawString("" + hopCount, sourcePixelPosition.x, sourcePixelPosition.y);
}
}
protected Color getColorOf(RadioConnection conn) {
if (isRouteRequest(conn.getSourceData()))
return Color.RED;
else if (isRouteReply(conn.getSourceData()))
return Color.GREEN;
else
return Color.BLACK;
}
private boolean isRouteRequest(byte[] data) {
if (data.length > 28)
return data[28] == 1;
return false;
}
private boolean isRouteReply(byte[] data) {
if (data.length > 28)
return data[28] == 2;
return false;
}
private int getHopCount(byte[] data) {
if (data.length > 31)
return (int) data[31];
return -1;
}
}

View file

@ -0,0 +1,77 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: uaodv-example.c,v 1.1 2006/08/21 12:13:12 fros4943 Exp $
*/
#include "contiki-net.h"
#include "net/uaodv.h"
#include "net/uaodv-rt.h"
#include "lib/sensors.h"
#include "sys/log.h"
#include "dev/button-sensor.h"
#include "dev/serial.h"
/*---------------------------------------------------------------------------*/
PROCESS(uaodv_example_process, "uAODV example");
AUTOSTART_PROCESSES(&uaodv_process, &uaodv_example_process);
/*---------------------------------------------------------------------------*/
PROCESS_THREAD(uaodv_example_process, ev, data)
{
static uip_ipaddr_t addr;
PROCESS_BEGIN();
int ipA, ipB, ipC, ipD;
char buf[200];
button_sensor.activate();
serial_init();
while(1) {
PROCESS_WAIT_EVENT();
if(ev == sensors_event && data == &button_sensor && button_sensor.value(0)) {
uip_ipaddr(addr, 10,10,0,1);
log_message("Sending RREQ to (static) 10.10.0.1\n", "");
uaodv_request_route_to(addr);
} else if(ev == serial_event_message) {
sscanf(data, "SENDTO>%d.%d.%d.%d", &ipA, &ipB, &ipC, &ipD);
sprintf(buf, "Sending RREQ to %d.%d.%d.%d .. \n", ipA, ipB, ipC, ipD);
log_message(buf, "");
uip_ipaddr(&addr, ipA, ipB, ipC, ipD);
uaodv_request_route_to(&addr);
}
}
PROCESS_END();
}
/*---------------------------------------------------------------------------*/

View file

@ -0,0 +1,49 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ClassDescription.java,v 1.1 2006/08/21 12:12:57 fros4943 Exp $
*/
package se.sics.cooja;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Annotation type to describe a class.
* Description may be shown in menues etc.
*
* @author Fredrik Osterlind
*/
@Inherited
@Retention(RetentionPolicy.RUNTIME)
public @interface ClassDescription {
String value();
}

View file

@ -0,0 +1,176 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ConnectionLogger.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.io.File;
import java.io.FileOutputStream;
import org.apache.log4j.Logger;
import se.sics.cooja.interfaces.Position;
import se.sics.cooja.plugins.SimControl;
/**
* ConnectionLogger is a simple connection information outputter. All
* connections given via the method logConnection will be written to either
* default Log4J info stream, a log file or both.
*
* Log files have the following structure (spaces are tabs): SRC_POS [src_x]
* [src_y] [src_z] SRC_DATA [sent data bytes] DEST_POS [dest_x] [dest_y]
* [dest_z] DEST_DATA [received data bytes] [newline]
*
* @see RadioConnection
* @see RadioMedium
*
* @author Fredrik Osterlind
*/
public class ConnectionLogger {
private static final long serialVersionUID = 1L;
private static Logger logger = Logger.getLogger(SimControl.class);
private static int LOG_TO_FILE = 1;
private static int LOG_TO_LOG4J = 2;
private static int LOG_TO_FILE_AND_LOG4J = 3;
private int myType;
private File myFile;
/**
* Creates a new connection logger outputting to Log4J info stream.
*/
public ConnectionLogger() {
myType = LOG_TO_LOG4J;
}
/**
* Creates a new connection logger outputting to a file.
*
* @param logFile
* Log file
*/
public ConnectionLogger(File logFile) {
myType = LOG_TO_FILE;
myFile = logFile;
if (myFile.exists())
myFile.delete();
}
/**
* Output given connection to either Log4J info stream or a file.
*
* @param conn
* Connection to output
*/
public void logConnection(RadioConnection conn) {
if (myType == LOG_TO_LOG4J || myType == LOG_TO_FILE_AND_LOG4J) {
if (conn.getDestinationPositons() != null
&& conn.getDestinationPositons().length > 0)
for (Position destPos : conn.getDestinationPositons()) {
logger.info("RADIODATA from " + conn.getSourcePosition() + " to "
+ destPos + "\tsize:" + conn.getSourceData().length);
}
else
logger.info("RADIODATA from " + conn.getSourcePosition() + " to "
+ "[NOWHERE]" + "\tsize:" + conn.getSourceData().length);
}
if (myType == LOG_TO_FILE || myType == LOG_TO_FILE_AND_LOG4J) {
try {
FileOutputStream out = new FileOutputStream(myFile, true);
if (conn.getDestinationPositons() != null
&& conn.getDestinationPositons().length > 0) {
for (int i = 0; i < conn.getDestinationPositons().length; i++) {
// Source pos
out.write("SRC_POS\t".getBytes());
Position pos = conn.getSourcePosition();
out.write(Double.toString(pos.getXCoordinate()).getBytes());
out.write("\t".getBytes());
out.write(Double.toString(pos.getYCoordinate()).getBytes());
out.write("\t".getBytes());
out.write(Double.toString(pos.getZCoordinate()).getBytes());
out.write("\t".getBytes());
// Source data
out.write("SRC_DATA\t".getBytes());
for (byte b : conn.getSourceData())
out.write(Integer.toHexString((int) b).getBytes());
out.write("\t".getBytes());
// Destination pos
out.write("DEST_POS\t".getBytes());
pos = conn.getDestinationPositons()[i];
out.write(Double.toString(pos.getXCoordinate()).getBytes());
out.write("\t".getBytes());
out.write(Double.toString(pos.getYCoordinate()).getBytes());
out.write("\t".getBytes());
out.write(Double.toString(pos.getZCoordinate()).getBytes());
out.write("\t".getBytes());
// Source data
out.write("DEST_DATA\t".getBytes());
for (byte b : conn.getDestinationData()[i])
out.write(Integer.toHexString((int) b).getBytes());
out.write("\t".getBytes());
out.write("\n".getBytes());
}
} else {
// Source pos
out.write("SRC_POS\t".getBytes());
Position pos = conn.getSourcePosition();
out.write(Double.toString(pos.getXCoordinate()).getBytes());
out.write("\t".getBytes());
out.write(Double.toString(pos.getYCoordinate()).getBytes());
out.write("\t".getBytes());
out.write(Double.toString(pos.getZCoordinate()).getBytes());
out.write("\t".getBytes());
// Source data
out.write("SRC_DATA\t".getBytes());
for (byte b : conn.getSourceData())
out.write(Integer.toHexString((int) b).getBytes());
out.write("\n".getBytes());
}
out.close();
} catch (Exception e) {
logger.fatal("Exception while logging to file: " + e);
myType = LOG_TO_LOG4J;
return;
}
}
}
}

View file

@ -0,0 +1,225 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: CoreComm.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.io.File;
import se.sics.cooja.corecomm.*;
/**
* The package corecomm's purpose is communicating with the simulation core
* using Java Native Interface (JNI). Each implementing class (named Lib[1-MAX]),
* loads a shared library which belongs to one mote type. The reason for this
* somewhat strange design is that once loaded, a native library cannot be unloaded
* in Java (yet). Therefore if we wish to load several libraries, the names and associated
* native functions must have unique names. And those names are defined via the calling class in JNI.
* For example, the native tick function in class Lib1 is named contiki_javasim_corecomm_Lib1_tick.
* When creating a new mote type, the main contiki source file is generated with function names
* compatible with the next available corecomm.
* This also implies that even if a mote type is deleted, a new one cannot be created without
* restarting the JVM and thus the entire simulation.
*
* Each implemented CoreComm class needs read access to the following core variables:
* <ul>
* <li>referenceVar
* </ul>
* and the following native functions:
* <ul>
* <li>init()
* <li>tick()
* <li>getReferenceAbsAddr()
* <li>getMemory(int start, int length)
* <li>setMemory(int start, int length, byte[] mem)
* </ul>
* @author Fredrik Osterlind
*/
public abstract class CoreComm {
/**
* Maximum supported core communicators in a simulation.
*/
private final static int MAX_LIBRARIES = 8;
// Static pointers to current libraries
private final static CoreComm[] coreComms = new CoreComm[MAX_LIBRARIES];
private final static File[] coreCommFiles = new File[MAX_LIBRARIES];
/**
* Has any library been loaded? Since libraries can't be unloaded
* the entire simulator may have to be restarted.
*
* @return True if any library has been loaded this session
*/
public static boolean hasLibraryBeenLoaded() {
for (int i=0; i < coreComms.length; i++)
if (coreComms[i] != null)
return true;
return false;
}
/**
* Has given library file already been loaded during this session?
* A loaded library can be removed, but not unloaded
* during one session. And a new library file, named
* the same as an earlier loaded and removed file,
* can't be loaded either.
*
* @param libraryFile Library file
* @return True if a library has already been loaded from the given file's filename
*/
public static boolean hasLibraryFileBeenLoaded(File libraryFile) {
for (File libFile: coreCommFiles)
if (libFile != null && libFile.getName().equals(libraryFile.getName()))
return true;
return false;
}
/**
* Get the class name of next free core communicator class.
* If null is returned, no classes are available.
*
* @return Class name
*/
public static String getAvailableClassName() {
if (coreComms[0] == null)
return "Lib1";
if (coreComms[1] == null)
return "Lib2";
if (coreComms[2] == null)
return "Lib3";
if (coreComms[3] == null)
return "Lib4";
if (coreComms[4] == null)
return "Lib5";
if (coreComms[5] == null)
return "Lib6";
if (coreComms[6] == null)
return "Lib7";
if (coreComms[7] == null)
return "Lib8";
return null;
}
/**
* Create and return an instance of the core communicator identified
* by className. This core communicator will load the native library libFile.
*
* @param className Class name of core communicator
* @param libFile Native library file
* @return Core Communicator
*/
public static CoreComm createCoreComm(String className, File libFile) {
if (className.equals("Lib1") && coreComms[0] == null) {
coreComms[0] = new Lib1(libFile);
coreCommFiles[0] = libFile;
return coreComms[0];
}
if (className.equals("Lib2") && coreComms[1] == null) {
coreComms[1] = new Lib2(libFile);
coreCommFiles[1] = libFile;
return coreComms[1];
}
if (className.equals("Lib3") && coreComms[2] == null) {
coreComms[2] = new Lib3(libFile);
coreCommFiles[2] = libFile;
return coreComms[2];
}
if (className.equals("Lib4") && coreComms[3] == null) {
coreComms[3] = new Lib4(libFile);
coreCommFiles[3] = libFile;
return coreComms[3];
}
if (className.equals("Lib5") && coreComms[4] == null) {
coreComms[4] = new Lib5(libFile);
coreCommFiles[4] = libFile;
return coreComms[4];
}
if (className.equals("Lib6") && coreComms[5] == null) {
coreComms[5] = new Lib6(libFile);
coreCommFiles[5] = libFile;
return coreComms[5];
}
if (className.equals("Lib7") && coreComms[6] == null) {
coreComms[6] = new Lib7(libFile);
coreCommFiles[6] = libFile;
return coreComms[6];
}
if (className.equals("Lib8") && coreComms[7] == null) {
coreComms[7] = new Lib8(libFile);
coreCommFiles[7] = libFile;
return coreComms[7];
}
return null;
}
/**
* Ticks a mote once. This should not be used directly,
* but instead via Mote.tick().
*/
public abstract void tick();
/**
* Initializes a mote by running a startup script in the core.
* (Should only by run once, at the same time as the library is loaded)
*/
protected abstract void init();
/**
* Returns absolute memory location of the core variable
* referenceVar. Used to get offset between relative and absolute
* memory addresses.
*
* @return Absolute memory address
*/
public abstract int getReferenceAbsAddr();
/**
* Returns a memory segment identified by start and length.
*
* @param start Start address of segment
* @param length Length of segment
* @return Memory segment
*/
public abstract byte[] getMemory(int start, int length);
/**
* Overwrites a memory segment identified by start and length.
*
* @param start Start address of segment
* @param length Length of segment
* @param mem Data to fill memory segment
*/
public abstract void setMemory(int start, int length, byte[] mem);
}

View file

@ -0,0 +1,143 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: DirectoryClassLoader.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.io.*;
import org.apache.log4j.Logger;
/**
* Loads an external file from the given directory as a Java class.
*
* @author Fredrik Osterlind
*/
public class DirectoryClassLoader extends ClassLoader {
private static Logger logger = Logger.getLogger(DirectoryClassLoader.class);
private File directory;
/**
* Creates a new class loader reading from given directory.
*
* @param directory
* Directory
*/
public DirectoryClassLoader(File directory) {
super();
this.directory = directory;
}
/**
* Creates a new class loader reading from given directory, with the given
* class loader as parent class loader.
*
* @param parent
* Parent class loader
* @param directory
* Directory
*/
public DirectoryClassLoader(ClassLoader parent, File directory) {
super(parent);
this.directory = directory;
}
public Class<?> findClass(String name) throws ClassNotFoundException {
String fullFilePath = directory.getPath() + File.separatorChar + name
+ ".class";
// Read external file
//logger.info("Directory class loader reading file: " + fullFilePath);
byte[] classData = loadClassData(fullFilePath);
if (classData == null) {
throw new ClassNotFoundException();
}
// Create class
return defineClass(name, classData, 0, classData.length);
}
private byte[] loadClassData(String name) {
// Support for fill class names in configuration file
// TODO Quick-fix (may contain bugs)
name = name.replace('.', File.separatorChar);
name = name.replace(File.separatorChar + "class", ".class");
// Open file for read access
File classFile = new File(name);
InputStream inputStream = null;
if (!classFile.exists()) {
//logger.fatal("File " + classFile + " does not exist!");
return null;
}
try {
inputStream = new FileInputStream(classFile);
if (inputStream == null) {
logger.fatal("File input stream is null!");
return null;
}
} catch (FileNotFoundException e) {
logger.fatal("Could not open file (not found?)!");
return null;
}
long fileSize = classFile.length();
if (fileSize > Integer.MAX_VALUE) {
logger.fatal("Class file is too large");
return null;
}
// Read class data
byte[] classData = new byte[(int) fileSize];
int offset = 0;
int numRead = 0;
try {
while (offset < classData.length
&& (numRead = inputStream.read(classData, offset, classData.length
- offset)) >= 0) {
offset += numRead;
}
inputStream.close();
} catch (IOException e) {
logger.fatal("Error when reading class file");
return null;
}
// Ensure all the bytes have been read in
if (offset < classData.length) {
logger.fatal("Could not read entire class file");
return null;
}
return classData;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,75 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: IPDistributor.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.lang.reflect.Constructor;
import java.util.Vector;
import org.apache.log4j.Logger;
/**
* A IP distributor is used for determining IP addresses of newly created motes.
*
* @author Fredrik Osterlind
*/
public abstract class IPDistributor {
private static Logger logger = Logger.getLogger(IPDistributor.class);
/**
* This method creates an instance of the given class with the given vector as
* constructor argument. Instead of calling the constructors directly this
* method may be used.
*
* @param ipDistClass Class
* @param newMotes All motes that later should be assigned IP numbers
* @return IP distributor instance
*/
public static final IPDistributor generateInterface(
Class<? extends IPDistributor> ipDistClass, Vector<Mote> newMotes) {
try {
// Generating IP distributor
Constructor constr = ipDistClass
.getConstructor(new Class[]{Vector.class});
return (IPDistributor) constr.newInstance(new Object[]{newMotes});
} catch (Exception e) {
logger.fatal("Exception when creating " + ipDistClass + ": " + e);
return null;
}
}
/**
* Returns the next mote position.
*
* @return Position
*/
public abstract String getNextIPAddress();
}

View file

@ -0,0 +1,208 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Mote.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.util.Collection;
import java.util.Observer;
import org.jdom.Element;
/**
* This interface represents a simulated mote.
*
* A mote is always in some state, describing the status of the CPU etc.
* Motes in different states may be handled differently by the for example simulation loops and plugins.
*
* All motes must also have an interface handler, a mote type and a mote memory.
*
* @see se.sics.cooja.MoteInterfaceHandler
* @see se.sics.cooja.MoteMemory
* @see se.sics.cooja.MoteType
*
* @author Fredrik Osterlind
*/
public interface Mote {
/**
* Active state.
*/
public static int STATE_ACTIVE = 1;
/**
* Sleeping state.
*/
public static int STATE_LPM = 2;
/**
* Dead state (may be out of batteries).
*/
public static int STATE_DEAD = 3;
/**
* Tries to change state to given argument.
* A dead mote can typically not change state, while a sleeping or active mote can.
*
* @param newState New state of mote.
*/
public void setState(int newState);
/**
* @return Current mote state
*/
public int getState();
/**
* Adds new state observer.
* This observer is notified if mote changes state.
*
* @see #deleteStateObserver(Observer)
* @param newObserver New observer
*/
public void addStateObserver(Observer newObserver);
/**
* Delete existing state observer.
*
* @see #addStateObserver(Observer)
* @param newObserver Registered state observer
*/
public void deleteStateObserver(Observer newObserver);
/**
* Returns the interface handler of this mote.
*
* @see #setInterfaces(MoteInterfaceHandler)
* @return Mote interface handler
*/
public MoteInterfaceHandler getInterfaces();
/**
* Sets the interface handler of this mote.
*
* @param moteInterfaceHandler New interface handler
* @see #getInterfaces()
*/
public void setInterfaces(MoteInterfaceHandler moteInterfaceHandler);
/**
* Returns the memory of this mote.
*
* @see #setMemory(MoteMemory)
* @return Mote memory
*/
public MoteMemory getMemory();
/**
* Sets the memory of this mote.
*
* @see #getMemory()
* @param memory Mote memory
*/
public void setMemory(MoteMemory memory);
/**
* Returns mote type.
*
* @see #setType(MoteType)
* @return Mote type
*/
public MoteType getType();
/**
* Sets mote type to given argument.
*
* @see #getType()
* @param type New type
*/
public void setType(MoteType type);
/**
* Returns simulation which holds this mote.
*
* @see #setSimulation(Simulation)
* @return Simulation
*/
public Simulation getSimulation();
/**
* Sets the simulation which holds this mote.
*
* @see #getSimulation()
* @param simulation Simulation
*/
public void setSimulation(Simulation simulation);
/**
* Ticks this mote and increases any internal time to given argument.
*
* Each mote implementation may handle calls to this method differently,
* but, if existing, the simulated mote should at least handle one event.
*
* This method is responsible for updating the mote interfaces, the memory and the mote state.
*
* A call to this method typically
* polls all interfaces,
* activates the memory,
* lets the underlying mote software handle one event,
* fetches the updated memory and
* finally polls all interfaces again.
*
* @param simTime New simulation time
*/
public void tick(int simTime);
/**
* Returns XML elements representing the current config of this mote.
* This is fetched by the simulator for example when saving a simulation configuration file.
* For example a mote may return the configs of all its interfaces.
* This method should however not return state specific information such as the mote state.
* (All nodes are restarted when loading a simulation.)
*
* @see #setConfigXML(Simulation, Collection)
* @return XML elements representing the current mote config
*/
public abstract Collection<Element> getConfigXML();
/**
* Sets the current mote config depending on the given XML elements.
*
* @param simulation Simulation holding this mote
* @param configXML Config XML elements
*
* @see #getConfigXML()
*/
public abstract boolean setConfigXML(Simulation simulation, Collection<Element> configXML);
}

View file

@ -0,0 +1,158 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MoteInterface.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.util.Collection;
import java.util.Observable;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
import org.jdom.Element;
/**
* A mote interface represents a mote property.
* Often this is a simulated hardware peripheral such as a button or a led.
* This can also be a property the mote software itself is unaware of,
* for example the current position of the mote.
*
* Interfaces are the main way for the simulator to interact with a simulated mote.
*
* Interfaces are divided into active and passive interfaces, and are handled differently.
* In order to create a passive interfaces, the class should also implement the dummy Java interface PassiveMoteInterface.
* For an explanation of the differences of active and passive interfaces see class PassiveMoteInterface.
*
* @see PassiveMoteInterface
* @author Fredrik Osterlind
*/
public abstract class MoteInterface extends Observable {
private static Logger logger = Logger.getLogger(MoteInterface.class);
/**
* This method creates an instance of the given class with the given mote as constructor
* argument. Instead of calling the interface constructors directly this method may be used.
*
* @param interfaceClass Mote interface class
* @param mote Mote that will hold the interface
* @return Mote interface instance
*/
public static final MoteInterface generateInterface(Class<? extends MoteInterface> interfaceClass, Mote mote) {
try {
// Generating interface
MoteInterface instance = (MoteInterface) interfaceClass.getConstructor(
new Class[] { Mote.class }).newInstance(new Object[] { mote });
return instance;
} catch (Exception e) {
logger.fatal("Exception when creating " + interfaceClass + ": " + e);
return null;
}
}
/**
* Actions to be performed just before the holding mote is ticked
*/
public abstract void doActionsBeforeTick();
/**
* Actions to be performed just after the holding mote has been ticked
*/
public abstract void doActionsAfterTick();
/**
* Returns a panel with interesting data for this interface.
* This could for example show last messages sent/received for
* a radio interface, or logged message for a log interface.
*
* All panels returned from this method must later be released
* for memory reasons.
*
* If returned panel is null, this interface will not be visualized.
*
* @see #releaseInterfaceVisualizer(JPanel)
* @return Interface visualizer or null
*/
public abstract JPanel getInterfaceVisualizer();
/**
* This method should be called when a visualizer panel is no longer in use.
* Any resources of that panel, for example registered observers, will be released.
*
* @see #getInterfaceVisualizer()
* @param panel A interface visualizer panel fetched earlier for this mote interface.
*/
public abstract void releaseInterfaceVisualizer(JPanel panel);
/**
* Returns approximated energy consumed (mQ) during the current tick.
* If the interface is active, this information must be available after the doActionsAfterTick method.
* If the interface is passive, this information must be available after the doActionsBeforeTick method.
*
* The interface is responsible to gather information about the current internal state,
* and calculate whatever energy it needs in that state and during one tick.
*
* If the holding mote is dead, this method will not be called.
* If the holding mote is sleeping and this interface is active, this method will not be called.
*
* For example, a radio transmitter or a PIR sensor often has a much higher energy
* usage than a button sensor which virtually needs no energy at all.
* If the radio is turned off in hardware, it should return a zero energy consumption.
* If the radio is sending something which would take longer than one tick, it may either return
* the total energy used directly, or a smaller amount during several ticks.
*
* This method may typically be used by the passive interface battery, which sums up
* all energy used during one tick and decreases the battery energy left.
*
* @see se.sics.cooja.interfaces.Battery
* @return Energy consumption of this device during the current tick
*/
public abstract double energyConsumptionPerTick();
/**
* Returns XML elements representing the current config of this mote interface.
* This is fetched by the simulator for example when saving a simulation configuration file.
* For example an IP interface may return one element with the mote IP address.
* This method should however not return state specific information such as a log history.
* (All nodes are restarted when loading a simulation.)
*
* @see #setConfigXML(Collection)
* @return XML elements representing the current interface config
*/
public abstract Collection<Element> getConfigXML();
/**
* Sets the current mote interface config depending on the given XML elements.
*
* @see #getConfigXML()
* @param configXML Config XML elements
*/
public abstract void setConfigXML(Collection<Element> configXML);
}

View file

@ -0,0 +1,358 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MoteInterfaceHandler.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.util.*;
import org.apache.log4j.Logger;
import se.sics.cooja.interfaces.*;
/**
* A mote interface handler holds all interfaces for a specific mote. Even
* though an interface handler strictly does not need any interfaces at all, a
* position interface is highly recommended. (A lot of plugins depend on a mote
* position, for example when visualizing nodes.)
*
* Interfaces are divided into active and passive interfaces. Active interfaces
* are only polled if the mote is active, while passive interfaces are polled in
* all states except dead state.
*
* Interfaces should be polled via this class when the mote is ticked.
*
* @author Fredrik Osterlind
*/
public class MoteInterfaceHandler {
private static Logger logger = Logger.getLogger(MoteInterfaceHandler.class);
private Battery myBattery;
private Beeper myBeeper;
private Button myButton;
private Clock myClock;
private IPAddress myIPAddress;
private LED myLED;
private Log myLog;
private MoteID myMoteID;
private PIR myPIR;
private Position myPosition;
private Radio myRadio;
private Vector<MoteInterface> myActiveInterfaces = new Vector<MoteInterface>();
private Vector<MoteInterface> myPassiveInterfaces = new Vector<MoteInterface>();
/**
* Creates a new empty mote interface handler.
*/
public MoteInterfaceHandler() {
}
/**
* Creates a new mote interface handler. All given interfaces are loaded.
*
* @param mote
* The mote holding this interface handler
* @param allInterfaces
* Simulation interfaces to load
*/
public MoteInterfaceHandler(Mote mote,
Vector<Class<? extends MoteInterface>> allInterfaces) {
// Load all interfaces
for (Class<? extends MoteInterface> interfaceClass : allInterfaces) {
boolean isPassive = false;
// Check if interface is active or passive
if (PassiveMoteInterface.class.isAssignableFrom(interfaceClass))
isPassive = true;
// Load interface
MoteInterface loadedInterface = MoteInterface.generateInterface(
interfaceClass, mote);
if (loadedInterface != null)
if (isPassive)
addPassiveInterface(loadedInterface);
else
addActiveInterface(loadedInterface);
else
logger.warn("Interface could not be loaded: " + interfaceClass);
}
}
/**
* Get an interface (active or passive) of the given type. Returns the first
* loaded interface found, that is either of the given class or of a subclass.
*
* For example, if the current radio interface is wanted, this method would be
* called like the following: getInterfaceOfType(Radio.class)
*
* @param interfaceType
* Type of interface to return
* @return Interface or null if no interface loaded of given type
*/
public <N extends MoteInterface> N getInterfaceOfType(Class<N> interfaceType) {
Enumeration<? extends MoteInterface> allActive = myActiveInterfaces.elements();
while (allActive.hasMoreElements()) {
N nextInterface = (N) allActive.nextElement();
if (interfaceType.isAssignableFrom(nextInterface.getClass()))
return nextInterface;
}
Enumeration<? extends MoteInterface> allPassive = myPassiveInterfaces.elements();
while (allPassive.hasMoreElements()) {
N nextInterface = (N) allPassive.nextElement();
if (interfaceType.isAssignableFrom(nextInterface.getClass()))
return nextInterface;
}
return null;
}
/**
* Returns the battery interface (if any).
*
* @return Battery interface
*/
public Battery getBattery() {
if (myBattery == null) {
myBattery = getInterfaceOfType(Battery.class);
}
return myBattery;
}
/**
* Returns the beeper interface (if any).
*
* @return Beeper interface
*/
public Beeper getBeeper() {
if (myBeeper == null) {
myBeeper = getInterfaceOfType(Beeper.class);
}
return myBeeper;
}
/**
* Returns the button interface (if any).
*
* @return Button interface
*/
public Button getButton() {
if (myButton == null) {
myButton = getInterfaceOfType(Button.class);
}
return myButton;
}
/**
* Returns the clock interface (if any).
*
* @return Clock interface
*/
public Clock getClock() {
if (myClock == null) {
myClock = getInterfaceOfType(Clock.class);
}
return myClock;
}
/**
* Returns the IP address interface (if any).
*
* @return IPAddress interface
*/
public IPAddress getIPAddress() {
if (myIPAddress == null) {
myIPAddress = getInterfaceOfType(IPAddress.class);
}
return myIPAddress;
}
/**
* Returns the LED interface (if any).
*
* @return LED interface
*/
public LED getLED() {
if (myLED == null) {
myLED = getInterfaceOfType(LED.class);
}
return myLED;
}
/**
* Returns the log interface (if any).
*
* @return Log interface
*/
public Log getLog() {
if (myLog == null) {
myLog = getInterfaceOfType(Log.class);
}
return myLog;
}
/**
* Returns the mote ID interface (if any).
*
* @return Mote ID interface
*/
public MoteID getMoteID() {
if (myMoteID == null) {
myMoteID = getInterfaceOfType(MoteID.class);
}
return myMoteID;
}
/**
* Returns the PIR interface (if any).
*
* @return PIR interface
*/
public PIR getPIR() {
if (myPIR == null) {
myPIR = getInterfaceOfType(PIR.class);
}
return myPIR;
}
/**
* Returns the position interface (if any).
*
* @return Position interface
*/
public Position getPosition() {
if (myPosition == null) {
myPosition = getInterfaceOfType(Position.class);
}
return myPosition;
}
/**
* Returns the radio interface (if any).
*
* @return Radio interface
*/
public Radio getRadio() {
if (myRadio == null) {
myRadio = getInterfaceOfType(Radio.class);
}
return myRadio;
}
/**
* Polls all active interfaces. This method should be called during a mote
* tick before the mote software is executed.
*/
public void doActiveActionsBeforeTick() {
for (int i = 0; i < myActiveInterfaces.size(); i++)
myActiveInterfaces.get(i).doActionsBeforeTick();
}
/**
* Polls all active interfaces. This method should be called during a mote
* tick after the mote software has executed.
*/
public void doActiveActionsAfterTick() {
for (int i = 0; i < myActiveInterfaces.size(); i++)
myActiveInterfaces.get(i).doActionsAfterTick();
}
/**
* Polls all passive interfaces. This method should be called during a mote
* tick before the mote software is executed.
*/
public void doPassiveActionsBeforeTick() {
for (int i = 0; i < myPassiveInterfaces.size(); i++)
myPassiveInterfaces.get(i).doActionsBeforeTick();
}
/**
* Polls all passive interfaces. This method should be called during a mote
* tick after the mote software has executed.
*/
public void doPassiveActionsAfterTick() {
for (int i = 0; i < myPassiveInterfaces.size(); i++)
myPassiveInterfaces.get(i).doActionsAfterTick();
}
/**
* Returns all passive mote interfaces.
*
* @return All passive mote interface
*/
public Vector<MoteInterface> getAllPassiveInterfaces() {
return myPassiveInterfaces;
}
/**
* Returns all active mote interfaces.
*
* @return All active mote interface
*/
public Vector<MoteInterface> getAllActiveInterfaces() {
return myActiveInterfaces;
}
/**
* Add an active interface to corresponding mote. An active interface is only
* allowed to act if the mote is in active state. However, since interfaces
* may awaken a sleeping mote up via external interrupts, most of the
* interfaces should be active.
*
* For example a button interface should be active. When the button is
* pressed, the interface will wake the mote up (simulated external
* interrupt), and then that button will be allowed to act before next tick.
*
* A passive interface is an interface which will always act if the mote is
* not dead. For example a battery should always be allowed to act since a
* mote needs energy even if it is in sleep mode.
*
* @see #addPassiveInterface(MoteInterface)
* @param newInterface
* New interface
*/
public void addActiveInterface(MoteInterface newInterface) {
myActiveInterfaces.add(newInterface);
}
/**
* Add a passive interface to corresponding mote. For explanation of passive
* vs active interfaces, see addActiveInterface(MoteInterface).
*
* @see #addActiveInterface(MoteInterface)
* @param newInterface
* New interface
*/
public void addPassiveInterface(MoteInterface newInterface) {
myPassiveInterfaces.add(newInterface);
}
}

View file

@ -0,0 +1,79 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MoteMemory.java,v 1.1 2006/08/21 12:12:55 fros4943 Exp $
*/
package se.sics.cooja;
/**
* This interface represents a mote memory.
*
* Mote memory is represented by byte arrays and this
* interface provides a few of basic operations.
*
* Note that this memory internally may consist of several
* different memory sections, not covering the entire range
* between the start address and the end address of this memory.
*
* @author Fredrik Osterlind
*/
public interface MoteMemory {
/**
* Clears the entire memory.
*/
public void clearMemory();
/**
* Returns a memory segment.
*
* @param address Start address of memory segment
* @param size Size of memory segment
* @return Memory segment or null if segment not available
*/
public byte[] getMemorySegment(int address, int size);
/**
* Sets a memory segment.
*
* @param address Start address of memory segment
* @param data Data
*/
public void setMemorySegment(int address, byte[] data);
/**
* Returns the sum of all byte array sizes in this memory.
* This is not neccessarily the the same as the total memory range,
* since the entire memory range may not be handled by this memory.
*
* @return Total size
*/
public int getTotalSize();
}

View file

@ -0,0 +1,149 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: MoteType.java,v 1.1 2006/08/21 12:12:57 fros4943 Exp $
*/
package se.sics.cooja;
import java.util.Collection;
import javax.swing.JFrame;
import javax.swing.JPanel;
import org.jdom.Element;
/**
* Every simulated motes belongs to a mote type.
*
* The mote type defines properties common for several motes. These properties
* may differ between different implementations, but typically includes how a
* mote of that type is initialized, which hardware peripherals each mote has
* etc.
*
* A mote type may also hold the connection to an underlying simulation
* framework.
*
* @author Fredrik Osterlind
*/
public interface MoteType {
/**
* Returns the mote type description.
*
* @return Description
*/
public String getDescription();
/**
* Sets the mote type description.
*
* @param description
* New description
*/
public void setDescription(String description);
/**
* Returns the mote type identifier.
*
* @return Mote type identifier
*/
public String getIdentifier();
/**
* Sets the mote type identifier.
*
* @param identifier
* New identifier
*/
public void setIdentifier(String identifier);
/**
* Returns a panel with interesting data for this mote type.
*
* @return Mote type visualizer
*/
public JPanel getTypeVisualizer();
/**
* Returns this mote type's platform configuration.
*
* @return Platform configuration
*/
public PlatformConfig getConfig();
/**
* Generates a mote of this mote type.
*
* @param simulation
* Newly created mote's simulation
* @return New mote
*/
public Mote generateMote(Simulation simulation);
/**
* This method configures and initializes a mote type ready to be used. It is
* called from the simulator when a new mote type is created. It may simply
* confirm that all settings are valid and return true, or display a dialog
* allowing a user to manually configure the mote type.
*
* This method need normally only be run once per mote type!
*
* @param parentFrame
* Parent frame or null
* @param simulation
* Simulation holding (or that should hold) mote type
* @return True if mote type has valid settings and is ready to be used
*/
public boolean configureAndInit(JFrame parentFrame, Simulation simulation);
/**
* Returns XML elements representing the current config of this mote type.
* This is fetched by the simulator for example when saving a simulation
* configuration file. For example a Contiki base directory may be saved.
*
* @see #setConfigXML(Simulation, Collection)
* @return XML elements representing the current mote type's config
*/
public Collection<Element> getConfigXML();
/**
* Sets the current mote type config depending on the given XML elements.
* Observe that this method is responsible for restoring the configuration
* depending on the given arguments. This may include recompiling and loading
* libraries.
*
* @see #getConfigXML()
* @param simulation
* Simulation that will hold the mote type
* @param configXML
* Config XML elements
* @return True if config was set successfully, false otherwise
*/
public boolean setConfigXML(Simulation simulation,
Collection<Element> configXML);
}

View file

@ -0,0 +1,58 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: PassiveMoteInterface.java,v 1.1 2006/08/21 12:12:57 fros4943 Exp $
*/
package se.sics.cooja;
/**
* Mote interfaces are divided into active and passive interfaces.
*
* A passive mote interface is treated different than an ordinary (active)
* mote interface;
* Passive interfaces are allowed to act even when the mote is sleeping,
* while active interface only acts when the mote is in active state.
*
* A typical active interface is the radio interface, since radio
* messages only can be received when the mote is active.
*
* A typical passive interface is the battery interface, since a mote
* consumes energy even though it is sleeping.
*
* All passive interface should implement this interface.
* All interfaces not implemented this interface will be handled as active interfaces.
*
* Any energy required by this interface must be available after the
* doActionsBeforeTick method.
*
* @author Fredrik Osterlind
*/
public interface PassiveMoteInterface {
}

View file

@ -0,0 +1,359 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: PlatformConfig.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.io.*;
import java.util.*;
import org.apache.log4j.Logger;
/**
* A platform configuration may hold the configuration for one or several user
* platforms as well as a general simulator configuration.
*
* The configuration for a user platform may for example consist of which
* plugins, interfaces and processes that the specific platform supplies. Each
* user platform configuration is read from the property file cooja.config, a
* file which is required in each user platform.
*
* Values can be fetched as String, Boolean, Integer, Double or String array.
*
* Several configurations can be merged, together forming a final overall
* configuration. The order of the how configurations are merged matter - later
* values will overwrite earlier. For example merging two configurations with
* the key 'SOMEKEY' in the following order:
*
* SOMEKEY = a b c
*
* SOMEKEY = d e
*
* will result in the final value "d e".
*
* If a specific value should be extended instead of overwritten, the value must
* start with a single space-surrounded '+'. For example, merging two
* configurations with the key as above in the following order:
*
* SOMEKEY = a b c
*
* SOMEKEY = + d e
*
* will result in the final value "a b c d e".
*
* The simulator will hold a merged platform configuration, depending on which
* user platforms are used. Additionally. each mote type may also have a
* configuration of its own, that differs from the general simulator
* configuration.
*
* Often, but not necessarily, keys are named depending on which class is
* associated with the information. For example, let's say a battery interface
* wants to store its initial capacity (a double) using this approach. Data
* stored in the external configuration file can look like the following:
* se.sics.cooja.interfaces.Battery.initial_capacity 54.123321
*
* This value is then be read by: myMoteTypeConfig.getDoubleValue(Battery.class,
* "initial_capacity");
*
* @author Fredrik Osterlind
*/
public class PlatformConfig {
private static Logger logger = Logger.getLogger(PlatformConfig.class);
private Properties myConfig = new Properties();
/**
* Creates a new empty platform configuration.
*/
public PlatformConfig() {
myConfig = new Properties();
}
/**
* Loads the given property file and appends it to the current configuration.
* If a property already exists it will be overwritten, unless the new value
* begins with a '+' in which case the old value will be extended.
*
* @param propertyFile
* Property file to read
* @return True if file was read ok, false otherwise
* @throws FileNotFoundException
* If file was not found
* @throws IOException
* Stream read error
*/
public boolean appendConfig(File propertyFile) throws FileNotFoundException,
IOException {
return appendConfig(myConfig, propertyFile);
}
private static boolean appendConfig(Properties currentValues,
File propertyFile) throws FileNotFoundException, IOException {
// Open file
FileInputStream in = new FileInputStream(propertyFile);
return appendConfig(currentValues, in);
}
/**
* Reads propertues from the given stream and appends them to the current
* configuration. If a property already exists it will be overwritten, unless
* the new value begins with a '+' in which case the old value will be
* extended.
*
* @param configFileStream
* Stream to read from
* @return True if stream was read ok, false otherwise
* @throws IOException
* Stream read error
*/
public boolean appendConfig(InputStream configFileStream) throws IOException {
return appendConfig(myConfig, configFileStream);
}
private static boolean appendConfig(Properties currentValues,
InputStream configFileStream) throws IOException {
// Read from stream
Properties newProps = new Properties();
newProps.load(configFileStream);
configFileStream.close();
// Read new properties
Enumeration en = newProps.keys();
while (en.hasMoreElements()) {
String key = (String) en.nextElement();
String property = newProps.getProperty(key);
if (property.startsWith("+ ")) {
if (currentValues.getProperty(key) != null)
currentValues.setProperty(key, currentValues.getProperty(key) + " " + property.substring(1).trim());
else
currentValues.setProperty(key, property.substring(1).trim());
} else
currentValues.setProperty(key, property);
}
return true;
}
/**
* @return All property names in configuration
*/
public Enumeration<String> getPropertyNames() {
return (Enumeration<String>) myConfig.propertyNames();
}
/**
* Get string value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @param defaultValue
* Default value to return if id is not found
* @return Value or defaultValue if id wasn't found
*/
public String getStringValue(Class callingClass, String id,
String defaultValue) {
return getStringValue(myConfig, callingClass, id, defaultValue);
}
private static String getStringValue(Properties currentValues,
Class callingClass, String id, String defaultValue) {
String val = currentValues.getProperty(callingClass.getName() + "." + id);
if (val == null) {
logger.warn("Could not find key named '" + callingClass.getName() + "." + id + "'");
return defaultValue;
}
return val;
}
/**
* Returns value of given name.
*
* @param name
* Name
* @return Value as string
*/
public String getStringValue(String name) {
if (!myConfig.containsKey(name))
logger.debug("Could not find key named '" + name + "'");
return myConfig.getProperty(name);
}
/**
* Get string value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @return Value or null if id wasn't found
*/
public String getStringValue(Class callingClass, String id) {
return getStringValue(callingClass, id, null);
}
/**
* Get string array value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @return Value or null if id wasn't found
*/
public String[] getStringArrayValue(Class callingClass, String id) {
String stringVal = getStringValue(callingClass, id, null);
if (stringVal == null)
return new String[0];
return getStringValue(callingClass, id, "").split(" ");
}
/**
* Get string value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @return Value or null if id wasn't found
*/
public String getValue(Class callingClass, String id) {
return getStringValue(callingClass, id);
}
/**
* Get integer value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @param defaultValue
* Default value to return if id is not found
* @return Value or defaultValue if id wasn't found
*/
public int getIntegerValue(Class callingClass, String id, int defaultValue) {
String str = getStringValue(callingClass, id);
if (str == null)
return defaultValue;
return Integer.parseInt(str);
}
/**
* Get integer value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @return Value or 0 if id wasn't found
*/
public int getIntegerValue(Class callingClass, String id) {
return getIntegerValue(callingClass, id, 0);
}
/**
* Get double value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @param defaultValue
* Default value to return if id is not found
* @return Value or defaultValue if id wasn't found
*/
public double getDoubleValue(Class callingClass, String id,
double defaultValue) {
String str = getStringValue(callingClass, id);
if (str == null)
return defaultValue;
return Double.parseDouble(str);
}
/**
* Get double value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @return Value or 0.0 if id wasn't found
*/
public double getDoubleValue(Class callingClass, String id) {
return getDoubleValue(callingClass, id, 0.0);
}
/**
* Get boolean value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @param defaultValue
* Default value to return if id is not found
* @return Value or defaultValue if id wasn't found
*/
public boolean getBooleanValue(Class callingClass, String id,
boolean defaultValue) {
String str = getStringValue(callingClass, id);
if (str == null)
return defaultValue;
return Boolean.parseBoolean(str);
}
/**
* Get boolean value with given id.
*
* @param callingClass
* Class which value belongs to
* @param id
* Id of value to return
* @return Value or false if id wasn't found
*/
public boolean getBooleanValue(Class callingClass, String id) {
return getBooleanValue(callingClass, id, false);
}
public PlatformConfig clone() {
PlatformConfig clone = new PlatformConfig();
clone.myConfig = (Properties) this.myConfig.clone();
return clone;
}
}

View file

@ -0,0 +1,93 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Positioner.java,v 1.1 2006/08/21 12:12:51 fros4943 Exp $
*/
package se.sics.cooja;
import java.lang.reflect.Constructor;
import org.apache.log4j.Logger;
/**
* A positioner is used for determining positions of newly created motes.
*
* @author Fredrik Osterlind
*/
public abstract class Positioner {
private static Logger logger = Logger.getLogger(Positioner.class);
/**
* This method creates an instance of the given class with the given interval
* information as constructor arguments. Instead of calling the constructors
* directly this method may be used.
*
* @param positionerClass
* Positioner class
* @param totalNumberOfMotes
* Total number of motes that should be generated using this
* positioner
* @param startX
* Lowest X value of positions generated using returned positioner
* @param endX
* Highest X value of positions generated using returned positioner
* @param startY
* Lowest Y value of positions generated using returned positioner
* @param endY
* Highest Y value of positions generated using returned positioner
* @param startZ
* Lowest Z value of positions generated using returned positioner
* @param endZ
* Highest Z value of positions generated using returned positioner
* @return Postioner instance
*/
public static final Positioner generateInterface(
Class<? extends Positioner> positionerClass, int totalNumberOfMotes,
double startX, double endX, double startY, double endY, double startZ,
double endZ) {
try {
// Generating positioner
Constructor constr = positionerClass.getConstructor(new Class[]{
int.class, double.class, double.class, double.class, double.class,
double.class, double.class});
return (Positioner) constr.newInstance(new Object[]{totalNumberOfMotes,
startX, endX, startY, endY, startZ, endZ});
} catch (Exception e) {
logger.fatal("Exception when creating " + positionerClass + ": " + e);
return null;
}
}
/**
* Returns the next mote position.
*
* @return Position
*/
public abstract double[] getNextPosition();
}

View file

@ -0,0 +1,150 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: RadioConnection.java,v 1.1 2006/08/21 12:12:55 fros4943 Exp $
*/
package se.sics.cooja;
import java.util.Vector;
import se.sics.cooja.interfaces.Position;
import se.sics.cooja.interfaces.Radio;
/**
* RadioConnection represents a radio connection between a sending radio
* and zero or more receiving radios.
* By registering as an observer to the current radio medium, all
* radio connections and data sent in that medium can be accessed.
*
* Each radio is associated with a position and some radio data.
* Often the destinations' and source's data will refer to the same object,
* but some radio mediums may want to distort the transferred data, hence
* resulting in different data sent and received.
*
* @see RadioMedium
* @author Fredrik Osterlind
*/
public class RadioConnection {
private Radio sourceRadio;
private Position sourcePosition;
private byte[] sourceData;
private Vector<Radio> destinationRadios = new Vector<Radio>();
private Vector<Position> destinationPositions = new Vector<Position>();
private Vector<byte[]> destinationData = new Vector<byte[]>();
/**
* Set source of this connection.
*
* @param radio Source radio
* @param position Source position
* @param data Source data
*/
public void setSource(Radio radio, Position position, byte[] data) {
sourceRadio = radio;
sourcePosition = position;
sourceData = data;
}
/**
* Add a connection destination.
*
* @param radio Source radio
* @param position Source position
* @param data Source data
*/
public void addDestination(Radio radio, Position position, byte[] data) {
destinationRadios.add(radio);
destinationPositions.add(position);
destinationData.add(data);
}
/**
* @return Source radio
*/
public Radio getSourceRadio() {
return sourceRadio;
}
/**
* @return Source position
*/
public Position getSourcePosition() {
return sourcePosition;
}
/**
* Returns the data actually sent by source radio.
* @return Source data
*/
public byte[] getSourceData() {
return sourceData;
}
/**
* @return Array of destination radios
*/
public Radio[] getDestinationRadios() {
Radio[] radioArrayType;
Radio[] radioArray;
radioArrayType = new Radio[destinationRadios.size()];
radioArray = (Radio[]) destinationRadios.toArray(radioArrayType);
return radioArray;
}
/**
* @return Array of destination positions
*/
public Position[] getDestinationPositons() {
Position[] positionArrayType;
Position[] positionArray;
positionArrayType = new Position[destinationPositions.size()];
positionArray = (Position[]) destinationPositions.toArray(positionArrayType);
return positionArray;
}
/**
* Returns an array of data actually received by each radio.
* @return Array of destination data
*/
public byte[][] getDestinationData() {
byte[][] dataArrayType;
byte[][] dataArray;
dataArrayType = new byte[destinationData.size()][];
dataArray = (byte[][]) destinationData.toArray(dataArrayType);
return dataArray;
}
}

View file

@ -0,0 +1,176 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: RadioMedium.java,v 1.1 2006/08/21 12:12:55 fros4943 Exp $
*/
package se.sics.cooja;
import java.util.Collection;
import java.util.Observer;
import org.jdom.Element;
import se.sics.cooja.interfaces.Position;
import se.sics.cooja.interfaces.Radio;
/**
* This interface represents a radio medium. Radios registered to this medium
* can both send and receive radio data. Depending on the implementation of this
* interface, more or less accurate radio behaviour imitation is aquired.
*
* Often a radio medium, at initialization, registers one or several dynamic
* plugins. These plugins shows the user some radio medium specific details,
* such as radio transmission radius etc.
*
* @author Fredrik Osterlind
*/
public abstract class RadioMedium {
/**
* Registers a mote to this medium.
*
* How radio data will be received from and sent to this mote depends on the
* medium implementation. Common factors may be random, distance from sending
* to receiving mote and interference with other radio transmitters in some
* range.
*
* @param mote
* Mote to register
* @param sim
* Simulation holding mote
*/
public abstract void registerMote(Mote mote, Simulation sim);
/**
* Unregisters a mote from this medium.
*
* @param mote
* Mote to unregister
* @param sim
* Simulation holding mote
*/
public abstract void unregisterMote(Mote mote, Simulation sim);
/**
* Register a radio to this medium at a given position.
*
* Concerning radio data, this radio will be treated the same way as a mote's
* radio. This method can be used to add non-mote radio devices, such as a
* packet generator or a sniffer.
*
* @param radio
* Radio
* @param position
* Position
* @param sim
* Simulation holding radio
*/
public abstract void registerRadioInterface(Radio radio, Position position,
Simulation sim);
/**
* Unregisters a radio interface from this medium.
*
* @param radio
* Radio interface to unregister
* @param sim
* Simulation holding radio
*/
public abstract void unregisterRadioInterface(Radio radio, Simulation sim);
/**
* Adds an observer which is notified after the radio connections has been
* calculated. Often a radio medium is a tick observer and makes these
* calculations after each tick loop. A radio medium observer may then gather
* network data by being notified every time the radio medium has delivered
* data. The radio medium observable MUST notify observers every time the
* getLastTickConnections returns a new value, even if the new value is null.
*
* @see #getLastTickConnections()
* @see #deleteRadioMediumObserver(Observer)
* @param observer
* New observer
*/
public abstract void addRadioMediumObserver(Observer observer);
/**
* Deletes an radio medium observer.
*
* @see #addRadioMediumObserver(Observer)
* @param observer
* Observer to delete
*/
public abstract void deleteRadioMediumObserver(Observer observer);
/**
* Returns all connections made during last tick loop.
*
* Typically a radio medium is a tick observer and transfers data between
* radios after each tick loop. When these calculations are finished, it will
* in turn notify all radio medium observers. A radio medium observer may get
* information about which connections were made by using this method. Observe
* that this method may return null of no connections were made.
*
* @see RadioConnection
* @return All connections made during last tick loop or null if none
*/
public abstract RadioConnection[] getLastTickConnections();
/**
* Set an overall connection logger. This logger will see all connections in
* the radio medium.
*
* @param logger
* New overall connection logger.
*/
public abstract void setConnectionLogger(ConnectionLogger logger);
/**
* Returns XML elements representing the current config of this radio medium.
* This is fetched by the simulator for example when saving a simulation
* configuration file. For example a radio medium may return user altered
* range parameters. This method should however not return state specific
* information such as a current radio status. (All nodes are restarted when
* loading a simulation.)
*
* @see #setConfigXML(Collection)
* @return XML elements representing the current radio medium config
*/
public abstract Collection<Element> getConfigXML();
/**
* Sets the current radio medium config depending on the given XML elements.
*
* @see #getConfigXML()
* @param configXML
* Config XML elements
* @return True if config was set successfully, false otherwise
*/
public abstract boolean setConfigXML(Collection<Element> configXML);
}

View file

@ -0,0 +1,512 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: SectionMoteMemory.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import org.apache.log4j.Logger;
import se.sics.cooja.MoteMemory;
/**
* Represents a mote memory consisting of non-overlapping
* memory sections. This memory also contains information
* about variable starts addresses.
* <p>
* When an unhandled memory segment is set a new section is
* automatically created for this segment.
* <p>
* @author Fredrik Osterlind
*/
public class SectionMoteMemory implements MoteMemory {
private static Logger logger = Logger.getLogger(SectionMoteMemory.class);
private Vector<MoteMemorySection> sections = new Vector<MoteMemorySection>();
private final Properties variableAddresses;
/**
* Create a new mote memory with information about which
* variables exist and their relative memory addresses.
*
* @param variableAddresses Variable addresses
*/
public SectionMoteMemory(Properties variableAddresses) {
this.variableAddresses = variableAddresses;
}
/**
* @return All variable names known and residing in this memory
*/
public String[] getVariableNames() {
String[] names = new String[variableAddresses.size()];
Enumeration nameEnum = variableAddresses.keys();
for (int i=0; i < variableAddresses.size(); i++) {
names[i] = (String) nameEnum.nextElement();
}
return names;
}
public void clearMemory() {
sections.clear();
}
public byte[] getMemorySegment(int address, int size) {
for (int i=0; i < sections.size(); i++) {
if (sections.elementAt(i).includesAddr(address) && sections.elementAt(i).includesAddr(address + size - 1)) {
return sections.elementAt(i).getMemorySegment(address, size);
}
}
return null;
}
public void setMemorySegment(int address, byte[] data) {
// TODO Creating overlapping memory sections possible
for (int i=0; i < sections.size(); i++) {
if (sections.elementAt(i).includesAddr(address) && sections.elementAt(i).includesAddr(address + data.length - 1)) {
sections.elementAt(i).setMemorySegment(address, data);
return;
}
}
sections.add(new MoteMemorySection(address, data));
}
public int getTotalSize() {
int totalSize = 0;
for (MoteMemorySection section: sections)
totalSize += section.getSize();
return totalSize;
}
/**
* Returns the total number of sections in this memory.
*
* @return Number of sections
*/
public int getNumberOfSections() {
return sections.size();
}
/**
* Removes a memory segment from this memory.
* The section containing the segment may be split into two sections.
*
* @param startAddr Start address
* @param size Length
*/
public void removeSegmentFromMemory(int startAddr, int size) {
for (MoteMemorySection section: sections)
// Find section containing segment to remove
if (section.includesAddr(startAddr) &&
section.includesAddr(startAddr + size - 1)) {
MoteMemorySection oldSection = section;
byte[] dataFirstPart = oldSection.getMemorySegment(
oldSection.startAddr,
(int) (startAddr - oldSection.startAddr)
);
byte[] dataSecondPart = oldSection.getMemorySegment(
startAddr + size,
(int) (oldSection.startAddr + oldSection.getSize() - (startAddr + size)));
MoteMemorySection newSectionFirstPart = new MoteMemorySection(oldSection.startAddr, dataFirstPart);
MoteMemorySection newSectionSecondPart = new MoteMemorySection(startAddr + size, dataSecondPart);
// Remove old section, add new sections
sections.remove(oldSection);
if (newSectionFirstPart.getSize() > 0)
sections.add(newSectionFirstPart);
if (newSectionSecondPart.getSize() > 0)
sections.add(newSectionSecondPart);
}
}
/**
* Get start address of section at given position.
*
* @param sectionNr Section position
* @return Start address of section
*/
public int getStartAddrOfSection(int sectionNr) {
if (sectionNr >= sections.size())
return 0;
return sections.elementAt(sectionNr).getStartAddr();
}
/**
* Get size of section at given position.
*
* @param sectionNr Section position
* @return Size of section
*/
public int getSizeOfSection(int sectionNr) {
if (sectionNr >= sections.size())
return 0;
return sections.elementAt(sectionNr).getSize();
}
/**
* Get data of section at given position.
*
* @param sectionNr Section position
* @return Data at section
*/
public byte[] getDataOfSection(int sectionNr) {
if (sectionNr >= sections.size())
return null;
return sections.elementAt(sectionNr).getData();
}
/**
* Returns a value of the integer variable with the given name.
*
* @param varName Name of integer variable
* @return Value of integer variable
*/
public int getIntValueOf(String varName) {
// Get start address of variable
if (!variableAddresses.containsKey(varName))
return -1;
int varAddr = ((Integer) variableAddresses.get(varName)).intValue();
byte[] varData = getMemorySegment(varAddr, 4);
int retVal = 0;
int pos = 0;
retVal += ((int) (varData[pos++] & 0xFF)) << 24;
retVal += ((int) (varData[pos++] & 0xFF)) << 16;
retVal += ((int) (varData[pos++] & 0xFF)) << 8;
retVal += ((int) (varData[pos++] & 0xFF)) << 0;
// TODO Check if small/big-endian when coming from JNI?
retVal = Integer.reverseBytes(retVal);
return retVal;
}
/**
* Set integer value of variable with given name.
*
* @param varName Name of integer variable
* @param newVal New value to set
*/
public void setIntValueOf(String varName, int newVal) {
// Get start address of variable
if (!variableAddresses.containsKey(varName))
return;
int varAddr = ((Integer) variableAddresses.get(varName)).intValue();
// TODO Check if small/big-endian when coming from JNI?
int newValToSet = Integer.reverseBytes(newVal);
// Create byte array
int pos = 0;
byte[] varData = new byte[4];
varData[pos++] = (byte) ((newValToSet & 0xFF000000) >> 24);
varData[pos++] = (byte) ((newValToSet & 0xFF0000) >> 16);
varData[pos++] = (byte) ((newValToSet & 0xFF00) >> 8);
varData[pos++] = (byte) ((newValToSet & 0xFF) >> 0);
setMemorySegment(varAddr, varData);
}
/**
* Returns a value of the byte variable with the given name.
*
* @param varName Name of byte variable
* @return Value of byte variable
*/
public byte getByteValueOf(String varName) {
// Get start address of variable
if (!variableAddresses.containsKey(varName))
return -1;
int varAddr = ((Integer) variableAddresses.get(varName)).intValue();
byte[] varData = getMemorySegment(varAddr, 1);
return varData[0];
}
/**
* Set byte value of variable with given name.
*
* @param varName Name of byte variable
* @param newVal New value to set
*/
public void setByteValueOf(String varName, byte newVal) {
// Get start address of variable
if (!variableAddresses.containsKey(varName))
return;
int varAddr = ((Integer) variableAddresses.get(varName)).intValue();
byte[] varData = new byte[1];
varData[0] = newVal;
setMemorySegment(varAddr, varData);
}
/**
* Returns byte array of given length and with the given name.
*
* @param varName Name of array
* @param length Length of array
* @return Data of array
*/
public byte[] getByteArray(String varName, int length) {
// Get start address of variable
if (!variableAddresses.containsKey(varName))
return null;
int varAddr = ((Integer) variableAddresses.get(varName)).intValue();
// TODO Check if small/big-endian when coming from JNI?
return getMemorySegment(varAddr, length);
}
/**
* Set byte array of the variable with the given name.
*
* @param varName Name of array
* @param data New data of array
*/
public void setByteArray(String varName, byte[] data) {
// Get start address of variable
if (!variableAddresses.containsKey(varName))
return;
int varAddr = ((Integer) variableAddresses.get(varName)).intValue();
// TODO Check if small/big-endian when coming from JNI?
setMemorySegment(varAddr, data);
}
/**
* A memory section represented of a byte array and a start address.
*
* @author Fredrik Osterlind
*/
private class MoteMemorySection {
private byte[] data = null;
private int startAddr;
/**
* Create a new memory section.
*
* @param startAddr Start address of section
* @param data Data of section
*/
public MoteMemorySection(int startAddr, byte[] data) {
this.startAddr = startAddr;
this.data = data;
}
/**
* Returns start address of this memory section.
*
* @return Start address
*/
public int getStartAddr() {
return startAddr;
}
/**
* Returns size of this memory section.
*
* @return Size
*/
public int getSize() {
return data.length;
}
/**
* Returns the entire byte array which defines this section.
*
* @return Byte array
*/
public byte[] getData() {
return data;
}
/**
* True if given address is part of this memory section.
*
* @param addr Address
* @return True if given address is part of this memory section, false otherwise
*/
public boolean includesAddr(int addr) {
if (data == null)
return false;
return (addr >= startAddr && addr < (startAddr + data.length));
}
/**
* Returns memory segment.
*
* @param addr Start address of memory segment
* @param size Size of memory segment
* @return Memory segment
*/
public byte[] getMemorySegment(int addr, int size) {
byte[] ret = new byte[size];
for (int i = 0; i < size; i++)
ret[i] = data[(int) (addr - startAddr + i)];
return ret;
}
/**
* Sets a memory segment.
* @param addr Start of memory segment
* @param data Data of memory segment
*/
public void setMemorySegment(int addr, byte[] data) {
int nonnull=0;
for (int i = 0; i < data.length; i++) {
if (data[i] != 0) nonnull++;
this.data[(int) (addr - startAddr + i)] = data[i];
}
}
public MoteMemorySection clone() {
byte[] dataClone = new byte[data.length];
for (int i=0; i < data.length; i++)
dataClone[i] = data[i];
MoteMemorySection clone = new MoteMemorySection(startAddr, dataClone);
return clone;
}
}
// EXPERIMENTAL AND DEBUG METHODS
public SectionMoteMemory clone() {
Vector<MoteMemorySection> clonedSections = new Vector<MoteMemorySection>();
for (int i=0; i < sections.size(); i++) {
clonedSections.add((MoteMemorySection) sections.elementAt(i).clone());
}
SectionMoteMemory clone = new SectionMoteMemory(variableAddresses);
clone.sections = clonedSections;
return clone;
}
protected byte[] getChecksum() {
MessageDigest messageDigest;
try {
messageDigest = MessageDigest.getInstance("MD5");
for (int i=0; i < sections.size(); i++) {
messageDigest.update(sections.get(i).data, 0, sections.get(i).getSize());
}
} catch (NoSuchAlgorithmException e) {
return null;
}
return messageDigest.digest();
}
protected Vector<Integer> getDifferenceAddressesOf(SectionMoteMemory anotherMem) {
Vector<Integer> differences = new Vector<Integer>();
if (this.getNumberOfSections() != anotherMem.getNumberOfSections()) {
logger.fatal("Number of section do not match!");
return null;
}
for (int i=0; i < sections.size(); i++) {
if (this.getSizeOfSection(i) != anotherMem.getSizeOfSection(i)) {
logger.fatal("Section " + i + " sizes do not match!");
return null;
}
if (this.getStartAddrOfSection(i) != anotherMem.getStartAddrOfSection(i)) {
logger.fatal("Section " + i + " start addresses do not match!");
return null;
}
for (int j=0; j < sections.get(i).getSize(); j++)
if (this.sections.get(i).data[j] != anotherMem.getDataOfSection(i)[j])
differences.add(new Integer(sections.get(i).startAddr + j));
System.err.println();
}
return differences;
}
protected void printMemory() {
for (int i=0; i < sections.size(); i++) {
System.err.print("Section[" + i + "]: ");
for (int j=0; j < sections.get(i).getSize(); j++)
System.err.print(sections.get(i).getData()[j] + ",");
System.err.println();
}
}
protected void printDifferences(SectionMoteMemory anotherMem) {
if (this.getNumberOfSections() != anotherMem.getNumberOfSections()) {
logger.fatal("Number of section do not match!");
return;
}
for (int i=0; i < sections.size(); i++) {
if (this.getSizeOfSection(i) != anotherMem.getSizeOfSection(i)) {
logger.fatal("Section " + i + " sizes do not match!");
return;
}
if (this.getStartAddrOfSection(i) != anotherMem.getStartAddrOfSection(i)) {
logger.fatal("Section " + i + " start addresses do not match!");
return;
}
System.err.print("Section[" + i + "]: ");
for (int j=0; j < sections.get(i).getSize(); j++)
if (this.sections.get(i).data[j] != anotherMem.getDataOfSection(i)[j])
System.err.print(j + ",");
System.err.println();
}
}
protected void printChecksum() {
byte[] checksum = this.getChecksum();
System.err.print("Checksum: ");
for (int i=0; i < checksum.length; i++) {
System.err.print(checksum[i] + ",");
}
System.err.println();
}
}

View file

@ -0,0 +1,735 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: Simulation.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import java.io.*;
import java.util.*;
import org.apache.log4j.Logger;
import org.jdom.*;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import se.sics.cooja.dialogs.*;
/**
* A simulation contains motes and ticks them one by one. When all motes has
* been ticked once, the simulation sleeps for some specified time, and the
* current simulation time is updated. Some observers (tick observers) are also
* notified.
*
* When observing the simulation itself, the simulation state, added or deleted
* motes etc are observed, as opposed to individual mote changes. Changes of
* individual motes should instead be observed via corresponding mote
* interfaces.
*
* @author Fredrik Osterlind
*/
public class Simulation extends Observable implements Runnable {
private Vector<Mote> motes = new Vector<Mote>();
private Vector<MoteType> moteTypes = new Vector<MoteType>();
private int delayTime = 100;
private int currentSimulationTime = 0;
private int tickTime = 1;
private String title = null;
// Radio Medium
private RadioMedium currentRadioMedium = null;
private static Logger logger = Logger.getLogger(Simulation.class);
private boolean isRunning = false;
private boolean stopSimulation = false;
private Thread thread = null;
// Tick observable
private class TickObservable extends Observable {
private void allTicksPerformed() {
setChanged();
notifyObservers();
}
}
private TickObservable tickObservable = new TickObservable();
/**
* Add tick observer. This observer is notified once every tick loop, that is,
* when all motes have been ticked.
*
* @see #deleteTickObserver(Observer)
* @param newObserver
* New observer
*/
public void addTickObserver(Observer newObserver) {
tickObservable.addObserver(newObserver);
}
/**
* Delete an existing tick observer.
*
* @see #addTickObserver(Observer)
* @param observer
* Observer to delete
*/
public void deleteTickObserver(Observer observer) {
tickObservable.deleteObserver(observer);
}
public void run() {
long lastStartTime = System.currentTimeMillis();
logger.info("Simulation main loop started, system time: " + lastStartTime);
isRunning = true;
// Notify observers simulation is starting
this.setChanged();
this.notifyObservers(this);
while (isRunning) {
try {
// Tick all motes
for (Mote moteToTick : motes) {
moteToTick.tick(currentSimulationTime);
}
// Increase simulation time
currentSimulationTime += tickTime;
// Notify tick observers
tickObservable.allTicksPerformed();
// Sleep
if (delayTime > 0)
Thread.sleep(delayTime);
if (stopSimulation) {
// We should only tick once (and we just did), so abort now
stopSimulation = false;
isRunning = false;
thread = null;
}
} catch (InterruptedException e) {
isRunning = false;
thread = null;
break;
} catch (IllegalArgumentException e) {
logger.warn("llegalArgumentException:" + e);
isRunning = false;
thread = null;
break;
} catch (IllegalMonitorStateException e) {
logger.warn("IllegalMonitorStateException:" + e);
isRunning = false;
thread = null;
break;
}
}
isRunning = false;
thread = null;
stopSimulation = false;
// Notify observers simulation has stopped
this.setChanged();
this.notifyObservers(this);
logger.info("Simulation main loop stopped, system time: "
+ System.currentTimeMillis() + "\tDuration: "
+ (System.currentTimeMillis() - lastStartTime) + " ms");
}
/**
* Creates a new simulation with a delay time of 1 second.
*/
public Simulation() {
// New simulation instance
// logger.fatal("WARNING ADDING 10000 BLINKER NODES NOW!!!");
// for (int i=0; i < 10000; i++)
// addMote(new BlinkerNode());
}
/**
* Starts this simulation (notifies observers).
*/
public void startSimulation() {
if (!isRunning()) {
thread = new Thread(this);
thread.start();
}
}
/**
* Stops this simulation (notifies observers).
*/
public void stopSimulation() {
if (isRunning()) {
stopSimulation = true;
thread.interrupt();
// Wait until simulation stops
if (Thread.currentThread() != thread)
while (thread != null && thread.isAlive()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
} // else logger.fatal("Could not stop simulation: isRunning=" + isRunning +
// ", thread=" + thread);
}
/**
* Starts simulation if stopped, ticks all motes once, and finally stop
* simulation again.
*/
public void tickSimulation() {
stopSimulation = true;
if (!isRunning()) {
thread = new Thread(this);
thread.start();
}
// Wait until simulation stops
while (thread != null && thread.isAlive()) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
}
}
}
/**
* Loads a simulation configuration from given file.
*
* When loading mote types, user must recompile the actual library of each
* type. User may also change mote type settings at this point.
*
* @see #saveSimulationConfig(File)
* @param file
* File to read
* @return New simulation or null if recompiling failed or aborted
* @throws UnsatisfiedLinkError
* If associated libraries could not be loaded
*/
public static Simulation loadSimulationConfig(File file)
throws UnsatisfiedLinkError {
Simulation newSim = null;
try {
// Open config file
SAXBuilder builder = new SAXBuilder();
Document doc = builder.build(file);
Element root = doc.getRootElement();
// Check that config file version is correct
if (!root.getName().equals("simulation")) {
logger.fatal("Not a COOJA simulation config xml file!");
return null;
}
// Build new simulation
Collection<Element> config = root.getChildren();
newSim = new Simulation();
boolean createdOK = newSim.setConfigXML(config);
if (!createdOK) {
logger.info("Simulation not loaded");
return null;
}
} catch (JDOMException e) {
logger.fatal("File not wellformed: " + e.getMessage());
return null;
} catch (IOException e) {
logger.fatal("No access to file: " + e.getMessage());
return null;
} catch (Exception e) {
logger.fatal("Exception when loading file: " + e);
e.printStackTrace();
return null;
}
return newSim;
}
/**
* Saves current simulation configuration to given file and notifies
* observers.
*
* @see #loadSimulationConfig(File file)
* @see #getConfigXML()
* @param file
* File to write
*/
public void saveSimulationConfig(File file) {
try {
// Create simulation XML
Element root = new Element("simulation");
root.addContent(getConfigXML());
// Create config
Document doc = new Document(root);
// Write to file
FileOutputStream out = new FileOutputStream(file);
XMLOutputter outputter = new XMLOutputter();
outputter.setFormat(Format.getPrettyFormat());
outputter.output(doc, out);
out.close();
logger.info("Saved to file: " + file.getAbsolutePath());
} catch (Exception e) {
logger.warn("Exception while saving simulation config: " + e);
}
this.setChanged();
this.notifyObservers(this);
}
/**
* Returns the current simulation config represented by XML elements. This
* config also includes the current radio medium, all mote types and motes.
*
* @see #saveSimulationConfig(File file)
* @return Current simulation config
*/
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Title
element = new Element("title");
element.setText(title);
config.add(element);
// Delay time
element = new Element("delaytime");
element.setText(Integer.toString(delayTime));
config.add(element);
// Simulation time
element = new Element("simtime");
element.setText(Integer.toString(currentSimulationTime));
config.add(element);
// Tick time
element = new Element("ticktime");
element.setText(Integer.toString(tickTime));
config.add(element);
// Radio Medium
element = new Element("radiomedium");
element.setText(currentRadioMedium.getClass().getName());
Collection radioMediumXML = currentRadioMedium.getConfigXML();
if (radioMediumXML != null)
element.addContent(radioMediumXML);
config.add(element);
// Mote types
for (MoteType moteType : getMoteTypes()) {
element = new Element("motetype");
element.setText(moteType.getClass().getName());
Collection moteTypeXML = moteType.getConfigXML();
if (moteTypeXML != null)
element.addContent(moteTypeXML);
config.add(element);
}
// Motes
for (Mote mote : motes) {
element = new Element("mote");
element.setText(mote.getClass().getName());
Collection moteXML = mote.getConfigXML();
if (moteXML != null)
element.addContent(moteXML);
config.add(element);
}
return config;
}
/**
* Sets the current simulation config depending on the given XML elements.
*
* @see #getConfigXML()
* @param configXML
* Config XML elements
*/
public boolean setConfigXML(Collection<Element> configXML) throws Exception {
// Parse elements
for (Element element : configXML) {
// Title
if (element.getName().equals("title")) {
title = element.getText();
}
// Delay time
if (element.getName().equals("delaytime")) {
delayTime = Integer.parseInt(element.getText());
}
// Simulation time
if (element.getName().equals("simtime")) {
currentSimulationTime = Integer.parseInt(element.getText());
}
// Tick time
if (element.getName().equals("ticktime")) {
tickTime = Integer.parseInt(element.getText());
}
// Radio medium
if (element.getName().equals("radiomedium")) {
String radioMediumClassName = element.getText().trim();
Class<? extends RadioMedium> radioMediumClass = GUI.currentGUI
.tryLoadClass(this, RadioMedium.class, radioMediumClassName);
if (radioMediumClass != null)
// Create radio medium specified in config
currentRadioMedium = radioMediumClass.newInstance();
else
logger.warn("Could not find radio medium class: "
+ radioMediumClassName);
// Show configure simulation dialog
boolean createdOK = CreateSimDialog.showDialog(GUI.frame, this);
if (!createdOK) {
logger.debug("Simulation not created, aborting");
throw new Exception("Load aborted by user");
}
// Check if radio medium specific config should be applied
if (radioMediumClassName
.equals(currentRadioMedium.getClass().getName())) {
currentRadioMedium.setConfigXML(element.getChildren());
} else {
logger
.info("Radio Medium changed - ignoring radio medium specific config");
}
}
// Mote type
if (element.getName().equals("motetype")) {
String moteTypeClassName = element.getText().trim();
Class<? extends MoteType> moteTypeClass = GUI.currentGUI.tryLoadClass(
this, MoteType.class, moteTypeClassName);
if (moteTypeClass == null) {
logger.fatal("Could not load mote type class: " + moteTypeClassName);
return false;
}
MoteType moteType = moteTypeClass.getConstructor((Class[]) null)
.newInstance();
boolean createdOK = moteType.setConfigXML(this, element.getChildren());
if (createdOK) {
addMoteType(moteType);
} else {
logger
.fatal("Mote type was not created: " + element.getText().trim());
throw new Exception("All mote types were not recreated");
}
}
// Mote
if (element.getName().equals("mote")) {
Class<? extends Mote> moteClass = GUI.currentGUI.tryLoadClass(this,
Mote.class, element.getText().trim());
Mote mote = moteClass.getConstructor((Class[]) null).newInstance();
if (mote.setConfigXML(this, element.getChildren())) {
addMote(mote);
} else {
logger.fatal("Mote was not created: " + element.getText().trim());
throw new Exception("All motes were not recreated");
}
}
}
return true;
}
/**
* Removes a mote from this simulation
*
* @param mote
* Mote to remove
*/
public void removeMote(Mote mote) {
if (isRunning()) {
stopSimulation();
motes.remove(mote);
startSimulation();
} else
motes.remove(mote);
currentRadioMedium.unregisterMote(mote, this);
this.setChanged();
this.notifyObservers(this);
}
/**
* Adds a mote to this simulation
*
* @param mote
* Mote to add
*/
public void addMote(Mote mote) {
if (isRunning()) {
stopSimulation();
motes.add(mote);
startSimulation();
} else
motes.add(mote);
currentRadioMedium.registerMote(mote, this);
this.setChanged();
this.notifyObservers(this);
}
/**
* Get a mote from this simulation.
*
* @param pos
* Position of mote
* @return Mote
*/
public Mote getMote(int pos) {
return motes.get(pos);
}
/**
* Returns number of motes in this simulation.
*
* @return Number of motes
*/
public int getMotesCount() {
return motes.size();
}
/**
* Returns all mote types in simulation.
*
* @return All mote types
*/
public Vector<MoteType> getMoteTypes() {
return moteTypes;
}
/**
* Returns mote type with given identifier.
*
* @param identifier
* Mote type identifier
* @return Mote type or null if not found
*/
public MoteType getMoteType(String identifier) {
for (MoteType moteType : getMoteTypes()) {
if (moteType.getIdentifier().equals(identifier))
return moteType;
}
return null;
}
/**
* Adds given mote type to simulation.
*
* @param newMoteType
*/
public void addMoteType(MoteType newMoteType) {
moteTypes.add(newMoteType);
this.setChanged();
this.notifyObservers(this);
}
/**
* Set delay time to delayTime. When all motes have been ticked, the
* simulation waits for this time before ticking again.
*
* @param delayTime
* New delay time (ms)
*/
public void setDelayTime(int delayTime) {
this.delayTime = delayTime;
this.setChanged();
this.notifyObservers(this);
}
/**
* Returns current delay time.
*
* @return Delay time (ms)
*/
public int getDelayTime() {
return delayTime;
}
/**
* Set simulation time to simulationTime.
*
* @param simulationTime
* New simulation time (ms)
*/
public void setSimulationTime(int simulationTime) {
currentSimulationTime = simulationTime;
this.setChanged();
this.notifyObservers(this);
}
/**
* Returns current simulation time.
*
* @return Simulation time (ms)
*/
public int getSimulationTime() {
return currentSimulationTime;
}
/**
* Set tick time to tickTime. The tick time is the simulated time every tick
* takes. When all motes have been ticked, current simulation time is
* increased with tickTime. Default tick time is 1 ms.
*
* @see #getTickTime()
* @see #getTickTimeInSeconds()
* @param tickTime
* New tick time (ms)
*/
public void setTickTime(int tickTime) {
this.tickTime = tickTime;
this.setChanged();
this.notifyObservers(this);
}
/**
* Changes radio medium of this simulation to the given.
*
* @param radioMedium
* New radio medium
*/
public void setRadioMedium(RadioMedium radioMedium) {
// Remove current radio medium from observing motes
if (currentRadioMedium != null)
for (int i = 0; i < motes.size(); i++)
currentRadioMedium.unregisterMote(motes.get(i), this);
// Change current radio medium to new one
if (radioMedium == null) {
logger.fatal("Radio medium could not be created!");
return;
}
this.currentRadioMedium = radioMedium;
// Add all current motes to be observered by new radio medium
for (int i = 0; i < motes.size(); i++)
currentRadioMedium.registerMote(motes.get(i), this);
}
/**
* Get currently used radio medium.
*
* @return Currently used radio medium
*/
public RadioMedium getRadioMedium() {
return currentRadioMedium;
}
/**
* Get current tick time (ms).
*
* @see #setTickTime(int)
* @return Current tick time (ms)
*/
public int getTickTime() {
return tickTime;
}
/**
* Get current tick time (seconds).
*
* @see #setTickTime(int)
* @return Current tick time (seconds)
*/
public double getTickTimeInSeconds() {
return ((double) tickTime) / 1000.0;
}
/**
* Return true is simulation is running.
*
* @return True if simulation is running
*/
public boolean isRunning() {
return isRunning && thread != null;
}
/**
* Get current simulation title (short description).
*
* @return Title
*/
public String getTitle() {
return title;
}
/**
* Set simulation title.
*
* @param title
* New title
*/
public void setTitle(String title) {
this.title = title;
}
}

View file

@ -0,0 +1,95 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: VisPlugin.java,v 1.1 2006/08/21 12:12:56 fros4943 Exp $
*/
package se.sics.cooja;
import javax.swing.JInternalFrame;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameListener;
/**
* Abstract class VisPlugin should be implemented by plugins for COOJA Simulator.
* By extending JInternalFrame, the visual apperence is decided by the plugin itself.
*
* An implemented plugin should be registered at runtime using the following method:
* GUI.registerPlugin(Class<? extends VisPlugin>, String)
*
* For example how to implement a plugin see classes SimControl or Vis2D.
*
* @author Fredrik Osterlind
*/
public abstract class VisPlugin extends JInternalFrame {
/**
* Sets frame title
* @param title Frame title
*/
public VisPlugin(String title) {
super(title, true, true, true, true);
final VisPlugin thisPlugin = this;
// Close via gui
setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
// Detect frame events
addInternalFrameListener(new InternalFrameListener() {
public void internalFrameClosing(InternalFrameEvent e) {
GUI.currentGUI.removePlugin(thisPlugin, true);
}
public void internalFrameClosed(InternalFrameEvent e) {
// NOP
}
public void internalFrameOpened(InternalFrameEvent e) {
// NOP
}
public void internalFrameIconified(InternalFrameEvent e) {
// NOP
}
public void internalFrameDeiconified(InternalFrameEvent e) {
// NOP
}
public void internalFrameActivated(InternalFrameEvent e) {
// NOP
}
public void internalFrameDeactivated(InternalFrameEvent e) {
// NOP
}
}
);
}
/**
* This method is called when an opened plugin is about to close.
* It should release any resources such as registered observers or
* opened interface visualizers.
*/
public abstract void closePlugin();
}

View file

@ -0,0 +1,109 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: VisPluginType.java,v 1.1 2006/08/21 12:12:57 fros4943 Exp $
*/
package se.sics.cooja;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
/**
* Annotation type to describe a plugin type.
*
* @author Fredrik Osterlind
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface VisPluginType {
public static final int UNDEFINED_PLUGIN = 0;
/**
* Mote Plugin
*
* A mote plugin concerns one specific mote.
*
* An example of such a plugin may be to display
* some mote information in a frame.
*
* Mote plugins can not be instantiated from the
* regular menu bar, but are instead started from
* other plugins, for example a visualizer that let's
* a user select a mote.
*
* When constructed, a mote plugin is given a Mote.
*
* If the current simulation is removed, so are
* all instances of this plugin.
*/
public static final int MOTE_PLUGIN = 1;
/**
* Simulation Plugin
*
* A simulation plugin concerns one specific simulation.
*
* An example of such a plugin may be to display
* number of motes and current simulation time in a window.
*
* Simulation plugins are available via the plugins menubar.
*
* When constructed, a simulation plugin is given the current
* active simulation.
*
* If the current simulation is removed, so are
* all instances of this plugin.
*/
public static final int SIM_PLUGIN = 2;
/**
* GUI Plugin
*
* A GUI plugin does not depend on the current simulation to function.
*
* An example of such a plugin may be a control panel
* where a user can control the current simulation.
*
* GUI plugins are available via the plugins menubar.
*
* When constructed, a GUI plugin is given the current GUI.
*/
public static final int GUI_PLUGIN = 3;
/**
* Simulation Standard Plugin
*
* This is treated exactly like a Simulation Plugin, with the
* only difference that this will automatically be opened
* when a new simulation is created.
*/
public static final int SIM_STANDARD_PLUGIN = 4;
int value();
}

View file

@ -0,0 +1,317 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiMote.java,v 1.1 2006/08/21 12:13:10 fros4943 Exp $
*/
package se.sics.cooja.contikimote;
import java.util.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
/**
* A Contiki mote executes an actual Contiki system via
* a loaded shared library and JNI.
* It contains a section mote memory, a mote interface handler and a
* Contiki mote type.
*
* The mote type is responsible for the connection to the loaded
* Contiki system.
*
* When ticked a Contiki mote polls all interfaces, copies the mote
* memory to the core, lets the Contiki system handle one event,
* fetches the updated memory and finally polls all interfaces again.
* The mote state is also updated during a mote tick.
*
* @author Fredrik Osterlind
*/
public class ContikiMote implements Mote {
private static Logger logger = Logger.getLogger(ContikiMote.class);
private ContikiMoteType myType = null;
private SectionMoteMemory myMemory = null;
private MoteInterfaceHandler myInterfaceHandler = null;
private Simulation mySim = null;
// Time to wake up if sleeping
private int wakeUpTime = 0;
private int myState = STATE_ACTIVE;
// State observable
private class StateObservable extends Observable {
private void stateChanged() {
setChanged();
notifyObservers();
}
}
private StateObservable stateObservable = new StateObservable();
/**
* Creates a new uninitialized Contiki mote.
*
* This mote needs at least a type, a memory, a mote interface handler
* and to be connected to a simulation.
*/
public ContikiMote() {
}
/**
* Creates a new mote of given type.
* Both the initial mote memory and the interface handler
* are supplied from the mote type.
*
* @param moteType Mote type
* @param sim Mote's simulation
*/
public ContikiMote(ContikiMoteType moteType, Simulation sim) {
this.mySim = sim;
this.myType = moteType;
this.myMemory = moteType.createInitialMemory();
this.myInterfaceHandler = new MoteInterfaceHandler((Mote) this, moteType.getMoteInterfaces());
myState = STATE_ACTIVE;
}
public void setState(int newState) {
if (myState == STATE_DEAD) {
return;
}
if (myState == STATE_ACTIVE && newState != STATE_ACTIVE) {
myState = newState;
stateObservable.stateChanged();
}
if (myState == STATE_LPM && newState != STATE_LPM) {
myState = newState;
stateObservable.stateChanged();
}
}
public int getState() {
return myState;
}
public void addStateObserver(Observer newObserver) {
stateObservable.addObserver(newObserver);
}
public void deleteStateObserver(Observer newObserver) {
stateObservable.deleteObserver(newObserver);
}
public MoteInterfaceHandler getInterfaces() {
return myInterfaceHandler;
}
public void setInterfaces(MoteInterfaceHandler newInterfaces) {
myInterfaceHandler = newInterfaces;
}
public MoteMemory getMemory() {
return myMemory;
}
public void setMemory(MoteMemory memory) {
myMemory = (SectionMoteMemory) memory;
}
public MoteType getType() {
return myType;
}
public void setType(MoteType type) {
myType = (ContikiMoteType) type;
}
public Simulation getSimulation() {
return mySim;
}
public void setSimulation(Simulation simulation) {
mySim = simulation;
}
/**
* Ticks this mote once. This is done by first polling all interfaces
* and letting them act on the stored memory before the memory is set. Then
* the mote is ticked, and the new memory is received.
* Finally all interfaces are allowing to act on the new memory in order to
* discover relevant changes. This method also checks if mote should go to sleep
* depending on Contiki specifics; pending timers and polled processes.
*
* @param simTime Current simulation time
*/
public void tick(int simTime) {
// If mote is dead, do nothing at all
if (getState() == STATE_DEAD)
return;
// If mote is sleeping and has a wake up time, should it wake up now?
if (getState() == STATE_LPM && wakeUpTime > 0 && wakeUpTime <= simTime) {
setState(STATE_ACTIVE);
wakeUpTime = 0;
}
// If mote is active..
if (getState() == STATE_ACTIVE) {
// Let all active interfaces act before tick
// Observe that each interface may put the mote to sleep at this point
myInterfaceHandler.doActiveActionsBeforeTick();
}
// And let passive interfaces act even if mote is sleeping
myInterfaceHandler.doPassiveActionsBeforeTick();
// If mote is still active, complete this tick
if (getState() == STATE_ACTIVE) {
// Copy mote memory to core
myType.setCoreMemory(myMemory);
// Tick node
myType.tick();
// Fetch new updated memory from core
myType.getCoreMemory(myMemory);
// Let all active interfaces act again after tick
myInterfaceHandler.doActiveActionsAfterTick();
}
// Finally let all passive interfaces act
myInterfaceHandler.doPassiveActionsAfterTick();
// If mote is awake, should it go to sleep?
if (getState() == STATE_ACTIVE) {
// Check if this mote should sleep (no more pending timers or processes to poll)
int processRunValue = myMemory.getIntValueOf("simProcessRunValue");
int etimersPending = myMemory.getIntValueOf("simEtimerPending");
int nextExpirationTime = myMemory.getIntValueOf("simNextExpirationTime");
if (processRunValue == 0 && etimersPending == 0) {
setState(STATE_LPM);
wakeUpTime = 0;
}
if (processRunValue == 0 && etimersPending == 1 && nextExpirationTime > 0) {
setState(STATE_LPM);
wakeUpTime = nextExpirationTime;
}
}
}
/**
* Returns the current Contiki mote config represented by XML elements.
* This config also includes all mote interface configs.
*
* @return Current simulation config
*/
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Mote type identifier
element = new Element("motetype_identifier");
element.setText(getType().getIdentifier());
config.add(element);
// Active interface configs (if any)
for (MoteInterface moteInterface: getInterfaces().getAllActiveInterfaces()) {
element = new Element("interface_config");
element.setText(moteInterface.getClass().getName());
Collection interfaceXML = moteInterface.getConfigXML();
if (interfaceXML != null) {
element.addContent(interfaceXML);
config.add(element);
}
}
// Passive interface configs (if any)
for (MoteInterface moteInterface: getInterfaces().getAllPassiveInterfaces()) {
element = new Element("interface_config");
element.setText(moteInterface.getClass().getName());
Collection interfaceXML = moteInterface.getConfigXML();
if (interfaceXML != null) {
element.addContent(interfaceXML);
config.add(element);
}
}
return config;
}
public boolean setConfigXML(Simulation simulation, Collection<Element> configXML) {
mySim = simulation;
myState = STATE_ACTIVE;
for (Element element: configXML) {
String name = element.getName();
if (name.equals("motetype_identifier")) {
myType = (ContikiMoteType) simulation.getMoteType(element.getText());
myMemory = myType.createInitialMemory();
myInterfaceHandler = new MoteInterfaceHandler((Mote) this, myType.getMoteInterfaces());
} else if (name.equals("interface_config")) {
Class<? extends MoteInterface> moteInterfaceClass =
GUI.currentGUI.tryLoadClass(this, MoteInterface.class, element.getText().trim());
if (moteInterfaceClass == null) {
logger.fatal("Could not load mote interface class: " + element.getText().trim());
return false;
}
MoteInterface moteInterface = myInterfaceHandler.getInterfaceOfType(moteInterfaceClass);
moteInterface.setConfigXML(element.getChildren());
}
}
return true;
}
public String toString() {
if (getInterfaces().getMoteID() != null) {
return "Contiki Mote, ID=" + getInterfaces().getMoteID().getMoteID();
} else
return "Contiki Mote, ID=null";
}
}

View file

@ -0,0 +1,48 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiMoteInterface.java,v 1.1 2006/08/21 12:13:09 fros4943 Exp $
*/
package se.sics.cooja.contikimote;
/**
* A Contiki mote interface has information about which, if any, core interfaces
* it needs.
*
* All classes implementing this interface should also define a static method:
* public String[] getCoreInterfaceDependencies() {
* ...
* }
*
* The method should return the names of all needed core interfaces.
*
* @author Fredrik Osterlind
*/
public interface ContikiMoteInterface {
}

View file

@ -0,0 +1,898 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiMoteType.java,v 1.1 2006/08/21 12:13:09 fros4943 Exp $
*/
package se.sics.cooja.contikimote;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.io.*;
import java.security.*;
import java.util.*;
import java.util.regex.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
/**
* The Contiki mote type holds the native library used to communicate with an
* underlying Contiki system. All communication with that system should always
* pass through this mote type.
* <p>
* This type also contains information about which processes, sensors and core
* interfaces a mote of this type has, as well as where the Contiki OS, COOJA
* core files and an optional user platform are located.
* <p>
* All core communication with the Contiki mote should be via this class. When a
* mote type is created it allocates a CoreComm to be used with this type, and
* loads a map file. The map file is used to map variable names to addresses.
* <p>
* When a new mote type is created an initialization function is run on the
* Contiki system in order to create the initial memory. When a new mote is
* created the createInitialMemory() method should be called to get this initial
* memory for the mote.
*
* @author Fredrik Osterlind
*/
@ClassDescription("Contiki Mote Type")
public class ContikiMoteType implements MoteType {
private static Logger logger = Logger.getLogger(ContikiMoteType.class);
/**
* Map file suffix
*/
final static public String mapSuffix = ".map";
/**
* Library file suffix
*/
final static public String librarySuffix = ".library";
/**
* Make dependency file suffix
*/
final static public String dependSuffix = ".a";
/**
* Temporary output directory
*/
final static public File tempOutputDirectory = new File("." + File.separatorChar + "obj_cooja" + File.separatorChar);
// Regular expressions for parsing the map file
final static private String bssSectionAddrRegExp = "^.bss[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String bssSectionSizeRegExp = "^.bss[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String dataSectionAddrRegExp = "^.data[ \t]*0x([0-9A-Fa-f]*)[ \t]*0x[0-9A-Fa-f]*[ \t]*$";
final static private String dataSectionSizeRegExp = "^.data[ \t]*0x[0-9A-Fa-f]*[ \t]*0x([0-9A-Fa-f]*)[ \t]*$";
final static private String varAddressRegExpPrefix = "^[ \t]*0x([0-9A-Fa-f]*)[ \t]*";
final static private String varAddressRegExpSuffix = "[ \t]*$";
final static private String varNameRegExp = "^[ \t]*(0x[0-9A-Fa-f]*)[ \t]*([^ ]*)[ \t]*$";
final static private String varSizeRegExpPrefix = "^";
final static private String varSizeRegExpSuffix = "[ \t]*(0x[0-9A-Fa-f]*)[ \t]*[^ ]*[ \t]*$";
// Mote type specific data
private String identifier = null;
private String description = null;
private String contikiBaseDir = null;
private String contikiCoreDir = null;
private Vector<File> userPlatformDirs = null;
private Vector<String> processes = null;
private Vector<String> sensors = null;
private Vector<String> coreInterfaces = null;
private Vector<Class<? extends MoteInterface>> moteInterfaces = null;
// Simulation holding this mote type
private Simulation mySimulation = null;
// Type specific class configuration
private PlatformConfig myConfig = null;
// Core communication variables
private String libraryClassName = null;
private int offsetRelToAbs = 0;
private CoreComm myCoreComm = null;
// Variable name to address mappings
private Properties varAddresses = new Properties();
// Map file contents
private Vector<String> mapContents = new Vector<String>();
// Initial memory for all motes of this type
private SectionMoteMemory initialMemory = null;
/**
* Creates a new uninitialized Contiki mote type. This mote type needs to load
* a library file and parse a map file before it can be used.
*/
public ContikiMoteType() {
}
/**
* Creates a new Contiki mote type. This type uses two external files: a map
* file for parsing relative addresses of Contiki variables (identifier +
* ".map") and a library file with an actual compiled Contiki system
* (identifier + ".library")
*
* @param identifier
* Unique identifier for this mote type
*/
public ContikiMoteType(String identifier) {
doInit(identifier);
}
public Mote generateMote(Simulation simulation) {
return new ContikiMote(this, simulation);
}
public boolean configureAndInit(JFrame parentFrame, Simulation simulation) {
return ContikiMoteTypeDialog.showDialog(parentFrame, simulation, this);
}
/**
* This is an mote type initialization method and should normally never be
* called by any other part than the mote type constructor. It is called from
* the constructor with an identifier argument. but not from the standard
* constructor. This method may be called from the simulator when loading
* configuration files, and the libraries must be recompiled.
*
* This method allocates a core communicator, loads the Contiki library file,
* loads and parses the map file, creates a variable name to address mapping
* of the Contiki system and finally creates the Contiki mote initial memory.
*
* @param identifier
* Mote type identifier
* @return True if initialization ok, false otherwise
*/
protected boolean doInit(String identifier) {
this.identifier = identifier;
if (myCoreComm != null) {
logger
.fatal("Core communicator not null. Is library already loaded? Aborting");
return false;
}
File libFile = new File(ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + identifier + librarySuffix);
File mapFile = new File(ContikiMoteType.tempOutputDirectory.getPath()
+ File.separatorChar + identifier + mapSuffix);
// Check that library file exists
if (!libFile.exists()) {
logger.fatal("Library file could not be found: " + libFile);
return false;
}
// Check that map file exists
if (!mapFile.exists()) {
logger.fatal("Map file could not be found: " + mapFile);
return false;
}
// Allocate core communicator class
libraryClassName = CoreComm.getAvailableClassName();
myCoreComm = CoreComm.createCoreComm(libraryClassName, libFile);
// Load map file
mapContents = loadMapFile(mapFile);
if (mapContents == null) {
logger.fatal("Map file could not be loaded: " + mapFile);
return false;
}
// Load variable addresses from Contiki system
varAddresses.clear();
Vector<String> varNames = getAllVariableNames();
for (String varName : varNames) {
int varAddress = getRelVarAddress(varName);
if (varAddress > 0) {
varAddresses.put(varName, new Integer(varAddress));
} else
logger.warn("Parsed Contiki variable '" + varName
+ "' but could not find address");
}
// Get offset between relative and absolute addresses
offsetRelToAbs = getReferenceAbsAddr()
- getRelVarAddr(mapContents, "referenceVar");
// Parse addresses of data and BSS memory sections
int relDataSectionAddr = loadRelDataSectionAddr(mapContents);
int dataSectionSize = loadDataSectionSize(mapContents);
int relBssSectionAddr = loadRelBssSectionAddr(mapContents);
int bssSectionSize = loadBssSectionSize(mapContents);
if (relDataSectionAddr <= 0 || dataSectionSize <= 0
|| relBssSectionAddr <= 0 || bssSectionSize <= 0) {
logger.fatal("Could not parse section addresses correctly");
return false;
}
// Create initial memory
byte[] initialDataSection = getCoreMemory(relDataSectionAddr
+ offsetRelToAbs, dataSectionSize);
byte[] initialBssSection = getCoreMemory(
relBssSectionAddr + offsetRelToAbs, bssSectionSize);
initialMemory = new SectionMoteMemory(varAddresses);
initialMemory.setMemorySegment(relDataSectionAddr, initialDataSection);
initialMemory.setMemorySegment(relBssSectionAddr, initialBssSection);
return false;
}
/**
* Ticks the currently loaded mote. This should not be used directly, but
* rather via ContikiMote.tick().
*/
public void tick() {
myCoreComm.tick();
}
/**
* Creates and returns a copy of this mote type's initial memory (just after
* the init function has been run). When a new mote is created it should get
* it's memory from here.
*
* @return Initial memory of a mote type
*/
public SectionMoteMemory createInitialMemory() {
return initialMemory.clone();
}
/**
* Copy given memory to the Contiki system. This should not be used directly,
* but instead via ContikiMote.setMemory().
*
* @param mem
* New memory
*/
public void setCoreMemory(SectionMoteMemory mem) {
for (int i = 0; i < mem.getNumberOfSections(); i++) {
setCoreMemory(mem.getStartAddrOfSection(i) + offsetRelToAbs, mem
.getSizeOfSection(i), mem.getDataOfSection(i));
}
}
/**
* Copy core memory to given memory. This should not be used directly, but
* instead via ContikiMote.getMemory().
*
* @param mem
* Memory to set
*/
public void getCoreMemory(SectionMoteMemory mem) {
for (int i = 0; i < mem.getNumberOfSections(); i++) {
int startAddr = mem.getStartAddrOfSection(i);
int size = mem.getSizeOfSection(i);
mem.setMemorySegment(startAddr, getCoreMemory(startAddr + offsetRelToAbs,
size));
}
}
public String getIdentifier() {
return identifier;
}
public void setIdentifier(String identifier) {
logger.warn("Contiki mote type is read-only");
}
/**
* @return Contiki mote type's library class name
*/
public String getLibraryClassName() {
return libraryClassName;
}
/**
* Get relative address of variable with given name.
*
* @param varName
* Name of variable
* @return Relative memory address of variable or -1 if not found
*/
protected int getRelVarAddress(String varName) {
int varAddr;
String varAddrString;
if ((varAddrString = varAddresses.getProperty(varName)) != null) {
varAddr = Integer.parseInt(varAddrString);
return varAddr;
}
String regExp = varAddressRegExpPrefix + varName + varAddressRegExpSuffix;
String retString = getFirstMatchGroup(mapContents, regExp, 1);
if (retString != null) {
varAddresses.setProperty(varName, Integer.toString(Integer.parseInt(
retString.trim(), 16)));
return Integer.parseInt(retString.trim(), 16);
} else
return -1;
}
private int getReferenceAbsAddr() {
return myCoreComm.getReferenceAbsAddr();
}
private byte[] getCoreMemory(int start, int length) {
return myCoreComm.getMemory(start, length);
}
private void setCoreMemory(int start, int length, byte[] mem) {
myCoreComm.setMemory(start, length, mem);
}
private static String getFirstMatchGroup(Vector<String> lines, String regexp,
int groupNr) {
Pattern pattern = Pattern.compile(regexp);
for (int i = 0; i < lines.size(); i++) {
Matcher matcher = pattern.matcher(lines.elementAt(i));
if (matcher.find()) {
return matcher.group(groupNr);
}
}
return null;
}
/**
* Returns all variable names in both data and BSS section by parsing the map
* file. These values should not be trusted completely as the parsing may
* fail.
*
* @return Variable names found in the data and bss section
*/
public Vector<String> getAllVariableNames() {
Vector<String> varNames = getAllVariableNames(mapContents,
loadRelDataSectionAddr(mapContents),
loadRelDataSectionAddr(mapContents) + loadDataSectionSize(mapContents));
varNames.addAll(getAllVariableNames(mapContents,
loadRelBssSectionAddr(mapContents), loadRelBssSectionAddr(mapContents)
+ loadBssSectionSize(mapContents)));
return varNames;
}
private Vector<String> getAllVariableNames(Vector<String> lines,
int startAddress, int endAddress) {
Vector<String> varNames = new Vector<String>();
Pattern pattern = Pattern.compile(varNameRegExp);
for (int i = 0; i < lines.size(); i++) {
Matcher matcher = pattern.matcher(lines.elementAt(i));
if (matcher.find()) {
if (Integer.decode(matcher.group(1)).intValue() >= startAddress
&& Integer.decode(matcher.group(1)).intValue() <= endAddress) {
varNames.add(matcher.group(2));
}
}
}
return varNames;
}
protected int getVariableSize(Vector<String> lines, String varName) {
Pattern pattern = Pattern.compile(varSizeRegExpPrefix + varName
+ varSizeRegExpSuffix);
for (int i = 0; i < lines.size(); i++) {
Matcher matcher = pattern.matcher(lines.elementAt(i));
if (matcher.find()) {
return Integer.decode(matcher.group(1));
}
}
return -1;
}
private static int loadRelDataSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else
return 0;
}
private static int loadDataSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, dataSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else
return 0;
}
private static int loadRelBssSectionAddr(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionAddrRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else
return 0;
}
private static int loadBssSectionSize(Vector<String> mapFile) {
String retString = getFirstMatchGroup(mapFile, bssSectionSizeRegExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else
return 0;
}
private static int getRelVarAddr(Vector<String> mapContents, String varName) {
String regExp = varAddressRegExpPrefix + varName + varAddressRegExpSuffix;
String retString = getFirstMatchGroup(mapContents, regExp, 1);
if (retString != null)
return Integer.parseInt(retString.trim(), 16);
else
return 0;
}
private static Vector<String> loadMapFile(File mapFile) {
Vector<String> mapContents = new Vector<String>();
try {
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(mapFile)));
while (in.ready()) {
mapContents.add(in.readLine());
}
} catch (FileNotFoundException e) {
logger.fatal("File not found: " + e);
return null;
} catch (IOException e) {
logger.fatal("IO error: " + e);
return null;
}
return mapContents;
}
/**
* Returns simulation holding this mote type
*
* @return Simulation
*/
public Simulation getSimulation() {
return mySimulation;
}
/**
* Sets simulation holding this mote type
*
* @param simulation
* Simulation holding this mote type
*/
public void setSimulation(Simulation simulation) {
mySimulation = simulation;
}
public String getDescription() {
return description;
}
public void setDescription(String newDescription) {
description = newDescription;
}
/**
* Returns path to contiki base dir
*
* @return String containing path
*/
public String getContikiBaseDir() {
return contikiBaseDir;
}
/**
* Sets contiki base dir to path.
*
* @param path
* Contiki base dir
*/
public void setContikiBaseDir(String path) {
contikiBaseDir = path;
}
/**
* Returns path to contiki core dir
*
* @return String containing path
*/
public String getContikiCoreDir() {
return contikiCoreDir;
}
/**
* Sets contiki core dir to path.
*
* @param path
* Contiki core dir
*/
public void setContikiCoreDir(String path) {
contikiCoreDir = path;
}
/**
* Returns user platform directories
*
* @return User platform directories
*/
public Vector<File> getUserPlatformDirs() {
return userPlatformDirs;
}
/**
* Sets user platform directories.
*
* @param dirs
* New user platform directories
*/
public void setUserPlatformDirs(Vector<File> dirs) {
userPlatformDirs = dirs;
}
public PlatformConfig getConfig() {
return myConfig;
}
/**
* Sets mote type platform configuration. This may differ from the general
* simulator platform configuration.
*
* @param moteTypeConfig
* Platform configuration
*/
public void setConfig(PlatformConfig moteTypeConfig) {
myConfig = moteTypeConfig;
}
/**
* Returns all processes of this mote type
*
* @return All processes
*/
public Vector<String> getProcesses() {
return processes;
}
/**
* Set startup processes
*
* @param processes
* New startup processes
*/
public void setProcesses(Vector<String> processes) {
this.processes = processes;
}
/**
* Returns all sensors of this mote type
*
* @return All sensors
*/
public Vector<String> getSensors() {
return sensors;
}
/**
* Set sensors
*
* @param sensors
* New sensors
*/
public void setSensors(Vector<String> sensors) {
this.sensors = sensors;
}
/**
* Returns all core interfaces of this mote type
*
* @return All core interfaces
*/
public Vector<String> getCoreInterfaces() {
return coreInterfaces;
}
/**
* Set core interfaces
*
* @param coreInterfaces
* New core interfaces
*/
public void setCoreInterfaces(Vector<String> coreInterfaces) {
this.coreInterfaces = coreInterfaces;
}
/**
* Returns all mote interfaces of this mote type
*
* @return All mote interfaces
*/
public Vector<Class<? extends MoteInterface>> getMoteInterfaces() {
return moteInterfaces;
}
/**
* Set mote interfaces of this mote type
*
* @param moteInterfaces
* New mote interfaces
*/
public void setMoteInterfaces(
Vector<Class<? extends MoteInterface>> moteInterfaces) {
this.moteInterfaces = moteInterfaces;
}
/**
* Create a checksum of file. Used for checking if needed files are unchanged
* when loading a saved simulation.
*
* @param file
* File containg data to checksum
* @return Checksum
*/
protected byte[] createChecksum(File file) {
int bytesRead = 1;
byte[] readBytes = new byte[128];
MessageDigest messageDigest;
try {
InputStream fileInputStream = new FileInputStream(file);
messageDigest = MessageDigest.getInstance("MD5");
while (bytesRead > 0) {
bytesRead = fileInputStream.read(readBytes);
if (bytesRead > 0)
messageDigest.update(readBytes, 0, bytesRead);
}
fileInputStream.close();
} catch (NoSuchAlgorithmException e) {
return null;
} catch (IOException e) {
return null;
}
return messageDigest.digest();
}
/**
* Returns a panel with interesting data for this mote type.
*
* @return Mote type visualizer
*/
public JPanel getTypeVisualizer() {
JPanel panel = new JPanel();
JLabel label = new JLabel();
JPanel smallPane;
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// Identifier
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Identifier");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(identifier);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Description
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Description");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(description);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Contiki dir
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Contiki path");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(contikiBaseDir);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Library class name
smallPane = new JPanel(new BorderLayout());
label = new JLabel("JNI Class");
smallPane.add(BorderLayout.WEST, label);
label = new JLabel(libraryClassName);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
// Processes
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Processes");
smallPane.add(BorderLayout.WEST, label);
panel.add(smallPane);
for (String process : processes) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(process);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
}
// Sensors
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Sensors");
smallPane.add(BorderLayout.WEST, label);
panel.add(smallPane);
for (String sensor : sensors) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(sensor);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
}
// Core Interfaces
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Core interfaces");
smallPane.add(BorderLayout.WEST, label);
panel.add(smallPane);
for (String mInterface : coreInterfaces) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(mInterface);
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
}
// Mote Interfaces
smallPane = new JPanel(new BorderLayout());
label = new JLabel("Mote interfaces");
smallPane.add(BorderLayout.WEST, label);
panel.add(smallPane);
for (Class moteInterface : moteInterfaces) {
smallPane = new JPanel(new BorderLayout());
label = new JLabel(moteInterface.getSimpleName());
smallPane.add(BorderLayout.EAST, label);
panel.add(smallPane);
}
panel.add(Box.createRigidArea(new Dimension(0, 5)));
return panel;
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Identifier
element = new Element("identifier");
element.setText(getIdentifier());
config.add(element);
// Description
element = new Element("description");
element.setText(getDescription());
config.add(element);
// Contiki base directory
element = new Element("contikibasedir");
element.setText(getContikiBaseDir());
config.add(element);
// Contiki core directory
element = new Element("contikicoredir");
element.setText(getContikiCoreDir());
config.add(element);
// User platform directory
for (File userPlatform: userPlatformDirs) {
element = new Element("userplatformdir");
element.setText(userPlatform.getPath());
config.add(element);
}
// Contiki processes
for (String process : getProcesses()) {
element = new Element("process");
element.setText(process);
config.add(element);
}
// Contiki sensors
for (String sensor : getSensors()) {
element = new Element("sensor");
element.setText(sensor);
config.add(element);
}
// Mote interfaces
for (Class moteInterface : getMoteInterfaces()) {
element = new Element("moteinterface");
element.setText(moteInterface.getName());
config.add(element);
}
// Core interfaces
for (String coreInterface : getCoreInterfaces()) {
element = new Element("coreinterface");
element.setText(coreInterface);
config.add(element);
}
return config;
}
public boolean setConfigXML(Simulation simulation,
Collection<Element> configXML) {
userPlatformDirs = new Vector<File>();
processes = new Vector<String>();
sensors = new Vector<String>();
coreInterfaces = new Vector<String>();
moteInterfaces = new Vector<Class<? extends MoteInterface>>();
mySimulation = simulation;
for (Element element : configXML) {
String name = element.getName();
if (name.equals("identifier")) {
identifier = element.getText();
} else if (name.equals("description")) {
description = element.getText();
} else if (name.equals("contikibasedir")) {
contikiBaseDir = element.getText();
} else if (name.equals("contikicoredir")) {
contikiCoreDir = element.getText();
} else if (name.equals("userplatformdir")) {
userPlatformDirs.add(new File(element.getText()));
} else if (name.equals("process")) {
processes.add(element.getText());
} else if (name.equals("sensor")) {
sensors.add(element.getText());
} else if (name.equals("coreinterface")) {
coreInterfaces.add(element.getText());
} else if (name.equals("moteinterface")) {
Class<? extends MoteInterface> moteInterfaceClass =
GUI.currentGUI.tryLoadClass(this, MoteInterface.class, element.getText().trim());
if (moteInterfaceClass == null) {
logger.warn("Can't find mote interface class: " + element.getText());
} else
moteInterfaces.add(moteInterfaceClass);
} else {
logger.fatal("Unrecognized entry in loaded configuration: " + name);
}
}
boolean createdOK = configureAndInit(GUI.frame, simulation);
return createdOK;
}
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,136 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiBeeper.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.util.Collection;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.Beeper;
/**
* Ths class represents a beeper.
*
* It needs read access to the following core variables:
* <ul>
* <li>char simBeeped (1=on, else off)
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>beep_interface
* </ul>
* <p>
* This observable is changed and notifies observers whenever the beeper changes
* state.
*
* @author Fredrik Osterlind
*/
public class ContikiBeeper extends Beeper implements ContikiMoteInterface {
private Mote mote = null;
private SectionMoteMemory moteMem = null;
private static Logger logger = Logger.getLogger(ContikiBeeper.class);
/**
* Assuming beep always lasts for 0.1 seconds. ESB measured energy
* consumption: 16.69 mA. Total energy consumption of a beep is then:
* 0.1*16.69
*/
private final double ENERGY_CONSUMPTION_BEEP;
private double myEnergyConsumption = 0.0;
private boolean justBeeped = false;
/**
* Creates an interface to the beeper at mote.
*
* @param mote
* Beeper's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiBeeper(Mote mote) {
// Read class configurations of this mote type
ENERGY_CONSUMPTION_BEEP = mote.getType().getConfig().getDoubleValue(
ContikiBeeper.class, "BEEP_CONSUMPTION_mQ");
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
}
public boolean isBeeping() {
return justBeeped;
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"beep_interface"};
}
public void doActionsBeforeTick() {
// Nothing to do
justBeeped = false;
}
public void doActionsAfterTick() {
if (moteMem.getByteValueOf("simBeeped") == 1) {
this.setChanged();
this.notifyObservers(mote);
justBeeped = true;
moteMem.setByteValueOf("simBeeped", (byte) 0);
myEnergyConsumption = ENERGY_CONSUMPTION_BEEP;
} else
myEnergyConsumption = 0.0;
}
public JPanel getInterfaceVisualizer() {
return null;
}
public void releaseInterfaceVisualizer(JPanel panel) {
}
public double energyConsumptionPerTick() {
return myEnergyConsumption;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,176 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiButton.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.awt.event.*;
import java.util.Collection;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.Button;
/**
* This class represents a button.
*
* It needs read/write access to the following core variables:
* <ul>
* <li>char simButtonIsDown (1=down, else up)
* <li>char simButtonChanged (1=changed, else not changed)
* <li>char simButtonIsActive (1=active, else inactive)
* </ul>
* Dependency core interfaces are:
* <ul>
* <li>button_interface
* </ul>
* <p>
* This observable notifies observers when the button changes state (between
* pressed and released).
*
* @author Fredrik Osterlind
*/
public class ContikiButton extends Button implements ContikiMoteInterface {
private SectionMoteMemory moteMem;
private Mote mote;
private boolean shouldBeReleased = false;
private static Logger logger = Logger.getLogger(ContikiButton.class);
private final boolean RAISES_EXTERNAL_INTERRUPT;
/**
* Creates an interface to the button at mote.
*
* @param mote
* Button's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiButton(Mote mote) {
// Read class configurations of this mote type
RAISES_EXTERNAL_INTERRUPT = mote.getType().getConfig()
.getBooleanValue(ContikiButton.class, "EXTERNAL_INTERRUPT_bool");
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"button_interface"};
}
/**
* Clicks button. Button will be down for one tick, and then released.
*/
public void clickButton() {
pressButton();
shouldBeReleased = true;
}
public void releaseButton() {
moteMem.setByteValueOf("simButtonIsDown", (byte) 0);
if (moteMem.getByteValueOf("simButtonIsActive") == 1) {
moteMem.setByteValueOf("simButtonChanged", (byte) 1);
// If mote is inactive, wake it up
if (RAISES_EXTERNAL_INTERRUPT)
mote.setState(Mote.STATE_ACTIVE);
setChanged();
notifyObservers();
}
}
public void pressButton() {
moteMem.setByteValueOf("simButtonIsDown", (byte) 1);
if (moteMem.getByteValueOf("simButtonIsActive") == 1) {
moteMem.setByteValueOf("simButtonChanged", (byte) 1);
// If mote is inactive, wake it up
if (RAISES_EXTERNAL_INTERRUPT)
mote.setState(Mote.STATE_ACTIVE);
setChanged();
notifyObservers();
}
}
public boolean isPressed() {
return moteMem.getByteValueOf("simButtonIsDown") == 1;
}
public void doActionsBeforeTick() {
// Nothing to do
}
public void doActionsAfterTick() {
// If a button is pressed and should be clicked, release it now
if (shouldBeReleased) {
releaseButton();
shouldBeReleased = false;
}
}
public JPanel getInterfaceVisualizer() {
JPanel panel = new JPanel();
final JButton clickButton = new JButton("Click button");
panel.add(clickButton);
clickButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
clickButton();
}
});
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
}
public double energyConsumptionPerTick() {
return 0.0;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,117 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiClock.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.util.Collection;
import javax.swing.JPanel;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.Clock;
/**
* The class represents a clock and controls the core time.
*
* It needs read/write access to the following core variables:
* <ul>
* <li>int simCurrentTime
* </ul>
* Dependency core interfaces are:
* <ul>
* <li>clock_interface
* </ul>
* <p>
* This observable never updates.
*
* @author Fredrik Osterlind
*/
public class ContikiClock extends Clock implements ContikiMoteInterface {
private Mote mote = null;
private SectionMoteMemory moteMem = null;
private int timeDrift = 0;
/**
* Creates a time connected to mote.
*
* @param mote
* Mote to connect this time to.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiClock(Mote mote) {
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"clock_interface"};
}
public void setTime(int newTime) {
moteMem.setIntValueOf("simCurrentTime", newTime);
}
public int getTime() {
return moteMem.getIntValueOf("simCurrentTime");
}
public void doActionsBeforeTick() {
// Update core time to correspond with the simulation time
setTime((int) mote.getSimulation().getSimulationTime() + timeDrift);
}
public void doActionsAfterTick() {
// Nothing to do
}
public JPanel getInterfaceVisualizer() {
return null;
}
public void releaseInterfaceVisualizer(JPanel panel) {
}
public double energyConsumptionPerTick() {
return 0.0;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,187 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiIPAddress.java,v 1.1 2006/08/21 12:13:04 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.IPAddress;
/**
* This class represents an uIP IP address.
*
* It needs write access to the following core variables:
* <ul>
* <li>char simIPa
* <li>char simIPb
* <li>char simIPc
* <li>char simIPd
* <li>char simIPChanged (1 if new IP should be set)
* </ul>
* <p>
* The new IP will be "simIPa.simIPb.simIPc.simIPd". Dependency core interfaces
* are:
* <ul>
* <li>ip_interface
* </ul>
*
* This observable notifies observers if the IP address is set or changed.
*
* @author Fredrik Osterlind
*/
public class ContikiIPAddress extends IPAddress implements ContikiMoteInterface {
private SectionMoteMemory moteMem = null;
private static Logger logger = Logger.getLogger(ContikiIPAddress.class);
private boolean setIP;
char a = 0, b = 0, c = 0, d = 0;
/**
* Creates an interface to the IP address at mote.
*
* @param mote
* IP address' mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiIPAddress(Mote mote) {
this.moteMem = (SectionMoteMemory) mote.getMemory();
setIP = false;
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"ip_interface"};
}
public String getIPString() {
return "" + (int) a + "." + (int) b + "." + (int) c + "." + (int) d;
}
public void setIPString(String ipAddress) {
String[] ipArray = ipAddress.split("\\.");
if (ipArray.length < 4) {
logger.warn("Could not set ip address (" + ipAddress + ")");
} else
setIPNumber((char) Integer.parseInt(ipArray[0]), (char) Integer
.parseInt(ipArray[1]), (char) Integer.parseInt(ipArray[2]),
(char) Integer.parseInt(ipArray[3]));
}
public void setIPNumber(char a, char b, char c, char d) {
setIP = true;
this.a = a;
this.b = b;
this.c = c;
this.d = d;
}
public void doActionsBeforeTick() {
if (setIP) {
setIP = false;
moteMem.setByteValueOf("simIPa", (byte) a);
moteMem.setByteValueOf("simIPb", (byte) b);
moteMem.setByteValueOf("simIPc", (byte) c);
moteMem.setByteValueOf("simIPd", (byte) d);
moteMem.setByteValueOf("simIPChanged", (byte) 1);
setChanged();
notifyObservers();
}
}
public void doActionsAfterTick() {
// Nothing to do
}
public JPanel getInterfaceVisualizer() {
JPanel panel = new JPanel();
final JLabel ipLabel = new JLabel();
ipLabel.setText("Current address: " + (int) a + "." + (int) b + "."
+ (int) c + "." + (int) d);
panel.add(ipLabel);
Observer observer;
this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) {
ipLabel.setText("Current address: " + (int) a + "." + (int) b + "."
+ (int) c + "." + (int) d);
}
});
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer);
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) {
logger.fatal("Error when releasing panel, observer is null");
return;
}
this.deleteObserver(observer);
}
public double energyConsumptionPerTick() {
// Virtual interface, does not require any energy
return 0.0;
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Infinite boolean
element = new Element("ipv4address");
element.setText(getIPString());
config.add(element);
return config;
}
public void setConfigXML(Collection<Element> configXML) {
for (Element element : configXML) {
if (element.getName().equals("ipv4address")) {
setIPString(element.getText());
}
}
}
}

View file

@ -0,0 +1,260 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiLED.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.awt.*;
import java.util.*;
import javax.swing.JPanel;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.LED;
/**
* This class represents three mote LEDs.
*
* It needs read access to the following core variables:
* <ul>
* <li>char simLedsValue
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>leds_interface
* </ul>
* <p>
* This observable is changed and notifies observers whenever any led has
* changed.
*
* @author Fredrik Osterlind
*/
public class ContikiLED extends LED implements ContikiMoteInterface {
private static Logger logger = Logger.getLogger(ContikiLED.class);
private Mote mote = null;
private SectionMoteMemory moteMem = null;
private byte oldLedValue = 0;
private static final byte LEDS_GREEN = 1;
private static final byte LEDS_YELLOW = 2;
private static final byte LEDS_RED = 4;
private static final Color DARK_GREEN = new Color(0, 100, 0);
private static final Color DARK_YELLOW = new Color(100, 100, 0);
private static final Color DARK_RED = new Color(100, 0, 0);
private static final Color GREEN = new Color(0, 255, 0);
private static final Color YELLOW = new Color(255, 255, 0);
private static final Color RED = new Color(255, 0, 0);
private double myEnergyConsumption = 0.0;
/**
* Approximate energy consumption of a green led (mA). ESB measured value:
* 5.69 mA. TODO Measure energy consumption
*/
public final double ENERGY_CONSUMPTION_GREEN_LED;
/**
* Approximate energy consumption of a yellow led (mA). ESB measured value:
* 5.69 mA. TODO Measure energy consumption
*/
public final double ENERGY_CONSUMPTION_YELLOW_LED;
/**
* Approximate energy consumption of a red led (mA). ESB measured value: 5.69
* mA.
*/
public final double ENERGY_CONSUMPTION_RED_LED;
private double energyOfGreenLedPerTick = -1;
private double energyOfYellowLedPerTick = -1;
private double energyOfRedLedPerTick = -1;
public ContikiLED() {
ENERGY_CONSUMPTION_GREEN_LED = 0;
ENERGY_CONSUMPTION_YELLOW_LED = 0;
ENERGY_CONSUMPTION_RED_LED = 0;
}
/**
* Creates an interface to the led at mote.
*
* @param mote
* Led's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiLED(Mote mote) {
// Read class configurations of this mote type
ENERGY_CONSUMPTION_GREEN_LED = mote.getType().getConfig()
.getDoubleValue(ContikiLED.class, "GREEN_LED_CONSUMPTION_mA");
ENERGY_CONSUMPTION_YELLOW_LED = mote.getType().getConfig()
.getDoubleValue(ContikiLED.class, "YELLOW_LED_CONSUMPTION_mA");
ENERGY_CONSUMPTION_RED_LED = mote.getType().getConfig()
.getDoubleValue(ContikiLED.class, "RED_LED_CONSUMPTION_mA");
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
if (energyOfGreenLedPerTick < 0) {
energyOfGreenLedPerTick = ENERGY_CONSUMPTION_GREEN_LED
* mote.getSimulation().getTickTimeInSeconds();
energyOfYellowLedPerTick = ENERGY_CONSUMPTION_YELLOW_LED
* mote.getSimulation().getTickTimeInSeconds();
energyOfRedLedPerTick = ENERGY_CONSUMPTION_RED_LED
* mote.getSimulation().getTickTimeInSeconds();
}
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"leds_interface"};
}
public boolean isAnyOn() {
return oldLedValue > 0;
}
public boolean isGreenOn() {
return (oldLedValue & LEDS_GREEN) > 0;
}
public boolean isYellowOn() {
return (oldLedValue & LEDS_YELLOW) > 0;
}
public boolean isRedOn() {
return (oldLedValue & LEDS_RED) > 0;
}
public void doActionsBeforeTick() {
// Nothing to do
}
public void doActionsAfterTick() {
if (checkLedStatus()) {
this.setChanged();
this.notifyObservers(mote);
}
}
private boolean checkLedStatus() {
boolean ledChanged;
byte newLedsValue = moteMem.getByteValueOf("simLedsValue");
if (newLedsValue != oldLedValue) {
ledChanged = true;
} else {
ledChanged = false;
}
myEnergyConsumption = 0.0;
if ((newLedsValue & LEDS_GREEN) > 0)
myEnergyConsumption += energyOfGreenLedPerTick;
if ((newLedsValue & LEDS_YELLOW) > 0)
myEnergyConsumption += energyOfYellowLedPerTick;
if ((newLedsValue & LEDS_RED) > 0)
myEnergyConsumption += energyOfRedLedPerTick;
oldLedValue = newLedsValue;
return ledChanged;
}
public JPanel getInterfaceVisualizer() {
final JPanel panel = new JPanel() {
public void paintComponent(Graphics g) {
super.paintComponent(g);
if (isGreenOn()) {
g.setColor(GREEN);
g.fillOval(20, 20, 20, 20);
} else {
g.setColor(DARK_GREEN);
g.fillOval(20, 20, 20, 20);
}
if (isYellowOn()) {
g.setColor(YELLOW);
g.fillOval(60, 20, 20, 20);
} else {
g.setColor(DARK_YELLOW);
g.fillOval(60, 20, 20, 20);
}
if (isRedOn()) {
g.setColor(RED);
g.fillOval(100, 20, 20, 20);
} else {
g.setColor(DARK_RED);
g.fillOval(100, 20, 20, 20);
}
}
};
Observer observer;
this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) {
panel.repaint();
}
});
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer);
panel.setMinimumSize(new Dimension(140, 60));
panel.setPreferredSize(new Dimension(140, 60));
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) {
logger.fatal("Error when releasing panel, observer is null");
return;
}
this.deleteObserver(observer);
}
public double energyConsumptionPerTick() {
return myEnergyConsumption;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,169 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiLog.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.awt.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.Log;
/**
* The class Log is an abstract interface to a mote's logging output. It needs
* read access to the following core variables:
* <ul>
* <li>char simLoggedFlag
* (1=mote has new outgoing log messages, else no new)
* <li>int simLoggedLength
* (length of new log message)
* <li>byte[] simLoggedData (data of new log messages)
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>simlog_interface
* </ul>
* <p>
* This observable is changed and notifies observers whenever a log message has
* been received from the core (checked after each tick). The public method
* getLastLogMessages gives access to the last log message(s).
*
* @author Fredrik Osterlind
*/
public class ContikiLog extends Log implements ContikiMoteInterface {
private static Logger logger = Logger.getLogger(ContikiLog.class);
private Mote mote = null;
private SectionMoteMemory moteMem = null;
private String lastLogMessage = null;
/**
* Creates an interface to mote's logging output.
*
* @param mote Log's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiLog(Mote mote) {
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
}
public static String[] getCoreInterfaceDependencies() {
return new String[] { "simlog_interface" };
}
public void doActionsBeforeTick() {
// Nothing to do
}
public void doActionsAfterTick() {
if (moteMem.getByteValueOf("simLoggedFlag") == 1) {
int totalLength = moteMem.getIntValueOf("simLoggedLength");
byte[] bytes = moteMem.getByteArray("simLoggedData", totalLength);
char[] chars = new char[bytes.length];
for (int i=0; i < chars.length; i++)
chars[i] = (char) bytes[i];
String message = String.valueOf(chars);
lastLogMessage = message;
moteMem.setByteValueOf("simLoggedFlag", (byte) 0);
moteMem.setIntValueOf("simLoggedLength", (int) 0);
this.setChanged();
this.notifyObservers(mote);
}
}
public String getLastLogMessages() {
return lastLogMessage;
}
public JPanel getInterfaceVisualizer() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
final JTextArea logTextPane = new JTextArea();
logTextPane.setOpaque(false);
logTextPane.setEditable(false);
if (lastLogMessage == null)
logTextPane.setText("");
else
logTextPane.append(lastLogMessage);
Observer observer;
this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) {
logTextPane.append(lastLogMessage);
logTextPane.setCaretPosition(logTextPane.getDocument().getLength());
}
});
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer);
JScrollPane scrollPane = new JScrollPane(logTextPane);
scrollPane.setPreferredSize(new Dimension(100,100));
panel.add(BorderLayout.NORTH, new JLabel("Last log messages:"));
panel.add(BorderLayout.CENTER, scrollPane);
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) {
logger.fatal("Error when releasing panel, observer is null");
return;
}
this.deleteObserver(observer);
}
public double energyConsumptionPerTick() {
// Does not require energy
return 0.0;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,167 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiMoteID.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.MoteID;
/**
* Ths class represents a mote ID number.
*
* It needs write access to the following core variables:
* <ul>
* <li>int simMoteID
* <li>char simMoteIDChanged
* </ul>
* When the mote id is set or changed, the random generator will also be seeded
* with this id (core function random_init()).
* <p>
* Dependency core interfaces are:
* <ul>
* <li>moteid_interface
* </ul>
* This observable notifies observers when the mote ID is set or changed.
*
* @author Fredrik Osterlind
*/
public class ContikiMoteID extends MoteID implements ContikiMoteInterface {
private SectionMoteMemory moteMem = null;
private static Logger logger = Logger.getLogger(ContikiMoteID.class);
private boolean setMoteID;
int moteID = 0;
/**
* Creates an interface to the mote ID at mote.
*
* @param mote
* Mote ID's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiMoteID(Mote mote) {
this.moteMem = (SectionMoteMemory) mote.getMemory();
setMoteID = false;
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"moteid_interface"};
}
public int getMoteID() {
return moteID;
}
public void setMoteID(int newID) {
setMoteID = true;
moteID = newID;
setChanged();
notifyObservers();
}
public void doActionsBeforeTick() {
if (setMoteID) {
setMoteID = false;
moteMem.setIntValueOf("simMoteID", moteID);
moteMem.setByteValueOf("simMoteIDChanged", (byte) 1);
}
setChanged();
notifyObservers();
}
public void doActionsAfterTick() {
// Nothing to do
}
public JPanel getInterfaceVisualizer() {
JPanel panel = new JPanel();
final JLabel idLabel = new JLabel();
idLabel.setText("Mote ID: " + moteID);
panel.add(idLabel);
Observer observer;
this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) {
idLabel.setText("Mote ID: " + moteID);
}
});
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer);
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) {
logger.fatal("Error when releasing panel, observer is null");
return;
}
this.deleteObserver(observer);
}
public double energyConsumptionPerTick() {
return 0.0;
}
public Collection<Element> getConfigXML() {
Vector<Element> config = new Vector<Element>();
Element element;
// Infinite boolean
element = new Element("id");
element.setText(Integer.toString(moteID));
config.add(element);
return config;
}
public void setConfigXML(Collection<Element> configXML) {
for (Element element : configXML) {
if (element.getName().equals("id")) {
setMoteID(Integer.parseInt(element.getText()));
}
}
}
}

View file

@ -0,0 +1,159 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiPIR.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.awt.event.*;
import java.util.Collection;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.PIR;
/**
* This class represents a passive infrared sensor.
*
* It needs read/write access to the following core variables:
* <ul>
* <li>char simPirChanged (1=changed, else not changed)
* <li>char simPirIsActive (1=active, else inactive)
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>pir_interface
* </ul>
* <p>
* This observable notifies observers if a change is discovered by the PIR.
*
* @author Fredrik Osterlind
*/
public class ContikiPIR extends PIR implements ContikiMoteInterface {
private static Logger logger = Logger.getLogger(ContikiPIR.class);
/**
* Approximate energy consumption of an active PIR sensor. ESB measured energy
* consumption is 0.4 mA. TODO Measure energy consumption
*/
public final double ENERGY_CONSUMPTION_PIR_mA;
private final boolean RAISES_EXTERNAL_INTERRUPT;
private double energyActivePerTick = -1;
private Mote mote;
private SectionMoteMemory moteMem;
private double myEnergyConsumption = 0.0;
/**
* Creates an interface to the pir at mote.
*
* @param mote
* Button's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiPIR(Mote mote) {
// Read class configurations of this mote type
ENERGY_CONSUMPTION_PIR_mA = mote.getType().getConfig().getDoubleValue(
ContikiPIR.class, "ACTIVE_CONSUMPTION_mA");
RAISES_EXTERNAL_INTERRUPT = mote.getType().getConfig()
.getBooleanValue(ContikiPIR.class, "EXTERNAL_INTERRUPT_bool");
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
if (energyActivePerTick < 0)
energyActivePerTick = ENERGY_CONSUMPTION_PIR_mA
* mote.getSimulation().getTickTimeInSeconds();
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"pir_interface"};
}
public void triggerChange() {
if (moteMem.getByteValueOf("simPirIsActive") == 1) {
moteMem.setByteValueOf("simPirChanged", (byte) 1);
// If mote is inactive, wake it up
if (RAISES_EXTERNAL_INTERRUPT)
mote.setState(Mote.STATE_ACTIVE);
this.setChanged();
this.notifyObservers();
}
}
public void doActionsBeforeTick() {
if (moteMem.getByteValueOf("simPirIsActive") == 1) {
myEnergyConsumption = energyActivePerTick;
} else
myEnergyConsumption = 0.0;
}
public void doActionsAfterTick() {
// Nothing to do
}
public JPanel getInterfaceVisualizer() {
JPanel panel = new JPanel();
final JButton clickButton = new JButton("Signal PIR");
panel.add(clickButton);
clickButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
triggerChange();
}
});
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
}
public double energyConsumptionPerTick() {
return myEnergyConsumption;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,256 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiRS232.java,v 1.1 2006/08/21 12:13:04 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
/**
* The class represents a simple RS232/Serial interface (only shows String
* format).
*
* It needs read/write access to the following core variables:
* <ul>
* <li>char simSerialSendingFlag (1=mote is sending data)
* <li>int simSerialSendingLength (length of data being sent from mote)
* <li>byte[] simSerialSendingData (data being sent from mote)
* <li>char simSerialRecevingFlag (1=mote is receving data)
* <li>int simSerialReceivingLength (length of data being received at mote)
* <li>byte[] simSerialReceivingData (data being received at mote)
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>rs232_interface
* </ul>
* <p>
* This observable is changed and notifies observers whenever a serial message
* has been received from the core (checked after each tick). The public method
* getSerialMessages gives access to the last data.
*
* @author Fredrik Osterlind
*/
@ClassDescription("Serial port (RS232)")
public class ContikiRS232 extends MoteInterface implements ContikiMoteInterface {
private static Logger logger = Logger.getLogger(ContikiRS232.class);
private Mote mote = null;
private SectionMoteMemory moteMem = null;
private String lastSerialMessage = null;
private final boolean RAISES_EXTERNAL_INTERRUPT;
private JTextArea logTextPane = null;
/**
* Approximate energy consumption of every sent character over RS232 (mQ).
*/
public final double ENERGY_CONSUMPTION_PER_CHAR_mQ;
private double myEnergyConsumption = 0.0;
/**
* Creates an interface to the RS232 at mote.
*
* @param mote
* RS232's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiRS232(Mote mote) {
// Read class configurations of this mote type
ENERGY_CONSUMPTION_PER_CHAR_mQ = mote.getType().getConfig()
.getDoubleValue(ContikiRS232.class, "CONSUMPTION_PER_CHAR_mQ");
RAISES_EXTERNAL_INTERRUPT = mote.getType().getConfig()
.getBooleanValue(ContikiRS232.class, "EXTERNAL_INTERRUPT_bool");
this.mote = mote;
this.moteMem = (SectionMoteMemory) mote.getMemory();
}
public static String[] getCoreInterfaceDependencies() {
return new String[]{"rs232_interface"};
}
public void doActionsBeforeTick() {
// Nothing to do
}
public void doActionsAfterTick() {
if (moteMem.getByteValueOf("simSerialSendingFlag") == 1) {
int totalLength = moteMem.getIntValueOf("simSerialSendingLength");
byte[] bytes = moteMem.getByteArray("simSerialSendingData", totalLength);
char[] chars = new char[bytes.length];
for (int i = 0; i < chars.length; i++)
chars[i] = (char) bytes[i];
myEnergyConsumption = ENERGY_CONSUMPTION_PER_CHAR_mQ * totalLength;
String message = String.valueOf(chars);
lastSerialMessage = message;
moteMem.setByteValueOf("simSerialSendingFlag", (byte) 0);
moteMem.setIntValueOf("simSerialSendingLength", (int) 0);
this.setChanged();
this.notifyObservers(mote);
} else
myEnergyConsumption = 0.0;
}
/**
* Returns all serial messages sent by mote the last tick that anything was
* sent.
*
* @return Last serial messages sent by mote.
*/
public String getSerialMessages() {
return lastSerialMessage;
}
/**
* Send a serial message to mote.
*
* @param message
* Message that mote should receive
*/
public void sendSerialMessage(String message) {
if (logTextPane != null) {
logTextPane.append("> " + message + "\n");
}
// Flag for incoming data
moteMem.setByteValueOf("simSerialReceivingFlag", (byte) 1);
byte[] dataToAppend = message.getBytes();
// Increase receiving size
int oldSize = moteMem.getIntValueOf("simSerialReceivingLength");
moteMem.setIntValueOf("simSerialReceivingLength", oldSize
+ dataToAppend.length);
int newSize = moteMem.getIntValueOf("simSerialReceivingLength");
// Write buffer characters
byte[] oldData = moteMem.getByteArray("simSerialReceivingData", oldSize);
byte[] newData = new byte[newSize];
for (int i = 0; i < oldData.length; i++)
newData[i] = oldData[i];
for (int i = 0; i < message.length(); i++)
newData[i + oldSize] = dataToAppend[i];
moteMem.setByteArray("simSerialReceivingData", newData);
if (RAISES_EXTERNAL_INTERRUPT)
mote.setState(Mote.STATE_ACTIVE);
}
public JPanel getInterfaceVisualizer() {
JPanel panel = new JPanel();
panel.setLayout(new BorderLayout());
if (logTextPane == null)
logTextPane = new JTextArea();
// Send RS232 data visualizer
JPanel sendPane = new JPanel();
final JTextField sendTextField = new JTextField(15);
JButton sendButton = new JButton("Send data");
sendButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
sendSerialMessage(sendTextField.getText());
}
});
sendPane.add(BorderLayout.WEST, sendTextField);
sendPane.add(BorderLayout.EAST, sendButton);
// Receive RS232 data visualizer
logTextPane.setOpaque(false);
logTextPane.setEditable(false);
if (lastSerialMessage == null)
logTextPane.setText("");
else
logTextPane.append(lastSerialMessage);
Observer observer;
this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) {
logTextPane.append("< " + lastSerialMessage + "\n");
logTextPane.setCaretPosition(logTextPane.getDocument().getLength());
}
});
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer);
JScrollPane scrollPane = new JScrollPane(logTextPane);
scrollPane.setPreferredSize(new Dimension(100, 100));
panel.add(BorderLayout.NORTH, new JLabel("Last serial data:"));
panel.add(BorderLayout.CENTER, scrollPane);
panel.add(BorderLayout.SOUTH, sendPane);
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) {
logger.fatal("Error when releasing panel, observer is null");
return;
}
this.deleteObserver(observer);
}
public double energyConsumptionPerTick() {
return myEnergyConsumption;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

View file

@ -0,0 +1,305 @@
/*
* Copyright (c) 2006, Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the Institute nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE INSTITUTE AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE INSTITUTE OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* $Id: ContikiRadio.java,v 1.1 2006/08/21 12:13:05 fros4943 Exp $
*/
package se.sics.cooja.contikimote.interfaces;
import java.util.*;
import javax.swing.*;
import org.apache.log4j.Logger;
import org.jdom.Element;
import se.sics.cooja.*;
import se.sics.cooja.contikimote.ContikiMoteInterface;
import se.sics.cooja.interfaces.Radio;
/**
* This class represents a radio transciever.
*
* It needs read/write access to the following core variables:
* <ul>
* <li>char simSentPacket (1=mote has new outgoing data, else no new outgoing
* data)
* <li>char simReceivedPacket (1=mote has new incoming data, else no new
* incoming data)
* <li>char simEtherBusy (1=ether is busy, MAC may try to resend later, else
* not busy)
* <li>int simReceivedPacketSize (size of new received data packet)
* <li>int simSentPacketSize (size of new sent data packet)
* <li>byte[] simSentPacketData (data of new sent data packet)
* <li>byte[] simReceivedPacketData (data of new received data packet)
* <li>char simRadioHWOn (radio hardware status (on/off))
* </ul>
* <p>
* Dependency core interfaces are:
* <ul>
* <li>radio_interface
* </ul>
* <p>
* This observable is changed and notifies observers whenever either the send
* status or listen status is changed. If current listen status is HEARS_PACKET
* just before a mote tick, the current packet data is transferred to the core.
* Otherwise no data will be transferred. If core has sent a packet, current
* sent status will be set to SENT_SOMETHING when returning from the mote tick
* that sent the packet. This status will be reset to SENT_NOTHING just before
* next tick.
*
* @author Fredrik Osterlind
*/
public class ContikiRadio extends Radio implements ContikiMoteInterface {
private Mote myMote;
private SectionMoteMemory myMoteMemory;
private static Logger logger = Logger.getLogger(ContikiRadio.class);
/**
* Approximate energy consumption of an active radio. ESB measured energy
* consumption is 5 mA. TODO Measure energy consumption
*/
public final double ENERGY_CONSUMPTION_RADIO_mA;
private final boolean RAISES_EXTERNAL_INTERRUPT;
private double energyActiveRadioPerTick = -1;
private int mySendState = SENT_NOTHING;
private int myListenState = HEARS_NOTHING;
private byte[] packetToMote = null;
private byte[] packetFromMote = null;
private boolean radioOn = true;
private double myEnergyConsumption=0.0;
/**
* Creates an interface to the radio at mote.
*
* @param mote
* Radio's mote.
* @see Mote
* @see se.sics.cooja.MoteInterfaceHandler
*/
public ContikiRadio(Mote mote) {
// Read class configurations of this mote type
ENERGY_CONSUMPTION_RADIO_mA = mote.getType().getConfig().getDoubleValue(ContikiRadio.class, "ACTIVE_CONSUMPTION_mA");
RAISES_EXTERNAL_INTERRUPT = mote.getType().getConfig().getBooleanValue(ContikiRadio.class, "EXTERNAL_INTERRUPT_bool");
this.myMote = mote;
this.myMoteMemory = (SectionMoteMemory) mote.getMemory();
if (energyActiveRadioPerTick < 0)
energyActiveRadioPerTick = ENERGY_CONSUMPTION_RADIO_mA * mote.getSimulation().getTickTimeInSeconds();
}
public static String[] getCoreInterfaceDependencies() {
return new String[] { "radio_interface" };
}
public byte[] getLastPacketSent() {
return packetFromMote;
}
public byte[] getLastPacketReceived() {
return packetToMote;
}
public void receivePacket(byte[] data) {
packetToMote = data;
}
public int getSendState() {
return mySendState;
}
public int getListenState() {
return myListenState;
}
public void setListenState(int newStatus) {
if (newStatus != myListenState) {
myListenState = newStatus;
this.setChanged();
this.notifyObservers(myMote.getInterfaces().getPosition());
}
// If mote is inactive, wake it up
if (RAISES_EXTERNAL_INTERRUPT)
myMote.setState(Mote.STATE_ACTIVE);
}
public void advanceListenState() {
if (myListenState == HEARS_NOTHING) {
setListenState(HEARS_PACKET);
} else
setListenState(HEARS_NOISE);
}
public void doActionsBeforeTick() {
// If radio hardware is turned off, we don't need to do anything..
if (!radioOn) {
myEnergyConsumption = 0.0;
return;
}
myEnergyConsumption = energyActiveRadioPerTick;
// Set ether status
if (getListenState() == HEARS_PACKET ||
getListenState() == HEARS_NOISE ||
getSendState() == SENT_SOMETHING) {
myMoteMemory.setByteValueOf("simEtherBusy", (byte) 1);
} else {
myMoteMemory.setByteValueOf("simEtherBusy", (byte) 0);
}
if (getListenState() == HEARS_NOTHING) {
// Haven't heard anything, nothing to do
} else if (getListenState() == HEARS_PACKET) {
// Heard only one packet, transfer to mote ok
myMoteMemory.setByteValueOf("simReceivedPacket", (byte) 1);
myMoteMemory.setIntValueOf("simReceivedPacketSize", packetToMote.length);
myMoteMemory.setByteArray("simReceivedPacketData", packetToMote);
} else if (getListenState() == HEARS_NOISE) {
// Heard several packets or noise, transfer failed
}
// Reset send flag
setSendStatus(SENT_NOTHING);
}
public void doActionsAfterTick() {
// Check new radio hardware status
if (myMoteMemory.getByteValueOf("simRadioHWOn") == 1) {
radioOn = true;
} else {
radioOn = false;
return;
}
// Reset listen flag
setListenState(HEARS_NOTHING);
if (fetchPacketFromCore()) {
setSendStatus(SENT_SOMETHING);
}
}
private void setSendStatus(int newStatus) {
if (newStatus != mySendState) {
mySendState = newStatus;
this.setChanged();
this.notifyObservers(myMote.getInterfaces().getPosition());
}
}
private boolean fetchPacketFromCore() {
if (myMoteMemory.getByteValueOf("simSentPacket") == 1) {
// TODO Increase energy consumption, we are sending a packet...
myMoteMemory.setByteValueOf("simSentPacket", (byte) 0);
int size = myMoteMemory.getIntValueOf("simSentPacketSize");
packetFromMote = myMoteMemory.getByteArray("simSentPacketData", size);
myMoteMemory.setIntValueOf("simSentPacketSize", 0);
return true;
}
return false;
}
public JPanel getInterfaceVisualizer() {
// Location
JPanel panel = new JPanel();
panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
final JLabel listenLabel = new JLabel();
final JLabel sendLabel = new JLabel();
if (getListenState() == HEARS_NOISE)
listenLabel.setText("Current listen status: hears noise");
else if (getListenState() == HEARS_NOTHING)
listenLabel.setText("Current listen status: hears nothing");
else if (getListenState() == HEARS_PACKET)
listenLabel.setText("Current listen status: hears a packet");
if (getSendState() == SENT_NOTHING)
sendLabel.setText("Current sending status: sent nothing");
else if (getSendState() == SENT_SOMETHING)
sendLabel.setText("Current sending status: sent a packet");
panel.add(listenLabel);
panel.add(sendLabel);
Observer observer;
this.addObserver(observer = new Observer() {
public void update(Observable obs, Object obj) {
if (getListenState() == HEARS_NOISE)
listenLabel.setText("Current listen status: hears noise");
else if (getListenState() == HEARS_NOTHING)
listenLabel.setText("Current listen status: hears nothing");
else if (getListenState() == HEARS_PACKET)
listenLabel.setText("Current listen status: hears a packet");
if (getSendState() == SENT_NOTHING)
sendLabel.setText("Current sending status: sent nothing");
else if (getSendState() == SENT_SOMETHING)
sendLabel.setText("Current sending status: sent a packet");
}
});
// Saving observer reference for releaseInterfaceVisualizer
panel.putClientProperty("intf_obs", observer);
return panel;
}
public void releaseInterfaceVisualizer(JPanel panel) {
Observer observer = (Observer) panel.getClientProperty("intf_obs");
if (observer == null) {
logger.fatal("Error when releasing panel, observer is null");
return;
}
this.deleteObserver(observer);
}
public double energyConsumptionPerTick() {
return myEnergyConsumption;
}
public Collection<Element> getConfigXML() {
return null;
}
public void setConfigXML(Collection<Element> configXML) {
}
}

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