repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
tinyos-io/tinyos-3.x-contrib | stanford-sing/apps/PowerNetBase/PowerNetBase.h | /*
* "Copyright (c) 2009 Stanford University. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY
* PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF STANFORD UNIVERSITY HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
* CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
/*
* Header file to specify the ID of the powernet messages
*
* @author <NAME>, <<EMAIL>>
* @date Oct 18, 2009
*/
#include <AM.h>
enum {
AM_ID = 0xCD,
QUEUE_SIZE = 8,
};
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/install.c | /* LIBUSB-WIN32, Generic Windows USB Library
* Copyright (c) 2002-2005 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <windows.h>
#include <winsvc.h>
#include <setupapi.h>
#include <stdio.h>
#include <regstr.h>
#include <wchar.h>
#include <string.h>
#ifdef __GNUC__
#include <ddk/cfgmgr32.h>
#else
#include <cfgmgr32.h>
#define strlwr(p) _strlwr(p)
#endif
#include "usb.h"
#include "registry.h"
#include "error.h"
#include "driver_api.h"
#define LIBUSB_DRIVER_PATH "system32\\drivers\\libusb0.sys"
#define LIBUSB_OLD_SERVICE_NAME_NT "libusbd"
#define INSTALLFLAG_FORCE 0x00000001
/* newdev.dll exports */
typedef BOOL (WINAPI * update_driver_for_plug_and_play_devices_t)(HWND,
LPCSTR,
LPCSTR,
DWORD,
PBOOL);
/* setupapi.dll exports */
typedef BOOL (WINAPI * setup_copy_oem_inf_t)(PCSTR, PCSTR, DWORD, DWORD,
PSTR, DWORD, PDWORD, PSTR*);
/* advapi32.dll exports */
typedef SC_HANDLE (WINAPI * open_sc_manager_t)(LPCTSTR, LPCTSTR, DWORD);
typedef SC_HANDLE (WINAPI * open_service_t)(SC_HANDLE, LPCTSTR, DWORD);
typedef BOOL (WINAPI * change_service_config_t)(SC_HANDLE, DWORD, DWORD,
DWORD, LPCTSTR, LPCTSTR,
LPDWORD, LPCTSTR, LPCTSTR,
LPCTSTR, LPCTSTR);
typedef BOOL (WINAPI * close_service_handle_t)(SC_HANDLE);
typedef SC_HANDLE (WINAPI * create_service_t)(SC_HANDLE, LPCTSTR, LPCTSTR,
DWORD, DWORD,DWORD, DWORD,
LPCTSTR, LPCTSTR, LPDWORD,
LPCTSTR, LPCTSTR, LPCTSTR);
typedef BOOL (WINAPI * delete_service_t)(SC_HANDLE);
typedef BOOL (WINAPI * start_service_t)(SC_HANDLE, DWORD, LPCTSTR);
typedef BOOL (WINAPI * query_service_status_t)(SC_HANDLE, LPSERVICE_STATUS);
typedef BOOL (WINAPI * control_service_t)(SC_HANDLE, DWORD, LPSERVICE_STATUS);
static HINSTANCE advapi32_dll = NULL;
static open_sc_manager_t open_sc_manager = NULL;
static open_service_t open_service = NULL;
static change_service_config_t change_service_config = NULL;
static close_service_handle_t close_service_handle = NULL;
static create_service_t create_service = NULL;
static delete_service_t delete_service = NULL;
static start_service_t start_service = NULL;
static query_service_status_t query_service_status = NULL;
static control_service_t control_service = NULL;
static bool_t usb_service_load_dll(void);
static bool_t usb_service_free_dll(void);
static bool_t usb_service_create(const char *name, const char *display_name,
const char *binary_path, unsigned long type,
unsigned long start_type);
static bool_t usb_service_stop(const char *name);
static bool_t usb_service_delete(const char *name);
void CALLBACK usb_touch_inf_file_rundll(HWND wnd, HINSTANCE instance,
LPSTR cmd_line, int cmd_show);
void CALLBACK usb_install_service_np_rundll(HWND wnd, HINSTANCE instance,
LPSTR cmd_line, int cmd_show)
{
usb_install_service_np();
}
void CALLBACK usb_uninstall_service_np_rundll(HWND wnd, HINSTANCE instance,
LPSTR cmd_line, int cmd_show)
{
usb_uninstall_service_np();
}
void CALLBACK usb_install_driver_np_rundll(HWND wnd, HINSTANCE instance,
LPSTR cmd_line, int cmd_show)
{
usb_install_driver_np(cmd_line);
}
int usb_install_service_np(void)
{
char display_name[MAX_PATH];
int ret = 0;
/* uninstall old filter driver */
usb_uninstall_service_np();
/* stop devices that are handled by libusb's device driver */
usb_registry_stop_libusb_devices();
/* the old driver is unloaded now */
if(usb_registry_is_nt())
{
memset(display_name, 0, sizeof(display_name));
/* create the Display Name */
_snprintf(display_name, sizeof(display_name) - 1,
"LibUsb-Win32 - Kernel Driver, Version %d.%d.%d.%d",
VERSION_MAJOR, VERSION_MINOR, VERSION_MICRO, VERSION_NANO);
/* create the kernel service */
if(!usb_service_create(LIBUSB_DRIVER_NAME_NT, display_name,
LIBUSB_DRIVER_PATH,
SERVICE_KERNEL_DRIVER, SERVICE_DEMAND_START))
ret = -1;
}
/* restart devices that are handled by libusb's device driver */
usb_registry_start_libusb_devices();
/* insert filter drivers */
usb_registry_insert_class_filter();
/* restart the whole USB system so that the new drivers will be loaded */
usb_registry_restart_all_devices();
return ret;
}
int usb_uninstall_service_np(void)
{
HANDLE win;
HKEY reg_key = NULL;
/* older version of libusb used a system service, just remove it */
if(usb_registry_is_nt())
{
usb_service_stop(LIBUSB_OLD_SERVICE_NAME_NT);
usb_service_delete(LIBUSB_OLD_SERVICE_NAME_NT);
}
else
{
do {
win = FindWindow("LIBUSB_SERVICE_WINDOW_CLASS", NULL);
if(win != INVALID_HANDLE_VALUE)
{
PostMessage(win, WM_DESTROY, 0, 0);
Sleep(500);
}
} while(win);
if(RegOpenKeyEx(HKEY_LOCAL_MACHINE,
"Software\\Microsoft\\Windows\\CurrentVersion"
"\\RunServices",
0, KEY_ALL_ACCESS, ®_key) == ERROR_SUCCESS)
{
RegDeleteValue(reg_key, "LibUsb-Win32 Daemon");
RegCloseKey(reg_key);
}
}
/* old versions used device filters that have to be removed */
usb_registry_remove_device_filter();
/* remove class filter driver */
usb_registry_remove_class_filter();
/* unload filter drivers */
usb_registry_restart_all_devices();
return 0;
}
int usb_install_driver_np(const char *inf_file)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
INFCONTEXT inf_context;
HINF inf_handle;
DWORD config_flags, problem, status;
BOOL reboot;
char inf_path[MAX_PATH];
char id[MAX_PATH];
char tmp_id[MAX_PATH];
char *p;
int dev_index;
HINSTANCE newdev_dll = NULL;
HMODULE setupapi_dll = NULL;
update_driver_for_plug_and_play_devices_t UpdateDriverForPlugAndPlayDevices;
setup_copy_oem_inf_t SetupCopyOEMInf;
newdev_dll = LoadLibrary("newdev.dll");
if(!newdev_dll)
{
usb_error("usb_install_driver(): loading newdev.dll failed\n");
return -1;
}
UpdateDriverForPlugAndPlayDevices =
(update_driver_for_plug_and_play_devices_t)
GetProcAddress(newdev_dll, "UpdateDriverForPlugAndPlayDevicesA");
if(!UpdateDriverForPlugAndPlayDevices)
{
usb_error("usb_install_driver(): loading newdev.dll failed\n");
return -1;
}
setupapi_dll = GetModuleHandle("setupapi.dll");
if(!setupapi_dll)
{
usb_error("usb_install_driver(): loading setupapi.dll failed\n");
return -1;
}
SetupCopyOEMInf = (setup_copy_oem_inf_t)
GetProcAddress(setupapi_dll, "SetupCopyOEMInfA");
if(!SetupCopyOEMInf)
{
usb_error("usb_install_driver(): loading setupapi.dll failed\n");
return -1;
}
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
/* retrieve the full .inf file path */
if(!GetFullPathName(inf_file, MAX_PATH, inf_path, NULL))
{
usb_error("usb_install_driver(): .inf file %s not found\n",
inf_file);
return -1;
}
/* open the .inf file */
inf_handle = SetupOpenInfFile(inf_path, NULL, INF_STYLE_WIN4, NULL);
if(inf_handle == INVALID_HANDLE_VALUE)
{
usb_error("usb_install_driver(): unable to open .inf file %s\n",
inf_file);
return -1;
}
/* find the .inf file's device description section marked "Devices" */
if(!SetupFindFirstLine(inf_handle, "Devices", NULL, &inf_context))
{
usb_error("usb_install_driver(): .inf file %s does not contain "
"any device descriptions\n", inf_file);
SetupCloseInfFile(inf_handle);
return -1;
}
do {
/* get the device ID from the .inf file */
if(!SetupGetStringField(&inf_context, 2, id, sizeof(id), NULL))
{
continue;
}
/* convert the string to lowercase */
strlwr(id);
reboot = FALSE;
/* copy the .inf file to the system directory so that is will be found */
/* when new devices are plugged in */
SetupCopyOEMInf(inf_path, NULL, SPOST_PATH, 0, NULL, 0, NULL, NULL);
/* update all connected devices matching this ID, but only if this */
/* driver is better or newer */
UpdateDriverForPlugAndPlayDevices(NULL, id, inf_path, INSTALLFLAG_FORCE,
&reboot);
/* now search the registry for device nodes representing currently */
/* unattached devices */
/* get all USB device nodes from the registry, present and non-present */
/* devices */
dev_info = SetupDiGetClassDevs(NULL, "USB", NULL, DIGCF_ALLCLASSES);
if(dev_info == INVALID_HANDLE_VALUE)
{
SetupCloseInfFile(inf_handle);
break;
}
dev_index = 0;
/* enumerate the device list to find all attached and unattached */
/* devices */
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
/* get the harware ID from the registry, this is a multi-zero string */
if(SetupDiGetDeviceRegistryProperty(dev_info, &dev_info_data,
SPDRP_HARDWAREID, NULL,
(BYTE *)tmp_id,
sizeof(tmp_id), NULL))
{
/* check all possible IDs contained in that multi-zero string */
for(p = tmp_id; *p; p += (strlen(p) + 1))
{
/* convert the string to lowercase */
strlwr(p);
/* found a match? */
if(strstr(p, id))
{
/* is this device disconnected? */
if(CM_Get_DevNode_Status(&status,
&problem,
dev_info_data.DevInst,
0) == CR_NO_SUCH_DEVINST)
{
/* found a device node that represents an unattached */
/* device */
if(SetupDiGetDeviceRegistryProperty(dev_info,
&dev_info_data,
SPDRP_CONFIGFLAGS,
NULL,
(BYTE *)&config_flags,
sizeof(config_flags),
NULL))
{
/* mark the device to be reinstalled the next time it is */
/* plugged in */
config_flags |= CONFIGFLAG_REINSTALL;
/* write the property back to the registry */
SetupDiSetDeviceRegistryProperty(dev_info,
&dev_info_data,
SPDRP_CONFIGFLAGS,
(BYTE *)&config_flags,
sizeof(config_flags));
}
}
/* a match was found, skip the rest */
break;
}
}
}
/* check the next device node */
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
/* get the next device ID from the .inf file */
} while(SetupFindNextLine(&inf_context, &inf_context));
/* we are done, close the .inf file */
SetupCloseInfFile(inf_handle);
usb_registry_stop_libusb_devices(); /* stop all libusb devices */
usb_registry_start_libusb_devices(); /* restart all libusb devices */
return 0;
}
bool_t usb_service_load_dll()
{
if(usb_registry_is_nt())
{
advapi32_dll = LoadLibrary("advapi32.dll");
if(!advapi32_dll)
{
usb_error("usb_service_load_dll(): loading DLL advapi32.dll"
"failed");
return FALSE;
}
open_sc_manager = (open_sc_manager_t)
GetProcAddress(advapi32_dll, "OpenSCManagerA");
open_service = (open_service_t)
GetProcAddress(advapi32_dll, "OpenServiceA");
change_service_config = (change_service_config_t)
GetProcAddress(advapi32_dll, "ChangeServiceConfigA");
close_service_handle = (close_service_handle_t)
GetProcAddress(advapi32_dll, "CloseServiceHandle");
create_service = (create_service_t)
GetProcAddress(advapi32_dll, "CreateServiceA");
delete_service = (delete_service_t)
GetProcAddress(advapi32_dll, "DeleteService");
start_service = (start_service_t)
GetProcAddress(advapi32_dll, "StartServiceA");
query_service_status = (query_service_status_t)
GetProcAddress(advapi32_dll, "QueryServiceStatus");
control_service = (control_service_t)
GetProcAddress(advapi32_dll, "ControlService");
if(!open_sc_manager || !open_service || !change_service_config
|| !close_service_handle || !create_service || !delete_service
|| !start_service || !query_service_status || !control_service)
{
FreeLibrary(advapi32_dll);
usb_error("usb_service_load_dll(): loading exported "
"functions of advapi32.dll failed");
return FALSE;
}
}
return TRUE;
}
bool_t usb_service_free_dll()
{
if(advapi32_dll)
{
FreeLibrary(advapi32_dll);
}
return TRUE;
}
bool_t usb_service_create(const char *name, const char *display_name,
const char *binary_path, unsigned long type,
unsigned long start_type)
{
SC_HANDLE scm = NULL;
SC_HANDLE service = NULL;
bool_t ret = FALSE;
if(!usb_service_load_dll())
{
return FALSE;
}
do
{
scm = open_sc_manager(NULL, SERVICES_ACTIVE_DATABASE,
SC_MANAGER_ALL_ACCESS);
if(!scm)
{
usb_error("usb_service_create(): opening service control "
"manager failed: %s", usb_win_error_to_string());
break;
}
service = open_service(scm, name, SERVICE_ALL_ACCESS);
if(service)
{
if(!change_service_config(service,
type,
start_type,
SERVICE_ERROR_NORMAL,
binary_path,
NULL,
NULL,
NULL,
NULL,
NULL,
display_name))
{
usb_error("usb_service_create(): changing config of "
"service '%s' failed: %s",
name, usb_win_error_to_string());
break;
}
ret = TRUE;
break;
}
if(GetLastError() == ERROR_SERVICE_DOES_NOT_EXIST)
{
service = create_service(scm,
name,
display_name,
GENERIC_EXECUTE,
type,
start_type,
SERVICE_ERROR_NORMAL,
binary_path,
NULL, NULL, NULL, NULL, NULL);
if(!service)
{
usb_error("usb_service_create(): creating "
"service '%s' failed: %s",
name, usb_win_error_to_string());
}
ret = TRUE;
}
} while(0);
if(service)
{
close_service_handle(service);
}
if(scm)
{
close_service_handle(scm);
}
usb_service_free_dll();
return ret;
}
bool_t usb_service_stop(const char *name)
{
bool_t ret = FALSE;
SC_HANDLE scm = NULL;
SC_HANDLE service = NULL;
SERVICE_STATUS status;
if(!usb_service_load_dll())
{
return FALSE;
}
do
{
scm = open_sc_manager(NULL, SERVICES_ACTIVE_DATABASE,
SC_MANAGER_ALL_ACCESS);
if(!scm)
{
usb_error("usb_stop_service(): opening service control "
"manager failed: %s", usb_win_error_to_string());
break;
}
service = open_service(scm, name, SERVICE_ALL_ACCESS);
if(!service)
{
ret = TRUE;
break;
}
if(!query_service_status(service, &status))
{
usb_error("usb_stop_service(): getting status of "
"service '%s' failed: %s",
name, usb_win_error_to_string());
break;
}
if(status.dwCurrentState == SERVICE_STOPPED)
{
ret = TRUE;
break;
}
if(!control_service(service, SERVICE_CONTROL_STOP, &status))
{
usb_error("usb_stop_service(): stopping service '%s' failed: %s",
name, usb_win_error_to_string());
break;
}
do
{
int wait = 0;
if(!query_service_status(service, &status))
{
usb_error("usb_stop_service(): getting status of "
"service '%s' failed: %s",
name, usb_win_error_to_string());
break;
}
Sleep(500);
wait += 500;
if(wait > 20000)
{
usb_error("usb_stop_service(): stopping "
"service '%s' failed, timeout", name);
ret = FALSE;
break;
}
ret = TRUE;
} while(status.dwCurrentState != SERVICE_STOPPED);
} while(0);
if(service)
{
close_service_handle(service);
}
if(scm)
{
close_service_handle(scm);
}
usb_service_free_dll();
return ret;
}
bool_t usb_service_delete(const char *name)
{
bool_t ret = FALSE;
SC_HANDLE scm = NULL;
SC_HANDLE service = NULL;
if(!usb_service_load_dll())
{
return FALSE;
}
do
{
scm = open_sc_manager(NULL, SERVICES_ACTIVE_DATABASE,
SC_MANAGER_ALL_ACCESS);
if(!scm)
{
usb_error("usb_delete_service(): opening service control "
"manager failed: %s", usb_win_error_to_string());
break;
}
service = open_service(scm, name, SERVICE_ALL_ACCESS);
if(!service)
{
ret = TRUE;
break;
}
if(!delete_service(service))
{
usb_error("usb_service_delete(): deleting "
"service '%s' failed: %s",
name, usb_win_error_to_string());
break;
}
ret = TRUE;
} while(0);
if(service)
{
close_service_handle(service);
}
if(scm)
{
close_service_handle(scm);
}
usb_service_free_dll();
return ret;
}
void CALLBACK usb_touch_inf_file_np_rundll(HWND wnd, HINSTANCE instance,
LPSTR cmd_line, int cmd_show)
{
usb_touch_inf_file_np(cmd_line);
}
int usb_touch_inf_file_np(const char *inf_file)
{
const char inf_comment[] = ";added by libusb to break this file's digital "
"signature";
const wchar_t inf_comment_uni[] = L";added by libusb to break this file's "
L"digital signature";
char buf[1024];
wchar_t wbuf[1024];
int found = 0;
OSVERSIONINFO version;
FILE *f;
version.dwOSVersionInfoSize = sizeof(OSVERSIONINFO);
if(!GetVersionEx(&version))
return -1;
/* XP system */
if((version.dwMajorVersion == 5) && (version.dwMinorVersion >= 1))
{
f = fopen(inf_file, "rb");
if(!f)
return -1;
while(fgetws(wbuf, sizeof(wbuf)/2, f))
{
if(wcsstr(wbuf, inf_comment_uni))
{
found = 1;
break;
}
}
fclose(f);
if(!found)
{
f = fopen(inf_file, "ab");
/* fputwc(0x000d, f); */
/* fputwc(0x000d, f); */
fputws(inf_comment_uni, f);
fclose(f);
}
}
else
{
f = fopen(inf_file, "r");
if(!f)
return -1;
while(fgets(buf, sizeof(buf), f))
{
if(strstr(buf, inf_comment))
{
found = 1;
break;
}
}
fclose(f);
if(!found)
{
f = fopen(inf_file, "a");
fputs("\n", f);
fputs(inf_comment, f);
fputs("\n", f);
fclose(f);
}
}
return 0;
}
int usb_install_needs_restart_np(void)
{
HDEVINFO dev_info;
SP_DEVINFO_DATA dev_info_data;
int dev_index = 0;
SP_DEVINSTALL_PARAMS install_params;
int ret = FALSE;
dev_info_data.cbSize = sizeof(SP_DEVINFO_DATA);
dev_info = SetupDiGetClassDevs(NULL, NULL, NULL,
DIGCF_ALLCLASSES | DIGCF_PRESENT);
SetEnvironmentVariable("LIBUSB_NEEDS_REBOOT", "1");
if(dev_info == INVALID_HANDLE_VALUE)
{
usb_error("usb_install_needs_restart_np(): getting "
"device info set failed");
return ret;
}
while(SetupDiEnumDeviceInfo(dev_info, dev_index, &dev_info_data))
{
memset(&install_params, 0, sizeof(SP_PROPCHANGE_PARAMS));
install_params.cbSize = sizeof(SP_DEVINSTALL_PARAMS);
if(SetupDiGetDeviceInstallParams(dev_info, &dev_info_data,
&install_params))
{
if(install_params.Flags & (DI_NEEDRESTART | DI_NEEDREBOOT))
{
usb_message("usb_install_needs_restart_np(): restart needed");
ret = TRUE;
}
}
dev_index++;
}
SetupDiDestroyDeviceInfoList(dev_info);
return ret;
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/platforms/nxtmote/lib_extra_AT91SAM7S256.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef lib_extra_AT91SAM7S256_H
#define lib_extra_AT91SAM7S256_H
/**
* Adapted for nxtmote.
* @author <NAME>
*/
// Some extra functions in relation to those found in lib_AT91SAM7S256.
// Various methods from different files.
// @author rup
/* *****************************************************************************
SOFTWARE API FOR AIC
***************************************************************************** */
//*----------------------------------------------------------------------------
//* \fn AT91F_AIC_ActiveID
//* \brief Return id of active interupt
//*----------------------------------------------------------------------------
__inline unsigned int AT91F_AIC_ActiveID (
AT91PS_AIC pAic) // \arg pointer to the AIC registers
{
return pAic->AIC_ISR;
}
/* *****************************************************************************
SOFTWARE API FOR TIMER/COUNTER
***************************************************************************** */
/*-----------------*/
/* Clock Selection */
/*-----------------*/
#define TC_CLKS 0x7
#define TC_CLKS_MCK2 0x0 //RC = 24027,42 tics ~ 24028
#define TC_CLKS_MCK8 0x1
#define TC_CLKS_MCK32 0x2
#define TC_CLKS_MCK128 0x3
#define TC_CLKS_MCK1024 0x4
//TODO: Make it configurable
#define TIMER0_INTERRUPT_LEVEL 1
#define TIMER1_INTERRUPT_LEVEL 4
//*----------------------------------------------------------------------------
//* Function Name : AT91F_TC_Open
//* Object : Initialize Timer Counter Channel and enable is clock
//* Input Parameters : <tc_pt> = TC Channel Descriptor Pointer
//* <mode> = Timer Counter Mode
//* : <TimerId> = Timer peripheral ID definitions
//* Output Parameters : None
//*----------------------------------------------------------------------------
void AT91F_TC_Open ( AT91PS_TC TC_pt, unsigned int Mode, unsigned int TimerId)
{
unsigned int dummy;
//* First, enable the clock of the TIMER
// rup: testing
//AT91F_PMC_EnablePeriphClock ( AT91C_BASE_PMC, 1<< TimerId ) ;
//* Disable the clock and the interrupts
TC_pt->TC_CCR = AT91C_TC_CLKDIS ;
TC_pt->TC_IDR = 0xFFFFFFFF ;
//* Clear status bit
dummy = TC_pt->TC_SR;
//* Suppress warning variable "dummy" was set but never used
dummy = dummy;
//* Set the Mode of the Timer Counter
TC_pt->TC_CMR = Mode ;
//* Enable the clock
TC_pt->TC_CCR = AT91C_TC_CLKEN ;
}
//*----------------------------------------------------------------------------
//* \fn AT91F_TC_IntEnable
//* \brief Return none
//*----------------------------------------------------------------------------
__inline void AT91_TC_IntEnable(
AT91PS_TC pTC, // \arg pointer to the timer base
unsigned int Mask) // \arg which interupts to enable
{
pTC->TC_IER = Mask;
}
//*----------------------------------------------------------------------------
//* \fn AT91F_TC_IntDisable
//* \brief Return none
//*----------------------------------------------------------------------------
__inline void AT91_TC_IntDisable(
AT91PS_TC pTC, // \arg pointer to the timer base
unsigned int Mask) // \arg which interupts to disable
{
pTC->TC_IDR = Mask;
}
#endif // lib_extra_AT91SAM7S256_H
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/lib6lowpan/lib6lowpan.c | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/* Implementation of draft-ietf-6lowpan-hc-06 */
/* @author <NAME> <<EMAIL>> */
/* Each function in this file should have an associated set of test cases in tests/ */
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#ifdef UNIT_TESTING
#include <stdio.h>
#else
// #define printf(fmt, args ...) ;
#endif
#include "lib6lowpan-includes.h"
#include "lib6lowpan.h"
#include "ip.h"
#include "Ieee154.h"
/* UTILITY MACROS AND FUNCTIONS */
/* test if the first 64-bits are fe80::/64 */
#define IS_LINKLOCAL(ADDR) \
((ADDR)->s6_addr16[0] == htons(0xfe80) && \
(ADDR)->s6_addr16[1] == 0 && \
(ADDR)->s6_addr16[2] == 0 && \
(ADDR)->s6_addr16[3] == 0)
/* test if the address is all zeroes */
#define IS_UNSPECIFIED(ADDR) \
((ADDR)->s6_addr16[0] == 0 && \
(ADDR)->s6_addr16[1] == 0 && \
(ADDR)->s6_addr16[2] == 0 && \
(ADDR)->s6_addr16[3] == 0 && \
(ADDR)->s6_addr16[4] == 0 && \
(ADDR)->s6_addr16[5] == 0 && \
(ADDR)->s6_addr16[6] == 0 && \
(ADDR)->s6_addr16[7] == 0)
#define COPY_IEEE154_ADDR(FIELD) \
if (frame-> FIELD .ieee_mode == IEEE154_ADDR_SHORT) { \
uint16_t tmpval = (frame-> FIELD . i_saddr); \
memcpy(buf, &tmpval, 2); \
buf += 2; \
} else { \
memcpy(buf, &(frame-> FIELD .i_laddr), 8); \
buf += 8; \
}
/* @return 0 if all bits in the range [start,end) are zero */
/* -1 otherwise */
int bit_range_zero_p(uint8_t *buf, int start, int end) {
int start_byte = start / 8;
int end_byte = end / 8;
int i;
uint8_t start_mask = 0xff << (8 - (start % 8));
uint8_t end_mask = 0xff << (8 - (end % 8));
// printf("start: %i end: %i, (%i, %i)\n", start, end, start_byte, end_byte);
// printf("start mask: 0x%x end mask: 0x%x\n", start_mask, end_mask);
if ((buf[start_byte] & start_mask) != 0) {
return -1;
}
if ((buf[end_byte] & end_mask) != 0) {
return -1;
}
for (i = start_byte; i < end_byte; i++) {
if (buf[i] != 0) return -1;
}
return 0;
}
/* HEADER PACKING */
/* functions for creating a compressed representation of an IPv6 header */
/* packs the Traffic Class and Flow Label fields as described in the internet draft */
/* @buf the buffer to write any anyline fields to */
/* @hdr the IPv6 header being compressed; this function only examines the first four octets */
/* @dispatch the octet corresponding to the first octet of the IPHC dispatch value */
/* modified to reflect the packing of the fields */
inline uint8_t *pack_tcfl(uint8_t *buf, struct ip6_hdr *hdr, uint8_t *dispatch) {
uint32_t flow = (ntohl(hdr->ip6_flow) & 0x000fffff);
uint8_t tc = (ntohl(hdr->ip6_flow) >> 20) & 0xff;
if (flow == 0 && tc == 0) {
// lucky us
*dispatch |= LOWPAN_IPHC_TF_NONE;
} else if (flow == 0) {
*dispatch |= LOWPAN_IPHC_TF_ECN_DSCP;
*buf = (tc >> 2) & 0xff;
*buf |= (tc << 6) & 0xff;
buf++;
} else if ((tc & 0x3) == tc) {
*dispatch |= LOWPAN_IPHC_TF_ECN_FL;
*buf = (tc << 6) & 0xff;
*buf |= (flow >> 16) & 0x0f;
*(buf + 1) = (flow >> 8) & 0xff;
*(buf + 2) = (flow) & 0xff;
buf += 3;
} else {
*dispatch |= LOWPAN_IPHC_TF_ECN_DSCP_FL;
*buf = (tc >> 2) & 0xff;
*buf |= (tc << 6) & 0xff;
*(buf + 1) = (flow >> 16) & 0x0f;
*(buf + 2) = (flow >> 8) & 0xff;
*(buf + 3) = (flow) & 0xff;
buf += 4;
}
return buf;
}
inline uint8_t *pack_nh(uint8_t *buf, struct ip6_hdr *hdr, uint8_t *dispatch) {
uint8_t nxt = hdr->ip6_nxt;
if (nxt == IPV6_HOP || nxt == IPV6_ROUTING || nxt == IPV6_FRAG ||
nxt == IPV6_DEST || nxt == IPV6_MOBILITY || nxt == IPV6_IPV6 ||
nxt == IANA_UDP) {
*dispatch |= LOWPAN_IPHC_NH_MASK;
} else {
*buf++ = hdr->ip6_nxt;
}
return buf;
}
inline uint8_t *pack_hlim(uint8_t *buf, struct ip6_hdr *hdr, uint8_t *dispatch) {
if (hdr->ip6_hlim == 1) {
*dispatch |= LOWPAN_IPHC_HLIM_1;
} else if (hdr->ip6_hlim == 64) {
*dispatch |= LOWPAN_IPHC_HLIM_64;
} else if (hdr->ip6_hlim == 255) {
*dispatch |= LOWPAN_IPHC_HLIM_255;
} else {
*dispatch |= LOWPAN_IPHC_HLIM_NONE;
*buf++ = hdr->ip6_hlim;
}
return buf;
}
/* packs all non-multicast addresses */
/* @buf output buffer */
/* @addr the ipv6 address to be compressed */
/* @context_match_len if a context matches, how long the match is. must be multiple of 8 */
/* @l2addr the link-layer address correspoinding to the address (source or destination) */
/* @pan the destination pan ID */
/* @flags return argument; which address mode was selected */
uint8_t *pack_address(uint8_t *buf, struct in6_addr *addr, int context_match_len,
ieee154_addr_t *l2addr, ieee154_panid_t pan, uint8_t *flags) {
*flags = 0;
if (IS_LINKLOCAL(addr)) {
/* then we use stateless compression */
/* no bits to set, just pack the IID */
if (addr->s6_addr16[4] == 0 &&
addr->s6_addr16[5] == 0 &&
addr->s6_addr16[6] == 0) {
// then we use 16-bit mode. This isn't going to be popular...
*flags |= LOWPAN_IPHC_AM_16;
memcpy(buf, &addr->s6_addr[14], 2);
return buf += 2;
} else if (/* maybe it's a 16-bit address with the IID derived from the PANID + address */
(addr->s6_addr16[4] == htons(letohs(pan)) &&
addr->s6_addr16[5] == htons(0x00ff) &&
addr->s6_addr16[6] == htons(0xfe00) &&
(((l2addr->ieee_mode == IEEE154_ADDR_SHORT) &&
addr->s6_addr16[7] == htons(letohs(l2addr->i_saddr))))) ||
/* no? Maybe it's just a straight-up 64-bit EUI64 */
((l2addr->ieee_mode == IEEE154_ADDR_EXT) &&
(memcmp(&addr->s6_addr[8], &l2addr->i_laddr.data, 8) == 0))) {
/* in either case we can elide the addressing from the packet. */
*flags |= LOWPAN_IPHC_AM_0;
return buf;
} else {
*flags |= LOWPAN_IPHC_AM_64;
memcpy(buf, &addr->s6_addr[8], 8);
return buf + 8;
}
} else if (context_match_len > 0) {
int extra = 0;
// then we're using the context
*flags |= LOWPAN_IPHC_AC_CONTEXT;
if (context_match_len == 128) {
*flags |= LOWPAN_IPHC_AM_0;
} else if (bit_range_zero_p(&addr->s6_addr[0], context_match_len, 112) == 0) {
*flags |= LOWPAN_IPHC_AM_16;
memcpy(buf, &addr->s6_addr[14], 2);
extra = 2;
} else if (bit_range_zero_p(&addr->s6_addr[0], context_match_len, 64) == 0) {
*flags |= LOWPAN_IPHC_AM_64;
memcpy(buf, &addr->s6_addr[8], 8);
extra = 8;
} else {
*flags |= LOWPAN_IPHC_AM_128;
*flags &= ~LOWPAN_IPHC_AC_CONTEXT;
memcpy(buf, &addr->s6_addr[0], 16);
extra = 16;
}
return buf + extra;
} else if (IS_UNSPECIFIED(addr)) {
/* this case doesn't involve any compression */
*flags |= LOWPAN_IPHC_AC_CONTEXT | LOWPAN_IPHC_AM_128;
return buf;
} else {
/* otherwise we have to send the whole thing. */
*flags |= LOWPAN_IPHC_AM_128;
memcpy(buf, addr->s6_addr, 16);
return buf + 16;
}
}
/* Packs a multicast address into the smallest address possible. */
/* does not currently implement stateful multicast address compression */
/* also does not check to make sure it is a multicast address */
uint8_t *pack_multicast(uint8_t *buf, struct in6_addr *addr, uint8_t *flags) {
/* no need to set AC since it's zero */
*flags = 0;
if ((addr->s6_addr16[0] == htons(0xff02)) &&
(bit_range_zero_p(addr->s6_addr, 16, 120) == 0)) {
*flags |= LOWPAN_IPHC_AM_M_8;
*buf = addr->s6_addr[15];
return buf + 1;
} else if (bit_range_zero_p(addr->s6_addr, 16, 104) == 0) {
*flags |= LOWPAN_IPHC_AM_M_32;
*buf = addr->s6_addr[1];
memcpy(buf + 1, &addr->s6_addr[13], 3);
return buf + 4;
} else if (bit_range_zero_p(addr->s6_addr, 16, 88) == 0) {
*flags |= LOWPAN_IPHC_AM_M_48;
*buf = addr->s6_addr[1];
memcpy(buf + 1, &addr->s6_addr[11], 5);
return buf + 6;
} else {
*flags += LOWPAN_IPHC_AM_M_128;
memcpy(buf, addr->s6_addr, 16);
return buf + 16;
}
}
/* never pack the ports */
int pack_udp(uint8_t *buf, size_t cnt, struct ip6_packet *packet, int offset) {
struct udp_hdr udp;
if (cnt < 7) {
return -1;
}
if (iov_read(packet->ip6_data, offset, sizeof(struct udp_hdr), (void *)&udp) != sizeof(struct udp_hdr)) {
return -1;
}
*buf = LOWPAN_NHC_UDP_PATTERN | LOWPAN_NHC_UDP_PORT_FULL;
memcpy(buf + 1, &udp.srcport, 4);
memcpy(buf + 5, &udp.chksum, 2);
return 7;
}
int pack_ipnh(uint8_t *dest, size_t cnt, uint8_t *type, struct ip6_packet *packet, int offset) {
struct ip6_ext ext;
/* read the ipv6 extension header out for processing */
if (iov_read(packet->ip6_data, offset, 2, (void *)&ext) != 2)
return -1;
if (ext.ip6e_len > cnt)
return -1;
*dest = LOWPAN_NHC_IPV6_PATTERN;
switch (*type) {
case IPV6_HOP:
*dest |= LOWPAN_NHC_EID_HOP; break;
case IPV6_ROUTING:
*dest |= LOWPAN_NHC_EID_ROUTING; break;
case IPV6_FRAG:
*dest |= LOWPAN_NHC_EID_FRAG; break;
case IPV6_DEST:
*dest |= LOWPAN_NHC_EID_DEST; break;
case IPV6_MOBILITY:
*dest |= LOWPAN_NHC_EID_MOBILE; break;
default:
return -1;
}
/* store the next header type */
/* if it's compressable, we will compress it */
*type = ext.ip6e_nxt;
if (ext.ip6e_nxt == IPV6_HOP || ext.ip6e_nxt == IPV6_ROUTING || ext.ip6e_nxt == IPV6_FRAG ||
ext.ip6e_nxt == IPV6_DEST || ext.ip6e_nxt == IPV6_MOBILITY || ext.ip6e_nxt == IPV6_IPV6 ||
ext.ip6e_nxt == IANA_UDP) {
*dest |= LOWPAN_NHC_NH;
}
dest ++;
*dest++ = ext.ip6e_len;
/* copy the payload */
if (iov_read(packet->ip6_data, offset + 2, ext.ip6e_len - 2, dest) != ext.ip6e_len - 2)
return -1;
return ext.ip6e_len;
}
int pack_nhc_chain(uint8_t **dest, size_t cnt, struct ip6_packet *packet) {
uint8_t nxt = packet->ip6_hdr.ip6_nxt;
int offset = 0, rv;
/* @return offset is the offset into the unpacked ipv6 datagram */
/* dest is updated to show how far we have gotten in the packed data */
while (nxt == IPV6_HOP || nxt == IPV6_ROUTING || nxt == IPV6_FRAG ||
nxt == IPV6_DEST || nxt == IPV6_MOBILITY || nxt == IPV6_IPV6) {
rv = pack_ipnh(*dest, cnt, &nxt, packet, offset);
if (rv < 0) return -1;
/* it just so happens that LOWPAN_IPNH doesn't change the length
of the headers */
*dest += rv;
offset += rv;
cnt -= rv;
}
if (nxt == IANA_UDP) {
rv = pack_udp(*dest, cnt, packet, offset);
if (rv < 0) return -1;
offset += sizeof(struct udp_hdr);
*dest += rv;
}
return offset;
}
uint8_t *pack_ieee154_header(uint8_t *buf, size_t cnt,
struct ieee154_frame_addr *frame) {
uint8_t *ieee_hdr = buf;
uint16_t fcf;
// struct ieee154_header_base *ieee_hdr = (struct ieee154_header_base *)buf;
/* fill in the following 802.15.4 fields: */
/* length: will be set once we know how long the data is */
/* fcf: (set frame time, addressing modes) */
/* destpan: set to address in frame */
/* source and destination addresses */
buf = buf + IEEE154_MIN_HDR_SZ;
COPY_IEEE154_ADDR(ieee_dst);
COPY_IEEE154_ADDR(ieee_src);
fcf = (IEEE154_TYPE_DATA << IEEE154_FCF_FRAME_TYPE);
fcf |= (frame->ieee_src.ieee_mode << IEEE154_FCF_SRC_ADDR_MODE);
fcf |= (frame->ieee_dst.ieee_mode << IEEE154_FCF_DEST_ADDR_MODE);
ieee_hdr[1] = (fcf & 0xff);
ieee_hdr[2] = (fcf >> 8);
ieee_hdr[4] = frame->ieee_dstpan & 0xff;
ieee_hdr[5] = frame->ieee_dstpan >> 8;
return buf;
}
uint8_t * lowpan_pack_headers(struct ip6_packet *packet,
struct ieee154_frame_addr *frame,
uint8_t *buf, size_t cnt) {
uint8_t *dispatch, temp_dispatch, ctx_match_length;
if ((packet->ip6_hdr.ip6_vfc & IPV6_VERSION_MASK) != IPV6_VERSION) {
return NULL;
}
/* Packing strategy: */
/* 1. we never create 6lowpan broadcast or mesh frames */
/* 2. first, pack the IP headers and any other compressible header into the frame */
/* 3. if the data will fit into the frame, copy it in too */
/* 4. otherwise, do a memmove(3) and insert a fragmentation header */
/* We'll then test the whole thing as a unit. */
/* There is no support for using more then a single context, and no
support for stateful packing of multicast addresses.
These things are only supported in decompression, for compatibility.
*/
dispatch = buf;
*dispatch = LOWPAN_DISPATCH_BYTE_VAL;
*(dispatch+1) = 0;
buf += 2;
buf = pack_tcfl(buf, &packet->ip6_hdr, dispatch);
buf = pack_nh(buf, &packet->ip6_hdr, dispatch);
buf = pack_hlim(buf, &packet->ip6_hdr, dispatch);
/* back the source and destination addresses */
ctx_match_length = lowpan_extern_match_context(&packet->ip6_hdr.ip6_src, &temp_dispatch);
temp_dispatch = 0;
buf = pack_address(buf, &packet->ip6_hdr.ip6_src, ctx_match_length,
&frame->ieee_src, frame->ieee_dstpan, &temp_dispatch);
*(dispatch+1) |= temp_dispatch << LOWPAN_IPHC_SAM_SHIFT;
if (packet->ip6_hdr.ip6_dst.s6_addr[0] != 0xff) {
/* not multicast */
ctx_match_length = lowpan_extern_match_context(&packet->ip6_hdr.ip6_src, &temp_dispatch);
temp_dispatch = 0;
buf = pack_address(buf, &packet->ip6_hdr.ip6_dst, ctx_match_length,
&frame->ieee_dst, frame->ieee_dstpan, &temp_dispatch);
*(dispatch+1) |= temp_dispatch << LOWPAN_IPHC_DAM_SHIFT;
} else {
/* multicast */
buf = pack_multicast(buf, &packet->ip6_hdr.ip6_dst, &temp_dispatch);
*(dispatch + 1) |= (temp_dispatch << LOWPAN_IPHC_DAM_SHIFT) | LOWPAN_IPHC_AM_M;
}
return buf;
}
#if ! defined(HAVE_LOWPAN_EXTERN_MATCH_CONTEXT)
int lowpan_extern_read_context(struct in6_addr *addr, int context) {
return -1;
}
int lowpan_extern_match_context(struct in6_addr *addr, UNUSED uint8_t *ctx_id) {
return 0;
}
#endif
uint8_t *unpack_ieee154_hdr(uint8_t *buf, struct ieee154_frame_addr *frame) {
uint16_t fcf = ((uint16_t)buf[2] << 8) | buf[1];
frame->ieee_dstpan = htole16(((uint16_t)buf[5] << 8) | buf[4]);
frame->ieee_src.ieee_mode = (fcf >> IEEE154_FCF_SRC_ADDR_MODE) & 0x3;
frame->ieee_dst.ieee_mode = (fcf >> IEEE154_FCF_DEST_ADDR_MODE) & 0x3;
buf += IEEE154_MIN_HDR_SZ;
if (frame->ieee_dst.ieee_mode == IEEE154_ADDR_SHORT) {
memcpy(&frame->ieee_dst.i_saddr, buf, 2);
buf += 2;
} else if (frame->ieee_dst.ieee_mode == IEEE154_ADDR_EXT) {
memcpy(&frame->ieee_dst.i_laddr, buf, 8);
buf += 8;
}
if (frame->ieee_src.ieee_mode == IEEE154_ADDR_SHORT) {
memcpy(&frame->ieee_src.i_saddr, buf, 2);
buf += 2;
} else if (frame->ieee_src.ieee_mode == IEEE154_ADDR_EXT) {
memcpy(&frame->ieee_src.i_laddr, buf, 8);
buf += 8;
}
return buf;
}
uint8_t *unpack_tcfl(struct ip6_hdr *hdr, uint8_t dispatch, uint8_t *buf) {
uint8_t fl[3] = {0,0,0};
uint8_t tc = 0;
switch (dispatch & LOWPAN_IPHC_TF_MASK) {
case LOWPAN_IPHC_TF_ECN_DSCP:
tc = ((*buf) >> 6) & 0xff;
tc |= ((*buf) << 2) & 0xff;
buf += 1;
break;
case LOWPAN_IPHC_TF_ECN_FL:
tc = ((*buf) >> 6) & 0xff;
fl[2] = buf[0] & 0x0f;
fl[1] = buf[1];
fl[0] = buf[2];
buf += 3;
break;
case LOWPAN_IPHC_TF_ECN_DSCP_FL:
tc = ((*buf) >> 6) & 0xff;
tc |= ((*buf) << 2) & 0xff;
fl[2] = buf[1] & 0x0f;
fl[1] = buf[2];
fl[0] = buf[3];
buf += 4;
break;
}
hdr->ip6_flow = htonl(((uint32_t)0x6 << 28) |
((uint32_t)tc << 20) |
((uint32_t)fl[2] << 16) |
((uint32_t)fl[1] << 8) | fl[0]);
return buf;
}
uint8_t *unpack_nh(struct ip6_hdr *hdr, uint8_t dispatch, uint8_t *buf) {
if ((dispatch & LOWPAN_IPHC_NH_MASK) == LOWPAN_IPHC_NH_INLINE) {
hdr->ip6_nxt = *buf;
return buf + 1;
} else {
return buf;
}
}
uint8_t *unpack_hlim(struct ip6_hdr *hdr, uint8_t dispatch, uint8_t *buf) {
switch (dispatch & LOWPAN_IPHC_HLIM_MASK) {
case LOWPAN_IPHC_HLIM_1:
hdr->ip6_hlim = 1;
break;
case LOWPAN_IPHC_HLIM_64:
hdr->ip6_hlim = 64;
break;
case LOWPAN_IPHC_HLIM_255:
hdr->ip6_hlim = 255;
break;
default:
hdr->ip6_hlim = *buf;
return buf + 1;
}
return buf;
}
uint8_t *unpack_address(struct in6_addr *addr, uint8_t dispatch,
int context, uint8_t *buf,
ieee154_addr_t *frame, ieee154_panid_t pan) {
memset(addr, 0, 16);
if(!((dispatch & LOWPAN_IPHC_AC_CONTEXT))) {
/* stateless compression */
switch (dispatch & LOWPAN_IPHC_AM_MASK) {
case LOWPAN_IPHC_AM_128:
memcpy(addr, buf, 16);
return buf + 16;
case LOWPAN_IPHC_AM_64:
addr->s6_addr16[0] = htons(0xfe80);
memcpy(&addr->s6_addr[8], buf, 8);
return buf + 8;
case LOWPAN_IPHC_AM_16:
addr->s6_addr16[0] = htons(0xfe80);
memcpy(&addr->s6_addr[14], buf, 2);
return buf + 2;
default:
addr->s6_addr16[0] = htons(0xfe80);
if (frame->ieee_mode == IEEE154_ADDR_EXT) {
memcpy(&addr->s6_addr[8], frame->i_laddr.data, 8);
} else {
addr->s6_addr16[4] = leton16(pan);
addr->s6_addr[11] = 0xff;
addr->s6_addr[12] = 0xfe;
addr->s6_addr16[7] = leton16(frame->i_saddr);
}
return buf;
}
} else {
/* context-based compression */
if ((dispatch & LOWPAN_IPHC_AM_MASK) == LOWPAN_IPHC_AM_128) {
// unspecified address ::
return buf;
} else {
lowpan_extern_read_context(addr, context);
switch (dispatch & LOWPAN_IPHC_AM_MASK) {
case LOWPAN_IPHC_AM_64:
memcpy(&addr->s6_addr[8], buf, 8);
return buf + 8;
case LOWPAN_IPHC_AM_16:
memcpy(&addr->s6_addr[14], buf, 2);
return buf + 2;
case LOWPAN_IPHC_AM_0:
// not clear how to use this:
// "and 'possibly' link-layer addresses"
return buf;
}
}
}
return NULL;
}
uint8_t *unpack_multicast(struct in6_addr *addr, uint8_t dispatch,
int context, uint8_t *buf) {
memset(addr->s6_addr, 0, 16);
if (!(dispatch & LOWPAN_IPHC_AC_CONTEXT)) {
int amount;
switch (dispatch & LOWPAN_IPHC_AM_MASK) {
case LOWPAN_IPHC_AM_M_128:
memcpy(addr->s6_addr, buf, 16);
return buf+ 16;
case LOWPAN_IPHC_AM_M_48:
amount = 5;
goto copy;
case LOWPAN_IPHC_AM_M_32:
amount = 3;
copy:
addr->s6_addr[0] = 0xff;
addr->s6_addr[1] = buf[0];
memcpy(&addr->s6_addr[16-amount], buf + 1, amount);
return buf + 1 + amount;
case LOWPAN_IPHC_AM_M_8:
addr->s6_addr16[0] = htons(0xff02);
addr->s6_addr[15] = buf[0];
return buf + 1;
}
} else {
// stateful multicast compression
// all you need to do is read in the context here...
}
return NULL;
}
uint8_t *unpack_udp(uint8_t *dest, uint8_t *nxt_hdr, uint8_t *buf) {
struct udp_hdr *udp = (struct udp_hdr *)dest;
uint8_t dispatch = *buf++;
*nxt_hdr = IANA_ICMP;
// MUST be elided
udp->len = 0;
// MAY be elided if sufficient conditions are met
udp->chksum = 0;
/* decompress the ports */
switch (dispatch & LOWPAN_NHC_UDP_PORT_MASK) {
case LOWPAN_NHC_UDP_PORT_FULL:
udp->srcport = htons((buf[0] << 8) | buf[1]);
udp->dstport = htons((buf[2] << 8) | buf[3]);
buf += 4;
break;
case LOWPAN_NHC_UDP_PORT_SRC_FULL:
udp->srcport = htons((buf[0] << 8) | buf[1]);
udp->dstport = htons((0xF0 << 8) | buf[2]);
buf += 3;
break;
case LOWPAN_NHC_UDP_PORT_DST_FULL:
udp->srcport = htons((0xF0 << 8) | buf[0]);
udp->dstport = htons((buf[1] << 8) | buf[2]);
buf += 3;
break;
case LOWPAN_NHC_UDP_PORT_SHORT:
udp->srcport = htons((0xF0B << 4) | (buf[0] >> 4));
udp->dstport = htons((0xF0B << 4) | (buf[0] & 0x0F));
buf += 1;
break;
}
if (!(dispatch & LOWPAN_NHC_UDP_CKSUM)) {
udp->chksum = htons((buf[0] << 8) | buf[1]);
buf += 2;
}
return buf;
}
/**
* Unpack a single header that has been encoded using LOWPAN_NHC
* compression
*
* NOTE: in order simplify application support, this function does NOT
* convert the length field of ip extension headers to the form
* required by RFC2460: that is, the length value remains in units of
* octets. It is expected that all software within a 6lowpan network
* will expect this to be the case; edge routers communicating with
* the outside world should take care to convert the length octet
* when such packets are received, including removing any necessary
* padding options.
*/
uint8_t *unpack_ipnh(uint8_t *dest, size_t cnt, uint8_t *nxt_hdr, uint8_t *buf) {
if (((*buf) & LOWPAN_NHC_IPV6_MASK) == LOWPAN_NHC_IPV6_PATTERN) {
struct ip6_ext *ext = (struct ip6_ext *)dest;
uint8_t length;
// decompress an ipv6 extension header
// fill in the next header field of the previous header
switch ((*buf) & LOWPAN_NHC_EID_MASK) {
case LOWPAN_NHC_EID_HOP:
*nxt_hdr = IPV6_HOP; break;
case LOWPAN_NHC_EID_ROUTING:
*nxt_hdr = IPV6_ROUTING; break;
case LOWPAN_NHC_EID_FRAG:
*nxt_hdr = IPV6_FRAG; break;
case LOWPAN_NHC_EID_DEST:
*nxt_hdr = IPV6_DEST; break;
case LOWPAN_NHC_EID_MOBILE:
*nxt_hdr = IPV6_MOBILITY; break;
case LOWPAN_NHC_EID_IPV6:
/* ja if this happens we need to restart compression at the next byte... */
*nxt_hdr = IPV6_IPV6; break;
default:
return NULL;
}
// if the next header value is inline, copy that in.
if (!((*buf) & LOWPAN_NHC_NH)) {
buf ++;
ext->ip6e_nxt = *buf;
}
buf += 1;
length = *buf++;
if (cnt < length - 2)
return NULL;
// buf now points at the start of the extension header data
memcpy(dest + 2, buf, length - 2);
ext->ip6e_len = length;
return buf + length - 2;
} else if (((*buf) & LOWPAN_NHC_UDP_MASK) == LOWPAN_NHC_UDP_PATTERN) {
// packed UDP header
return unpack_udp(dest, nxt_hdr, buf);
}
return NULL;
}
uint8_t *unpack_nhc_chain(uint8_t **dest, size_t cnt, uint8_t *nxt_hdr, uint8_t *buf) {
uint8_t *dispatch;
int has_nhc = 1;
do {
dispatch = buf;
buf = unpack_ipnh(*dest, cnt, nxt_hdr, buf);
if (!buf) return NULL;
if (((*dispatch & LOWPAN_NHC_IPV6_MASK) == LOWPAN_NHC_IPV6_PATTERN)) {
struct ip6_ext *ext = (struct ip6_ext *)*dest;
/* need to update dest */
*dest += ext->ip6e_len;
cnt -= ext->ip6e_len;
if ((*dispatch & LOWPAN_NHC_NH) && ext->ip6e_len > 0) {
nxt_hdr = &ext->ip6e_nxt;
} else {
has_nhc = 0;
}
} else if (((*dispatch) & LOWPAN_NHC_UDP_MASK) == LOWPAN_NHC_UDP_PATTERN) {
*nxt_hdr = IANA_UDP;
has_nhc = 0;
*dest += sizeof(struct udp_hdr);
} else { has_nhc = 0; }
} while (has_nhc);
return buf;
}
uint8_t *lowpan_unpack_headers(uint8_t *dest, size_t dst_cnt,
struct ieee154_frame_addr *frame,
uint8_t *buf, size_t cnt) {
uint8_t *dispatch, *unpack_start = buf, *unpack_end;
int contexts[2] = {0, 0};
struct ip6_hdr *hdr = (struct ip6_hdr *)dest;
dispatch = buf;
buf += 2;
if (((*dispatch) & LOWPAN_DISPATCH_BYTE_MASK) != LOWPAN_DISPATCH_BYTE_VAL) {
return NULL;
}
/* extend the dispatch block if the context extension is present */
if ((*(dispatch + 1) & LOWPAN_IPHC_CID_MASK) == LOWPAN_IPHC_CID_PRESENT) {
contexts[0] = (*buf >> 4) & 0xf;
contexts[1] = (*buf) & 0xf;
buf += 1;
}
/* pull out the IP header fields */
buf = unpack_tcfl(hdr, *dispatch, buf);
buf = unpack_nh(hdr, *dispatch, buf);
buf = unpack_hlim(hdr, *dispatch, buf);
/* source address is always unicast compressed */
// printf("unpack source: %p (%x)\n", buf, *buf);
buf = unpack_address(&hdr->ip6_src,
((*(dispatch + 1) >> LOWPAN_IPHC_SAM_SHIFT)),
contexts[0],
buf,
&frame->ieee_src,
frame->ieee_dstpan);
if (!buf) return NULL;
/* destination address may use multicast address compression */
if (*(dispatch + 1) & LOWPAN_IPHC_M) {
// printf("unpack multicast: %p\n", buf);
buf = unpack_multicast(&hdr->ip6_dst,
((*(dispatch + 1) >> LOWPAN_IPHC_DAM_SHIFT)),
contexts[1],
buf);
// printf("unpack multicast: %p (%x)\n", buf, *buf);
} else {
buf = unpack_address(&hdr->ip6_dst,
((*(dispatch + 1) >> LOWPAN_IPHC_DAM_SHIFT)),
contexts[1],
buf,
&frame->ieee_dst,
frame->ieee_dstpan);
}
if (!buf) return NULL;
/* IPv6 header is complete */
/* at this point, (might) need to decompress a chain of headers compressed with LOWPAN_NHC */
unpack_end = (uint8_t *)(hdr + 1);
if ((*dispatch) & LOWPAN_IPHC_NH_MASK) {
buf = unpack_nhc_chain(&unpack_end,
dst_cnt - sizeof(struct ip6_hdr),
&hdr->ip6_nxt,
buf);
if (!buf) return NULL;
}
/* copy any remaining payload into the unpack region */
memcpy(unpack_end, buf, cnt - (buf - unpack_start));
/* return a pointer to the end of the unpacked data */
return unpack_end + (cnt - (buf - unpack_start));
}
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/compress/dctApp.c | <gh_stars>1-10
/*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Stanford University 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 COPYRIGHT HOLDERS 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 STANFORD
* UNIVERSITY OR ITS 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.
*/
/**
* @author <NAME> (<EMAIL>)
*/
#include <math.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "tinyos_macros.h"
#include "jpeghdr.h"
#include "jpegTOS.h"
#include "jpegUncompress.h"
int ROW=40*8;//40*8;
int COL=30*8;//30*8;
int QUALITY=9;
int BANDWIDTH=225000;
int IS_COLOR=1;
int main(int argc, char **argv)
{
printf("usage: dctApp.exe [.pgm|.ppm file] [max filesize]\n");
char filename[1024];
if (argc >= 2)
sprintf(filename,argv[1]);
else
sprintf(filename,"data//test.pgm");
char* ext=filename, *tmp;
while ( (tmp=strstr(ext,".")) != NULL )
{
ext=&tmp[1];
}
printf("input file:%s ext:%s\n",filename,ext);
int max_filesize=INT_MAX;
if (argc == 3)
max_filesize = atoi(argv[2]);
int bufShift;
if (strcmp(ext,"pgm")==0)
{
IS_COLOR=0;
bufShift=1;
}
else
{
IS_COLOR=1;
bufShift=3;
}
char filenameIn[1024];
sprintf(filenameIn, "data//testIn.%s",ext);
char filenameOut[1024];
sprintf(filenameOut, "data//testOut.%s",ext);
/*
char *filename = "data//test.pgm";
char *filenameIn = "data//testIn.pgm";
char *filenameOut = "data//testOut.pgm";
int bufShift=1; IS_COLOR=0;//*/
/*
char *filename = "data//_test.ppm";
char *filenameIn = "data//_testIn.ppm";
char *filenameOut = "data//_testOut.ppm";
int bufShift=3; IS_COLOR=1;//*/
FILE *fd;
FILE *fdIn;
FILE *fdOut;
if (!(fd = fopen(filename, "r")) ){
printf("Can't open data: %s\n", filename);
return 1;
}
if ( !(fdIn = fopen(filenameIn, "w"))
|| !(fdOut = fopen(filenameOut, "w")))
{
printf("Can't open data for writing\n");
fclose(fd);
return 1;
}
unsigned char line[320];
unsigned char input[320*240*bufShift+10];
uint8_t dct_code[BANDWIDTH];
int i,count;
for (i=0; i<4; i++)
{
fgets(line, 320, fd);
fprintf(fdIn,"%s",line);
fprintf(fdOut,"%s",line);
}
i=0;
while( (count=fread(line, 1, 320, fd))>0)
{
memcpy(&(input[i]),line,count);
i+=count;
}
unsigned char input_save[320*240*bufShift+10];
memcpy(input_save, input, sizeof(input));
uint32_t idx;
if (IS_COLOR)
idx = encodeColJpeg(input,dct_code,BANDWIDTH,ROW,COL,QUALITY,bufShift);
else
idx = encodeJpeg(input,dct_code,BANDWIDTH,ROW,COL,QUALITY,bufShift,0);
FILE *fd_tmp1=0;
if (!(fd_tmp1 = fopen("data//coded.huf", "w")) ){
printf("Can't open %s file for writing\n",filename);
return 1;
}
if (idx > max_filesize)
idx = max_filesize;
fwrite(dct_code,1,idx,fd_tmp1);
fclose(fd_tmp1);
printf("CODE length: %d b (%d msgs)\n", (int)idx,(int)idx/64+1);
printf("written coded.huf file\n");
uint8_t recovered[320*240*bufShift+10];
memset(recovered,0,sizeof(recovered));
code_header_t header;
decodeJpegFile("data//coded.huf", recovered, &header);
double rmse=0.0;
for (i=0; i<ROW*COL; i++)
rmse+= (recovered[i]-input_save[i])*(recovered[i]-input_save[i]);
rmse = sqrt(rmse/ROW/COL);
printf("PSNR: %f\n",20*log(255/rmse));
printf("RMSE: %f\n",rmse);
{
fwrite(input_save,1,ROW*COL*bufShift,fdIn);
fwrite(recovered,1,ROW*COL*bufShift,fdOut);
}
fclose(fd);
fclose(fdIn); printf("written %s\n",filenameIn);
fclose(fdOut); printf("written %s\n",filenameOut);
return 1;
}
|
tinyos-io/tinyos-3.x-contrib | eon/apps/eserver/impl/stargate/mImpl.c | <reponame>tinyos-io/tinyos-3.x-contrib<filename>eon/apps/eserver/impl/stargate/mImpl.c<gh_stars>1-10
#include "mImpl.h"
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <netdb.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <poll.h>
#define SERVER_PORT 80
#define BUFFER_SIZE 8192
const uint8_t minPathState[NUMPATHS] =
{ STATE_BASE, STATE_BASE, STATE_BASE, STATE_BASE, STATE_BASE, STATE_TEXT,
STATE_TEXT, STATE_TEXT, STATE_TEXT, STATE_TEXT, STATE_TEXT, STATE_TEXT, STATE_TEXT, STATE_TEXT, STATE_TEXT,
STATE_TEXT, STATE_TEXT, STATE_BASE };
#include "mImpl.h"
int socket_in_use[1024], s, root_len;
struct sockaddr_in server_addr;
fd_set read_fds;
char *root;
int suffixTest(char *val, char *suffix) {
int len = strlen(val);
int s_len = strlen(suffix);
int i;
for (i=0;i<s_len;i++) {
if (val[len-i]!=suffix[s_len-i])
return 0;
}
return 1;
}
void closeSocket(int socket) {
close(socket);
if (socket > -1) {
if (socket < 1024)
socket_in_use[socket] = 2;
else
printf("ERR, socket to large\n");
}
}
void returnSocket(int socket) {
socket_in_use[socket] = 0;
}
void writeHeaders(int socket_in, bool close, int length, char *content) {
char msg[128];
sprintf(msg, "Content-Length: %d\r\n", length);
write(socket_in, msg, strlen(msg));
sprintf(msg, "Server: Markov 0.1\r\n");
write(socket_in, msg, strlen(msg));
sprintf(msg, "Content-Type: %s\r\n", content);
write(socket_in, msg, strlen(msg));
if (close)
write(socket_in, "Connection: close\r\n",19);
write(socket_in, "\r\n", 2);
}
void
init (int argc, char **argv)
{
int old_flags, i;
for (i=0;i<1024;i++)
socket_in_use[i] = 2;
s = socket(AF_INET,SOCK_STREAM,0);
int val = 1;
if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
{
perror("setsockopt: ");
exit(1);
}
if (argc < 3) {
fprintf (stderr, "Usage: %s <root-dir> <port-number> \n", argv[0]);
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
FD_ZERO(&read_fds);
FD_SET(s, &read_fds);
root = argv[1];
root_len = strlen(root);
if ((bind(s,(struct sockaddr*) &server_addr, sizeof(struct sockaddr))) < 0) {
perror("Bind: ");
return;
}
if (listen(s,50000)<0) {
perror("Listen : ");
return;
}
if (server_addr.sin_addr.s_addr) {
fprintf (stderr, "listening on address %s, port %d\n",
server_addr.sin_addr.s_addr, SERVER_PORT);
} else {
fprintf (stderr, "listening on address (NULL), port %d\n",SERVER_PORT);
}
}
// IN: [int socket, bool close, int length, char* content, char* output]
// OUT: []
int
Reply (Reply_in * in, Reply_out * out)
{
//if (in->close) {
closeSocket(in->socket);
//}
//else
//returnSocket(in->socket);
return 0;
}
// IN: [int socket]
// OUT: [int socket, bool close, char* file]
int
ReadRequest (ReadRequest_in * in, ReadRequest_out * out)
{
char buf[BUFFER_SIZE];
int rd,i;
int length = 0;
int doneRequest = 0;
out->file = 0;
out->close = 0;
//DEBUG printf("ReadRequest in\n");
do {
rd = read(in->socket, buf+length, BUFFER_SIZE-length);
if (rd == -1) {
perror("Reading request");
closeSocket(in->socket);
return -1;
}
else if (!rd) {
usleep(1000*10);
}
else {
char *start = buf;
char *end;
for (i=0;i<rd;i++) {
if (buf[i] == '\r') {
buf[i++] = 0;
buf[i] = 0; // Get rid of the \n
//DEBUG printf("%s\n", start);
if (length == 0) { // We're done...
doneRequest = 1;
break;
}
else if (start[0] == 'G' && start[1] == 'E' && start[2] == 'T') {
start = strchr(start, ' ')+1;
end = strchr(start+1, ' ');
*end = 0;
while (*end != 'H')
end++;
while (*end != '/')
end++;
end++;
int major = *end-'0'; // HACK HACK HACK Assumes ASCII
end+=2;
int minor = *end-'0'; // HACK HACK HACK Assumes ASCII
if (major != 1 || (minor > 1))
printf("Urm, HTTP version: %d.%d we may be in trouble...\n",
major, minor);
if (major == 1 && minor == 0) {
out->close = 1;
}
if (*start == '/')
start++;
out->file = strdup(start);
}
else if (start[0] == 'C' && start[1] == 'o' && start[2] == 'n' &&
strstr(start, "close")) {
out->close = 1;
}
start=buf+i+1;
length = 0;
}
else {
length++;
}
}
if (!doneRequest) {
strncpy(buf, start, length);
}
}
} while (!doneRequest);
if (!out->file) {
out->file = "/sys_error.html";
}
out->socket = in->socket;
// DEBUG printf("Request:%s:\n", out->request);
return 0;
}
// IN: [int socket]
void
BadRequest (ReadRequest_in * in, int err)
{
char *msg = "HTTP/1.1 404 File not found\r\n";
write(in->socket, msg, strlen(msg));
msg = "<html><body><h2>404 File Not Found!</h2><br>ReadRequest error</body></html>\n";
writeHeaders(in->socket, 1,strlen(msg), "text/html");
write(in->socket, msg, strlen(msg));
closeSocket(in->socket);
}
// IN: [int socket, bool close, char* file]
// OUT: []
int
Handler (Handler_in * in, Handler_out * out)
{
}
// IN: []
// OUT: [int socket]
int
Listen (Listen_out * out)
{
//out->type = in->type;
/* int bind_socket = -1;
// out->type = in->type;
// out->filename = in->request.url;
struct sockaddr_in server_addr;
bind_socket = socket(AF_INET, SOCK_STREAM, 0);
int val = 1;
if (setsockopt(bind_socket, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val)) < 0)
{
perror("setsockopt: ");
exit(1);
}
server_addr.sin_family = AF_INET;
server_addr.sin_port = htons(SERVER_PORT);
server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
if ((bind(bind_socket,(struct sockaddr*) &server_addr, sizeof(struct sockaddr))) < 0) {
perror("Bind: ");
return -1;
}
if (listen(bind_socket,500)<0) {
perror("Listen : ");
return -1;
}
printf ("listening on address %X, port %d\n", server_addr.sin_addr.s_addr, SERVER_PORT);
struct timeval select_timeout;
select_timeout.tv_sec = 5;
select_timeout.tv_usec = 0;
fd_set read_fds;
FD_ZERO(&read_fds);
FD_SET(bind_socket, &read_fds);
int max = bind_socket;
*/
// int sel;
// if ( sel=select(max+1, &read_fds, NULL, NULL, &select_timeout) > 0)
// {
socklen_t length = sizeof(struct sockaddr);
out->socket = accept(s, (struct sockaddr *)&server_addr,&length);
if(out->socket==-1)
return -1;
int optval = 1;
if (setsockopt (out->socket, SOL_TCP, TCP_NODELAY, &optval, sizeof (optval)) < 0)
{
perror("setsockopt");
}
//socket_in_use[out->socket] = 1;
// }
return 0;
}
// IN: [int socket]
// OUT: []
int
Page (Page_in * in, Page_out * out)
{
}
// IN: [int socket, bool close, char* file]
// OUT: [int socket, bool close, int length, char* content, char* output]
int
ReadWrite (ReadWrite_in * in, ReadWrite_out * out)
{
FILE *f;
int rd;
struct stat sb;
int res;
char file_name[128];
out->socket = in->socket;
out->close = in->close;
sprintf(file_name, "%s/%s", root, in->file);
//DEBUG printf("Looking for:%s:\n", file_name);
res = stat(file_name, &sb);
int file_size = sb.st_size;
if (res < 0) {
return 404;
}
else {
int ix=0;
char *ptr;
int header_len;
if (suffixTest(in->file, ".html")) {
out->content = "text/html";
}
else if (suffixTest(in->file, ".png")) {
out->content = "image/png";
}
else if (suffixTest(in->file, ".jpg") || suffixTest(in->file, ".jpeg")) {
out->content = "image/jpeg";
}
else if (suffixTest(in->file, ".gif")) {
out->content = "image/gif";
}
else if (suffixTest(in->file, ".mp4")) {
out->content = "video/mp4";
}
else if (suffixTest(in->file, ".mpeg")) {
out->content = "video/mpeg";
}
else if (suffixTest(in->file, ".mov")) {
out->content = "video/mov";
}
else if (suffixTest(in->file, ".wav")) {
out->content = "audio/wav";
}
else if (suffixTest(in->file, ".mpeg")) {
out->content = "video/mpeg";
}
else if (suffixTest(in->file, ".gif")) {
out->content = "image/gif";
}
else {
out->content = "text/plain";
}
//out->content="text/plain";
char hdrs[8192];
if (in->close) {
sprintf(hdrs, "HTTP/1.1 200 OK\r\nContent-type: %s\r\nServer: Markov 0.1\r\nConnection: close\r\nContent-Length: %d\r\n\r\n",
out->content, file_size);
}
else {
sprintf(hdrs, "HTTP/1.1 200 OK\r\nContent-type: %s\r\nServer: Markov 0.1\r\nContent-Length: %d\r\n\r\n",
out->content, file_size);
}
//printf(hdrs);
header_len = strlen(hdrs);
int written = write(in->socket, hdrs, header_len);
while (written < header_len) {
if (written < 0) {
perror("Writing");
closeSocket(in->socket);
return -1;
}
written += write(in->socket, hdrs+written, header_len-written);
}
//out->length = sb.st_size+header_len;
int fd = open(file_name, O_RDONLY);
if (fd < 0) {
perror("Reading");
closeSocket(in->socket);
return -1;
}
//out->output = (char *)malloc(out->length);
//memcpy(out->output, hdrs, header_len);
//ptr = out->output+strlen(hdrs);
char *pos;
do {
if ((rd = read(fd, hdrs, 8192)) < 0) {
perror("read");
closeSocket(in->socket);
return 0;
}
ix += rd;
pos = hdrs;
while (rd > 0) {
int ret = write(in->socket, hdrs, rd);
if (ret < 0) {
perror("write");
closeSocket(in->socket);
close(fd);
return 0;
}
else if (ret == 0) {
rd = 0;
break;
}
else {
pos += ret;
rd -= ret;
}
}
} while (ix < sb.st_size);
close(fd);
}
//DEBUG printf("Done reading for:%s:\n", file_name);
return 0;
}
// IN: [int socket, bool close, char* file]
void
FourOhFor (ReadWrite_in * in, int err)
{
char *msg = "HTTP/1.1 404 File not found\r\n";
write(in->socket, msg, strlen(msg));
msg = "<html><body><h2>404 File Not Found!</h2><br>ReadWrite Error.</body></html>\n";
writeHeaders(in->socket, in->close, strlen(msg), "text/html");
write(in->socket, msg, strlen(msg));
closeSocket(in->socket);
}
// IN: [int socket, bool close, char* file]
// OUT: []
int
Unavailable (Unavailable_in * in, Unavailable_out * out)
{
char *msg;
msg = "HTTP/1.1 400 Bad Request\r\n";
if (write(in->socket, msg, strlen(msg)) != -1) {
msg = "<html><body><h2>400 Bad Request!</h2></body></html>\n";
writeHeaders(in->socket, 1, strlen(msg), "text/html");
write(in->socket, msg, strlen(msg));
}
closeSocket(in->socket);
}
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tools/quanto/compression/test.c | #include <stdio.h>
#include "libquantocode.h"
enum {
SIZE = 100,
};
uint32_t list[100] = {
1, 2, 3, 4, 5, 6, 20, 20, 112, 239,
100, 239, 139, 30, 20, 223, 20, 239, 239, 223,
2390, 2039, 1012, 2432, 4055, 2139, 2955, 6000, 9920, 8244,
24539, 550, 15573, 32204, 34120, 32239, 11137, 20, 47, 253,
239, 112, 173, 20, 220, 204, 116, 239, 76, 239,
239, 112, 173, 239, 171, 173, 59, 239, 239, 1332332187u,
239, 173, 133, 213, 173, 204, 239, 2093333321u, 20, 239,
239, 239, 216, 20, 239, 10, 239, 239, 239, 20,
204, 109, 82, 239, 207, 82, 20, 173, 20, 112,
204, 133, 239, 173, 20, 239, 239, 22, 239, 173,
};
enum {
OK = 1,
FAIL = 0,
};
int testEliasDelta() {
int i;
uint32_t d;
bitBuf *buf;
bool ok = 1;
buf = bitBuf_new(400);
for (i = 0; i < SIZE; i++) {
elias_delta_encode(list[i], buf);
}
for (i = 0; i < SIZE; i++) {
d = elias_delta_decode(buf);
ok &= (d == list[i]);
printf("decoded %u (should be %u)\n", d, list[i]);
}
return (ok)?OK:FAIL;
}
int main() {
int r;
r = testEliasDelta();
printf("testEliasDelta : %s\n", (r == OK)?"ok":"fail");
return (r == OK)?0:1;
}
|
tinyos-io/tinyos-3.x-contrib | iowa/T2.tsync/IAtsync/PowCon.h | #ifndef POWCON_STRUCT
typedef struct {
uint16_t period; // period length in 1/8 seconds (max = 2.2 hours)
uint8_t livetime; // alive time per period in 1/8 seconds (max = 32 sec)
uint8_t priority; // priority within interval (for tie-breaks)
} powsched;
typedef powsched * powschedPtr;
enum { WAKE_slots = uniqueCount("PowCon") };
#define POWCON_STRUCT
#endif
|
tinyos-io/tinyos-3.x-contrib | shimmer/apps/AccelECG/AccelECG.h | /*
* Copyright (c) 2007, Intel Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* 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.
*
* Neither the name of the Intel Corporation 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 COPYRIGHT HOLDERS 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 COPYRIGHT OWNER 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.
*
* Author: <NAME>
* November, 2007
*/
/*
* @author <NAME>
* @date November, 2007
*
* @author <NAME>
* @date May 13, 2009 - ported to TinyOS 2.x
*/
#ifndef ACCELECG_H
#define ACCELECG_H
enum {
NUM_ACCEL_CHANS = 3
};
enum {
NUM_GYRO_CHANS = 3
};
enum {
SHIMMER_REV1 = 0
};
enum {
PROPRIETARY_DATA_TYPE = 0xFF,
STRING_DATA_TYPE = 0xFE
};
enum {
SAMPLING_1000HZ = 1,
SAMPLING_500HZ = 2,
SAMPLING_250HZ = 4,
SAMPLING_200HZ = 5,
SAMPLING_166HZ = 6,
SAMPLING_125HZ = 8,
SAMPLING_100HZ = 10,
SAMPLING_50HZ = 20,
SAMPLING_10HZ = 100,
SAMPLING_0HZ_OFF = 255
};
enum {
FRAMING_SIZE = 0x4,
FRAMING_CE_COMP = 0x20,
FRAMING_CE_CE = 0x5D,
FRAMING_CE = 0x7D,
FRAMING_BOF = 0xC0,
FRAMING_EOF = 0xC1,
FRAMING_BOF_CE = 0xE0,
FRAMING_EOF_CE = 0xE1,
};
#endif // ACCELECG_H
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/ieee154-interface.c |
#undef __BLOCKS__
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <netinet/in.h>
#include <pthread.h>
#include <Ieee154.h>
#include <signal.h>
#include "serialsource.h"
#include "serialprotocol.h"
#include "sfsource.h"
#include "lib6lowpan/blip-pc-includes.h"
#include "lib6lowpan/lib6lowpan.h"
#include "lib6lowpan/iovec.h"
#include "tun_dev.h"
#include "logging.h"
#include "devconf.h"
#include "device-config.h"
#include "queue.h"
/* configuration about us */
struct config device_config;
/* packet sources */
int tun_fd;
serial_source ser_src;
/* reader-writer threads */
pthread_t pan_writer, tun_reader;
pthread_t pan_reader;
pthread_mutex_t pan_lock;
int write_pan_packet(uint8_t *buf, int len) {
int rv;
pthread_mutex_lock(&pan_lock);
rv = write_serial_packet(ser_src, buf, len);
pthread_mutex_unlock(&pan_lock);
return rv;
}
void *read_pan_packet(int *len) {
void *rv = NULL;
fd_set fs;
/* int fd = serial_source_fd(ser_src); */
/* FD_ZERO(&fs); */
/* FD_SET(fd, &fs); */
/* pthread_mutex_lock(&pan_lock); */
/* if (serial_source_empty(ser_src)) { */
/* pthread_mutex_unlock(&pan_lock); */
/* while (select(fd + 1, &fs, NULL, NULL, NULL) < 0) { */
/* FD_ZERO(&fs); */
/* FD_SET(fd, &fs); */
/* } */
/* } else { */
/* pthread_mutex_unlock(&pan_lock); */
/* } */
/* pthread_mutex_lock(&pan_lock); */
/* if (!serial_source_empty(ser_src)) { */
rv = read_serial_packet(ser_src, len);
/* } */
/* pthread_mutex_unlock(&pan_lock); */
return rv;
}
/* message queues for either direction... */
struct blocking_queue pan_q;
struct blocking_queue tun_q;
enum { N_RECONSTRUCTIONS = 30,
RECONSTRUCT_CLEAN_INT = 5,};
struct lowpan_reconstruct reconstructions[N_RECONSTRUCTIONS];
pthread_t reconstruct_thread;
pthread_mutex_t reconstruct_lock;
enum {
S_RUNNING,
S_STOPPING,
};
sig_atomic_t run_state = S_RUNNING;
void stderr_msg(serial_source_msg problem) {
// fprintf(stderr, "Note: %i\n", problem);
}
void *xmalloc(size_t sz) {
void *rv = malloc(sz);
if (rv) return rv;
fatal("xmalloc: out of memory\n");
exit (1);
}
int resolve_l2_addresses(struct ip6_packet *pkt, struct ieee154_frame_addr *fr) {
char print_buf[128];
memset(fr, 0, sizeof(struct ieee154_frame_addr));
if (pkt->ip6_hdr.ip6_src.s6_addr16[0] == htons(0xfe80)) {
fr->ieee_src.ieee_mode = IEEE154_ADDR_EXT;
memcpy(fr->ieee_src.i_laddr.data, &pkt->ip6_hdr.ip6_src.s6_addr[8], 8);
if (memcmp(fr->ieee_src.i_laddr.data, device_config.eui64.data, 8) != 0) {
debug("wrong source address for link local communication, dropping\n");
// ieee154_print(&fr->ieee_src, print_buf, 128);
// debug("%s\n", print_buf);
return -1;
}
} else {
return -1;
}
if (pkt->ip6_hdr.ip6_dst.s6_addr16[0] == htons(0xfe80)) {
if (pkt->ip6_hdr.ip6_dst.s6_addr16[5] == ntohs(0x00FF) &&
pkt->ip6_hdr.ip6_dst.s6_addr16[6] == ntohs(0xFE00)) {
if (ntohs(pkt->ip6_hdr.ip6_dst.s6_addr16[4]) == device_config.panid) {
fr->ieee_dst.ieee_mode = IEEE154_ADDR_SHORT;
fr->ieee_dst.i_saddr = htole16(ntohs(pkt->ip6_hdr.ip6_dst.s6_addr16[7]));
} else {
warn("Cross-pan RFC4944 address mode not supported!\n");
return -1;
}
} else {
fr->ieee_dst.ieee_mode = IEEE154_ADDR_EXT;
memcpy(fr->ieee_dst.i_laddr.data, &pkt->ip6_hdr.ip6_dst.s6_addr[8], 8);
}
ieee154_print(&fr->ieee_dst, print_buf, 128);
debug("LL scope: L2 address is %s\n", print_buf);
} else {
return -1;
}
fr->ieee_dstpan = htole16(device_config.panid);
return 0;
}
void init_reconstruct() {
int i;
memset(reconstructions, 0, sizeof(reconstructions));
for (i = 0; i < N_RECONSTRUCTIONS; i++) {
reconstructions[i].r_timeout = T_UNUSED;
reconstructions[i].r_buf = NULL;
}
pthread_mutex_init(&reconstruct_lock, NULL);
}
struct lowpan_reconstruct *get_reconstruct(uint16_t key, uint16_t tag) {
struct lowpan_reconstruct *ret = NULL;
int i;
for (i = 0; i < N_RECONSTRUCTIONS; i++) {
struct lowpan_reconstruct *recon = &reconstructions[i];
if (recon->r_tag == tag &&
recon->r_source_key == key) {
if (recon->r_timeout > T_UNUSED) {
recon->r_timeout = T_ACTIVE;
ret = recon;
goto done;
} else if (recon->r_timeout < T_UNUSED) {
// if we have already tried and failed to get a buffer, we
// need to drop remaining fragments.
ret = NULL;
goto done;
}
}
if (recon->r_timeout == T_UNUSED) {
ret = recon;
}
}
done:
return ret;
}
void *age_reconstruct(void * arg) {
time_t last_cleaning = time(NULL);
while (run_state == S_RUNNING) {
int i;
if (last_cleaning > time(NULL) + RECONSTRUCT_CLEAN_INT) {
pthread_mutex_lock(&reconstruct_lock);
for (i = 0; i < N_RECONSTRUCTIONS; i++) {
switch (reconstructions[i].r_timeout) {
case T_ACTIVE:
reconstructions[i].r_timeout = T_ZOMBIE; break; // age existing receptions
case T_FAILED1:
reconstructions[i].r_timeout = T_FAILED2; break; // age existing receptions
case T_ZOMBIE:
case T_FAILED2:
// deallocate the space for reconstruction
debug("timing out buffer: src: %i tag: %i\n",
reconstructions[i].r_source_key, reconstructions[i].r_tag);
if (reconstructions[i].r_buf != NULL) {
free(reconstructions[i].r_buf);
}
memset(&reconstructions[i], 0, sizeof(reconstructions[i]));
reconstructions[i].r_timeout = T_UNUSED;
reconstructions[i].r_buf = NULL;
break;
}
}
pthread_mutex_unlock(&reconstruct_lock);
}
sleep(1);
}
}
/* blocks until there's a new message for the pan. then sends it out over the radio. */
void *pan_write(void * arg) {
while (run_state == S_RUNNING) {
int rv = -1;
uint8_t *frame = queue_pop(&pan_q);
/* the first byte is the dispatch value */
/* the second byte is the length of the IEEE154 frame, not including the length byte */
print_buffer(frame, frame[1] + 2);
while (rv < 0) {
rv = write_pan_packet(frame, frame[1] + 2);
debug("pan_write: length: %i result: %i\n", frame[1] + 2, rv);
// SDH : this isn't supposed to work with pthreads, and doesn't, at least on Linux
// usleep(1e3);
}
free(frame);
}
}
void deliver_to_kernel(struct lowpan_reconstruct *recon) {
struct ip6_packet pkt;
struct ip_iovec v;
struct ip6_hdr *iph = (struct ip6_hdr *)recon->r_buf;
iph->ip6_plen = htons(recon->r_bytes_rcvd - sizeof(struct ip6_hdr));
{
struct ip6_ext *cur = (struct ip6_ext *)(recon->r_buf + sizeof(struct ip6_hdr));
uint8_t nxt = iph->ip6_nxt;
while (nxt == IPV6_HOP || nxt == IPV6_ROUTING || nxt == IPV6_FRAG ||
nxt == IPV6_DEST || nxt == IPV6_MOBILITY || nxt == IPV6_IPV6) {
nxt = cur->ip6e_nxt;
cur = cur + cur->ip6e_len;
if (cur->ip6e_len == 0) {
break;
}
}
if (nxt == IANA_UDP) {
struct udp_hdr *udp = (struct udp_hdr *)cur;
udp->len = htons(recon->r_bytes_rcvd - ((uint8_t *)cur - recon->r_buf));
}
}
/* set up the IPv6 packet structure */
memcpy(&pkt.ip6_hdr, iph, sizeof(struct ip6_hdr));
pkt.ip6_data = &v;
v.iov_base = recon->r_buf + sizeof(struct ip6_hdr);
v.iov_len = ntohs(iph->ip6_plen);
v.iov_next = NULL;
tun_write(tun_fd, &pkt);
free(recon->r_buf);
memset(recon, 0, sizeof(struct lowpan_reconstruct));
recon->r_timeout = T_UNUSED;
recon->r_buf = NULL;
}
void *pan_read(void * arg) {
while (run_state == S_RUNNING) {
struct packed_lowmsg lowmsg;
struct ieee154_frame_addr frame_address;
int length;
uint8_t *frame = read_pan_packet(&length);
uint8_t *buf = frame + 1; /* skip the dispatch byte */
if (!frame)
continue;
if (frame[0] != TOS_SERIAL_802_15_4_ID) {
warn("invalid frame received!\n");
goto done;
}
info("serial packet arrived! (len: %i)\n", length);
print_buffer(buf, length);
buf = unpack_ieee154_hdr(buf, &frame_address);
length -= buf - frame;
if (!buf) {
warn("unpacking IEEE154 header failed!\n");
goto done;
}
lowmsg.data = buf;
lowmsg.len = length;
lowmsg.headers = getHeaderBitmap(&lowmsg);
if (lowmsg.headers == LOWMSG_NALP) {
warn("lowmsg NALP!\n");
goto done;
}
if (hasFrag1Header(&lowmsg) || hasFragNHeader(&lowmsg)) {
struct lowpan_reconstruct *recon;
uint16_t tag, source_key;
int rv;
pthread_mutex_lock(&reconstruct_lock);
source_key = ieee154_hashaddr(&frame_address.ieee_src);
getFragDgramTag(&lowmsg, &tag);
recon = get_reconstruct(source_key, tag);
if (!recon) {
pthread_mutex_unlock(&reconstruct_lock);
goto done;
}
if (hasFrag1Header(&lowmsg))
rv = lowpan_recon_start(&frame_address, recon, buf, length);
else rv = lowpan_recon_add(recon, buf, length);
if (rv < 0) {
recon->r_timeout = T_FAILED1;
pthread_mutex_unlock(&reconstruct_lock);
goto done;
} else {
recon->r_timeout = T_ACTIVE;
recon->r_source_key = source_key;
recon->r_tag = tag;
}
if (recon->r_size == recon->r_bytes_rcvd) {
deliver_to_kernel(recon);
}
pthread_mutex_unlock(&reconstruct_lock);
} else {
int rv;
struct lowpan_reconstruct recon;
buf = getLowpanPayload(&lowmsg);
if ((rv = lowpan_recon_start(&frame_address, &recon, buf, length)) < 0) {
warn("reconstruction failed!\n");
goto done;
}
if (recon.r_size == recon.r_bytes_rcvd) {
deliver_to_kernel(&recon);
} else {
free(recon.r_buf);
}
}
done:
free(frame);
}
}
void *tun_dev_read(void * arg) {
uint8_t buf[2500], read_buf[1500], *fragment;
struct ip6_packet *packet = (struct ip6_packet *)buf;
struct ip_iovec v;
struct lowpan_ctx ctx;
struct ieee154_frame_addr fr;
int len, i;
packet->ip6_data = &v;
v.iov_next = NULL;
v.iov_base = &buf[sizeof(struct ip6_packet)];
ctx.tag = 0;
while (run_state == S_RUNNING) {
len = tun_read(tun_fd, read_buf, 1500);
len -= sizeof(struct tun_pi);
if (len < 0) {
debug("tun_dev_read: read error\n");
continue;
}
/* set up the ip6_packet structure */
memcpy(&packet->ip6_hdr, read_buf + sizeof(struct tun_pi), len);
v.iov_len = len;
ctx.offset = 0;
ctx.tag++;
if (resolve_l2_addresses(packet, &fr) < 0) {
debug("could not resolve next hop; dropping\n");
continue;
}
fragment = xmalloc(128);
/* PPDU : max length 127 (all inclusive) */
/* 1 len + 2 FCS, so max buffer length is 126 (including length) */
while ((len = lowpan_frag_get(&fragment[1], 126, packet, &fr, &ctx)) > 0) {
fragment[0] = TOS_SERIAL_802_15_4_ID;
fragment[1] = len - 1 + 2;
print_buffer(fragment, len + 1);
printf("PUSH: %i\n", queue_push(&pan_q, fragment));
fragment = xmalloc(128);
}
free(fragment);
}
}
void configure_setparams(struct config *c, int cmdno) {
uint8_t buf[sizeof(config_cmd_t) + 1];
config_cmd_t *cmd = (config_cmd_t *)(&buf[1]);
int rv;
memset(buf, 0, sizeof(buf));
buf[0] = TOS_SERIAL_DEVCONF;
cmd->cmd = cmdno;
cmd->rf.short_addr = 12;// c->router_addr.s6_addr16[7]; // is network byte-order
cmd->rf.lpl_interval = htons(c->lpl_interval);
cmd->rf.channel = c->channel;
cmd->retx.retries = htons(c->retries);
cmd->retx.delay = htons(c->delay);
rv = write_pan_packet(buf, CONFIGURE_MSG_SIZE + 1);
debug("configure result: %i\n", rv);
}
/*
* At startup, set the L2 properties of the attached device, and read
* back the EUI-64. We'll need that to form the link-local address.
*/
int setup_serial(char *device, char *rate, struct config *c) {
uint8_t *ser_data;
int ser_len = 0;
config_reply_t *reply;
/* open the serial source as blocking */
ser_src = open_serial_source(device, platform_baud_rate(rate), 0, stderr_msg);
if (!ser_src) return -1;
/* kill ourselves if anything hangs */
alarm(5);
/* set the parameters */
configure_setparams(c, CONFIG_REBOOT);
/* wait to hear back... */
ser_data = read_serial_packet(ser_src, &ser_len);
if (!ser_data) return -1;
free(ser_data);
configure_setparams(c, CONFIG_SET_PARM);
ser_data = read_serial_packet(ser_src, &ser_len);
if (ser_data[0] != TOS_SERIAL_DEVCONF) return -1;
reply = (config_reply_t *)&ser_data[1];
memcpy(c->eui64.data, reply->ext_addr, 8);
free(ser_data);
alarm(0);
return 0;
}
int main(int argc, char **argv) {
char print_buf[128], dev[IF_NAMESIZE];
log_init();
log_setlevel(LOGLVL_DEBUG);
if (argc != 3) {
fatal("%s <device> <rate>\n", argv[0]);
exit(1);
}
queue_init(&pan_q);
queue_init(&tun_q);
init_reconstruct();
if (config_parse("ieee154_interface.conf", &device_config)) {
log_fatal_perror("parsing config file failed");
exit(1);
}
/* set up the serial interface device */
pthread_mutex_init(&pan_lock, NULL);
if (setup_serial(argv[1], argv[2], &device_config)) {
fatal("opening serial device failed!\n");
exit(1);
}
snprintf(print_buf, 128, "%02x:%02x:%02x:%02x:%02x:%02x:%02x:%02x",
device_config.eui64.data[0],device_config.eui64.data[1],device_config.eui64.data[2],
device_config.eui64.data[3],device_config.eui64.data[4],device_config.eui64.data[5],
device_config.eui64.data[6],device_config.eui64.data[7]);
info("device EUI-64: %s\n", print_buf);
pthread_create(&pan_writer, NULL, pan_write, NULL);
pthread_create(&reconstruct_thread, NULL, age_reconstruct, NULL);
/* initialize thes tun */
tun_fd = tun_open(dev);
if (tun_fd < 0) {
log_fatal_perror("opening tun device failed");
exit(1);
}
if (tun_setup(dev, device_config.eui64) < 0) {
exit(1);
}
sleep(1);
pthread_create(&tun_reader, NULL, tun_dev_read, NULL);
pthread_create(&pan_reader, NULL, pan_read, NULL);
pthread_join(pan_writer, NULL);
}
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/tos/lib/tossdr/tossim_sync.h | #ifndef TOSSIM_SYNC_H_INCLUDE
#define TOSSIM_SYNC_H_INCLUDE
#include <sim_tossdr.h>
class TossimSync {
public:
TossimSync();
~TossimSync();
void waitUntilNextEvent();
void runNextEventInTime();
bool waitUntilNextEvent_NoGil();
bool runNextEvent_NoGil();
sim_time_t simTime();
sim_time_t realTime();
sim_time_t syncTime();
void syncTo(sim_time_t time);
void syncToNow();
};
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/platforms/nxtmote/hardware.h | /**
* Adapted for nxtmote.
* @author <NAME>
*/
#ifndef __NXTMOTE_HARDWARE_H__
#define __NXTMOTE_HARDWARE_H__
#include "AT91SAM7S256.h"
#include "AT91SAM7S256_extra.h"
#include "lib_AT91SAM7S256.h"
#include "lib_extra_AT91SAM7S256.h"
#define OSC 48054850L
//PIT Timer
#define MS_1_TIME ((OSC/16)/1000)
typedef unsigned char UCHAR; //uint8_t
typedef unsigned short USHORT; //uint16_t
typedef unsigned char UBYTE; //uint8_t
typedef signed char SBYTE; //int8_t
typedef unsigned short int UWORD; //uint16_t
typedef signed short int SWORD; //int16_t
typedef unsigned long ULONG; //uint32_t
typedef signed long SLONG; //int32_t
typedef ULONG* PULONG;
typedef USHORT* PUSHORT;
typedef UCHAR* PUCHAR;
typedef char* PSZ;
/*
typedef signed char int8_t;
typedef unsigned char uint8_t;
typedef short int16_t;
typedef unsigned short uint16_t;
typedef int int32_t;
typedef unsigned int uint32_t;
typedef long long int64_t;
typedef unsigned long long uint64_t;
typedef int32_t intptr_t;
typedef uint32_t uintptr_t;
*/
extern void AT91F_Spurious_handler(void);
extern void AT91F_Default_IRQ_handler(void);
extern void AT91F_Default_FIQ_handler(void);
inline void __nesc_enable_interrupt() {
uint32_t statusReg = 0;
asm volatile (
"mrs %0,CPSR\n\t"
"bic %0,%1,#0xc0\n\t"
"msr CPSR_c, %1"
: "=r" (statusReg)
: "0" (statusReg)
);
return;
}
inline void __nesc_disable_interrupt() {
/*
uint32_t statusReg = 0;
asm volatile (
"mrs %0,CPSR\n\t"
"orr %0,%1,#0xc0\n\t"
"msr CPSR_c,%1\n\t"
: "=r" (statusReg)
: "0" (statusReg)
);
*/
return;
}
typedef uint32_t __nesc_atomic_t;
//TODO: enable
inline __nesc_atomic_t __nesc_atomic_start(void) @spontaneous() {
uint32_t result = 0;
/*
uint32_t temp = 0;
asm volatile (
"mrs %0,CPSR\n\t"
"orr %1,%2,%4\n\t"
"msr CPSR_cf,%3"
: "=r" (result) , "=r" (temp)
: "0" (result) , "1" (temp) , "i" (ARM_CPSR_INT_MASK)
);
*/
return result;
}
inline void __nesc_atomic_end(__nesc_atomic_t oldState) @spontaneous() {
//uint32_t statusReg = 0;
oldState &= ARM_CPSR_INT_MASK;
/*
asm volatile (
"mrs %0,CPSR\n\t"
"bic %0, %1, %2\n\t"
"orr %0, %1, %3\n\t"
"msr CPSR_c, %1"
: "=r" (statusReg)
: "0" (statusReg),"i" (ARM_CPSR_INT_MASK), "r" (oldState)
);
*/
return;
}
inline void __nesc_atomic_sleep() {
//__nesc_enable_interrupt();
}
// Add offset to channel id (first channel id is zero) to get timer peripheral id
#define TIMER_PID(chnl_id) chnl_id + AT91C_ID_TC0
// With MCK at 48054857 Hz and a timer incrementing at MCK/2
// 1 ms is approx. 24028 ticks
#define TICKSONEMSCLK2 (24028)
//#define TICKTOMSCLK2(ticks)
// priorities which are used in HplAt91InterruptM
const uint8_t TOSH_IRP_TABLE[] = {
0xFF, // AT91C_ID_FIQ ID 0, Advanced Interrupt Controller (FIQ)
AT91C_AIC_PRIOR_HIGHEST, // AT91C_ID_SYS ID 1, System Peripheral
0xFF, // AT91C_ID_PIOA ID 2, Parallel IO Controller
0xFF, // AT91C_ID_3_Reserved ID 3, Reserved
0xFF, // AT91C_ID_ADC ID 4, Analog-to-Digital Converter
0xFF, // AT91C_ID_SPI ID 5, Serial Peripheral Interface
0xFF, // AT91C_ID_US0 ID 6, USART 0
0xFF, // AT91C_ID_US1 ID 7, USART 1
0xFF, // AT91C_ID_SSC ID 8, Serial Synchronous Controller
AT91C_AIC_PRIOR_HIGHEST, // AT91C_ID_TWI ID 9, Two-Wire Interface
0xFF, // AT91C_ID_PWMC ID 10, PWM Controller
0xFF, // AT91C_ID_UDP ID 11, USB Device Port
0x04, // AT91C_ID_TC0 ID 12, Timer Counter 0
0xFF, // AT91C_ID_TC1 ID 13, Timer Counter 1
0xFF, // AT91C_ID_TC2 ID 14, Timer Counter 2
0xFF, // AT91C_ID_15_Reserved ID 15, Reserved
0xFF, // AT91C_ID_16_Reserved ID 16, Reserved
0xFF, // AT91C_ID_17_Reserved ID 17, Reserved
0xFF, // AT91C_ID_18_Reserved ID 18, Reserved
0xFF, // AT91C_ID_19_Reserved ID 19, Reserved
0xFF, // AT91C_ID_20_Reserved ID 20, Reserved
0xFF, // AT91C_ID_21_Reserved ID 21, Reserved
0xFF, // AT91C_ID_22_Reserved ID 22, Reserved
0xFF, // AT91C_ID_23_Reserved ID 23, Reserved
0xFF, // AT91C_ID_24_Reserved ID 24, Reserved
0xFF, // AT91C_ID_25_Reserved ID 25, Reserved
0xFF, // AT91C_ID_26_Reserved ID 26, Reserved
0xFF, // AT91C_ID_27_Reserved ID 27, Reserved
0xFF, // AT91C_ID_28_Reserved ID 28, Reserved
0xFF, // AT91C_ID_29_Reserved ID 29, Reserved
0xFF, // AT91C_ID_IRQ0 ID 30, Advanced Interrupt Controller (IRQ0)
0xFF, // AT91C_ID_IRQ1 ID 31, Advanced Interrupt Controller (IRQ1)
0xFF, // AT91C_ALL_INT ID 0xC0007FF7 ALL VALID INTERRUPTS
};
// priorities which are used in HplAt91InterruptM
// TRUE: AT91C_AIC_SRCTYPE_INT_HIGH_LEVEL
// FALSE: AT91C_AIC_SRCTYPE_INT_EDGE_TRIGGERED
const uint8_t TOSH_IRQLEVEL_TABLE[] = {
0xFF, // AT91C_ID_FIQ ID 0, Advanced Interrupt Controller (FIQ)
TRUE, // AT91C_ID_SYS ID 1, System Peripheral
0xFF, // AT91C_ID_PIOA ID 2, Parallel IO Controller
0xFF, // AT91C_ID_3_Reserved ID 3, Reserved
0xFF, // AT91C_ID_ADC ID 4, Analog-to-Digital Converter
0xFF, // AT91C_ID_SPI ID 5, Serial Peripheral Interface
0xFF, // AT91C_ID_US0 ID 6, USART 0
0xFF, // AT91C_ID_US1 ID 7, USART 1
0xFF, // AT91C_ID_SSC ID 8, Serial Synchronous Controller
FALSE, // AT91C_ID_TWI ID 9, Two-Wire Interface
0xFF, // AT91C_ID_PWMC ID 10, PWM Controller
0xFF, // AT91C_ID_UDP ID 11, USB Device Port
FALSE, // AT91C_ID_TC0 ID 12, Timer Counter 0
FALSE, // AT91C_ID_TC1 ID 13, Timer Counter 1
FALSE, // AT91C_ID_TC2 ID 14, Timer Counter 2
0xFF, // AT91C_ID_15_Reserved ID 15, Reserved
0xFF, // AT91C_ID_16_Reserved ID 16, Reserved
0xFF, // AT91C_ID_17_Reserved ID 17, Reserved
0xFF, // AT91C_ID_18_Reserved ID 18, Reserved
0xFF, // AT91C_ID_19_Reserved ID 19, Reserved
0xFF, // AT91C_ID_20_Reserved ID 20, Reserved
0xFF, // AT91C_ID_21_Reserved ID 21, Reserved
0xFF, // AT91C_ID_22_Reserved ID 22, Reserved
0xFF, // AT91C_ID_23_Reserved ID 23, Reserved
0xFF, // AT91C_ID_24_Reserved ID 24, Reserved
0xFF, // AT91C_ID_25_Reserved ID 25, Reserved
0xFF, // AT91C_ID_26_Reserved ID 26, Reserved
0xFF, // AT91C_ID_27_Reserved ID 27, Reserved
0xFF, // AT91C_ID_28_Reserved ID 28, Reserved
0xFF, // AT91C_ID_29_Reserved ID 29, Reserved
0xFF, // AT91C_ID_IRQ0 ID 30, Advanced Interrupt Controller (IRQ0)
0xFF, // AT91C_ID_IRQ1 ID 31, Advanced Interrupt Controller (IRQ1)
0xFF, // AT91C_ALL_INT ID 0xC0007FF7 ALL VALID INTERRUPTS
};
// Lookup table for some peripheral ids
AT91_REG PID_ADR_TABLE[] = {
0x00000000, // AT91C_ID_FIQ ID 0, Advanced Interrupt Controller (FIQ)
AT91C_BASE_PITC, // AT91C_ID_SYS ID 1, System Peripheral
0x00000000, // AT91C_ID_PIOA ID 2, Parallel IO Controller
0x00000000, // AT91C_ID_3_Reserved ID 3, Reserved
0x00000000, // AT91C_ID_ADC ID 4, Analog-to-Digital Converter
0x00000000, // AT91C_ID_SPI ID 5, Serial Peripheral Interface
0x00000000, // AT91C_ID_US0 ID 6, USART 0
0x00000000, // AT91C_ID_US1 ID 7, USART 1
0x00000000, // AT91C_ID_SSC ID 8, Serial Synchronous Controller
0x00000000, // AT91C_ID_TWI ID 9, Two-Wire Interface
0x00000000, // AT91C_ID_PWMC ID 10, PWM Controller
0x00000000, // AT91C_ID_UDP ID 11, USB Device Port
AT91C_BASE_TC0, // AT91C_ID_TC0 ID 12, Timer Counter 0
AT91C_BASE_TC1, // AT91C_ID_TC1 ID 13, Timer Counter 1
AT91C_BASE_TC2, // AT91C_ID_TC2 ID 14, Timer Counter 2
0x00000000, // AT91C_ID_15_Reserved ID 15, Reserved
0x00000000, // AT91C_ID_16_Reserved ID 16, Reserved
0x00000000, // AT91C_ID_17_Reserved ID 17, Reserved
0x00000000, // AT91C_ID_18_Reserved ID 18, Reserved
0x00000000, // AT91C_ID_19_Reserved ID 19, Reserved
0x00000000, // AT91C_ID_20_Reserved ID 20, Reserved
0x00000000, // AT91C_ID_21_Reserved ID 21, Reserved
0x00000000, // AT91C_ID_22_Reserved ID 22, Reserved
0x00000000, // AT91C_ID_23_Reserved ID 23, Reserved
0x00000000, // AT91C_ID_24_Reserved ID 24, Reserved
0x00000000, // AT91C_ID_25_Reserved ID 25, Reserved
0x00000000, // AT91C_ID_26_Reserved ID 26, Reserved
0x00000000, // AT91C_ID_27_Reserved ID 27, Reserved
0x00000000, // AT91C_ID_28_Reserved ID 28, Reserved
0x00000000, // AT91C_ID_29_Reserved ID 29, Reserved
0x00000000, // AT91C_ID_IRQ0 ID 30, Advanced Interrupt Controller (IRQ0)
0x00000000, // AT91C_ID_IRQ1 ID 31, Advanced Interrupt Controller (IRQ1)
0x00000000, // AT91C_ALL_INT ID 0xC0007FF7 ALL VALID INTERRUPTS
};
/* Bluetooth Start */
/* Error codes from then Loader */
enum
{
SUCCESS_ = 0x0000, // Name collision with SUCCESS from TinyError.h
INPROGRESS = 0x0001,
REQPIN = 0x0002,
NOMOREHANDLES = 0x8100,
NOSPACE = 0x8200,
NOMOREFILES = 0x8300,
EOFEXSPECTED = 0x8400,
ENDOFFILE = 0x8500,
NOTLINEARFILE = 0x8600,
FILENOTFOUND = 0x8700,
HANDLEALREADYCLOSED = 0x8800,
NOLINEARSPACE = 0x8900,
UNDEFINEDERROR = 0x8A00,
FILEISBUSY = 0x8B00,
NOWRITEBUFFERS = 0x8C00,
APPENDNOTPOSSIBLE = 0x8D00,
FILEISFULL = 0x8E00,
FILEEXISTS = 0x8F00,
MODULENOTFOUND = 0x9000,
OUTOFBOUNDERY = 0x9100,
ILLEGALFILENAME = 0x9200,
ILLEGALHANDLE = 0x9300,
BTBUSY = 0x9400,
BTCONNECTFAIL = 0x9500,
BTTIMEOUT = 0x9600,
FILETX_TIMEOUT = 0x9700,
FILETX_DSTEXISTS = 0x9800,
FILETX_SRCMISSING = 0x9900,
FILETX_STREAMERROR = 0x9A00,
FILETX_CLOSEERROR = 0x9B00,
BTWAIT = 0x9C00 // if cCommReq is busy
};
/* Loader */
enum
{
OPENREAD = 0x80,
OPENWRITE = 0x81,
READ = 0x82,
WRITE = 0x83,
CLOSE = 0x84,
DELETE = 0x85,
FINDFIRST = 0x86,
FINDNEXT = 0x87,
VERSIONS = 0x88,
OPENWRITELINEAR = 0x89,
OPENREADLINEAR = 0x8A,
OPENWRITEDATA = 0x8B,
OPENAPPENDDATA = 0x8C,
FINDFIRSTMODULE = 0x90,
FINDNEXTMODULE = 0x91,
CLOSEMODHANDLE = 0x92,
IOMAPREAD = 0x94,
IOMAPWRITE = 0x95,
BOOTCMD = 0x97, /* external command only */
SETBRICKNAME = 0x98,
BTGETADR = 0x9A,
DEVICEINFO = 0x9B,
DELETEUSERFLASH = 0xA0,
POLLCMDLEN = 0xA1,
POLLCMD = 0xA2,
RENAMEFILE = 0xA3,
BTFACTORYRESET = 0xA4
};
/* UI */
// Constants related to BlueToothState
enum
{
BT_STATE_VISIBLE = 0x01, // RW - BT visible
BT_STATE_CONNECTED = 0x02, // RW - BT connected to something
BT_STATE_OFF = 0x04, // RW - BT power off
BT_ERROR_ATTENTION = 0x08, // W - BT error attention
BT_CONNECT_REQUEST = 0x40, // RW - BT get connect accept in progress
BT_PIN_REQUEST = 0x80 // RW - BT get pin code
};
// Loader
//Mask out handle byte of Loader status word for error code checks
#define LOADER_ERR(StatusWord) ((StatusWord & 0xFF00))
//Byte value of error half of Loader status word
#define LOADER_ERR_BYTE(StatusWord) ((UBYTE)((StatusWord & 0xFF00) >> 8))
//Value of handle inside Loader status word
#define LOADER_HANDLE(StatusWord) ((UBYTE)(StatusWord))
//Pointer to lower byte of Loader status word
#define LOADER_HANDLE_P(StatusWord) ((UBYTE*)(&StatusWord))
// More loader
//Communications specific errors
#define ERR_COMM_CHAN_NOT_READY -32 //0xE0 Specified channel/connection not configured or busy
#define ERR_COMM_CHAN_INVALID -33 //0xDF Specified channel/connection is not valid
#define ERR_COMM_BUFFER_FULL -34 //0xDE No room in comm buffer
#define ERR_COMM_BUS_ERR -35 //0xDD Something went wrong on the communications bus
//Version numbers are two bytes, MAJOR.MINOR (big-endian)
//For example, version 1.5 would be 0x0105
//If these switch to little-endian, be sure to update
//definition and usages of VM_OLDEST_COMPATIBLE_VERSION, too!
#define FIRMWAREVERSION 0x0104 //1.04
#define PROTOCOLVERSION 0x017C //1.124
// RC
//Direct command protocol opcodes
//!!! These MUST be mutually exclusive with c_comm's protocol opcodes.
// Since all of c_comm's protocol opcodes are above 0x80, we're safe for now.
enum
{
RC_START_PROGRAM,
RC_STOP_PROGRAM,
RC_PLAY_SOUND_FILE,
RC_PLAY_TONE,
RC_SET_OUT_STATE,
RC_SET_IN_MODE,
RC_GET_OUT_STATE,
RC_GET_IN_VALS,
RC_RESET_IN_VAL,
RC_MESSAGE_WRITE,
RC_RESET_POSITION,
RC_GET_BATT_LVL,
RC_STOP_SOUND,
RC_KEEP_ALIVE,
RC_LS_GET_STATUS,
RC_LS_WRITE,
RC_LS_READ,
RC_GET_CURR_PROGRAM,
RC_GET_BUTTON_STATE,
RC_MESSAGE_READ,
NUM_RC_OPCODES
};
// IOCtrl
enum
{
POWERDOWN = 0x5A00,
BOOT = 0xA55A
};
// UI
// Constants related to Flags
enum
{
UI_UPDATE = 0x01, // W - Make changes take effect
UI_DISABLE_LEFT_RIGHT_ENTER = 0x02, // RW - Disable left, right and enter button
UI_DISABLE_EXIT = 0x04, // RW - Disable exit button
UI_REDRAW_STATUS = 0x08, // W - Redraw entire status line
UI_RESET_SLEEP_TIMER = 0x10, // W - Reset sleep timeout timer
UI_EXECUTE_LMS_FILE = 0x20, // W - Execute LMS file in "LMSfilename" (Try It)
UI_BUSY = 0x40, // R - UI busy running or datalogging (popup disabled)
UI_ENABLE_STATUS_UPDATE = 0x80 // W - Enable status line to be updated
};
// Dispplay
// Constants related to Flags
enum
{
DISPLAY_ON = 0x01, // W - Display on
DISPLAY_REFRESH = 0x02, // W - Enable refresh
DISPLAY_POPUP = 0x08, // W - Use popup display memory
DISPLAY_REFRESH_DISABLED = 0x40, // R - Refresh disabled
DISPLAY_BUSY = 0x80 // R - Refresh in progress
};
/* interface between comm and BC4 */
enum
{
MSG_BEGIN_INQUIRY,
MSG_CANCEL_INQUIRY,
MSG_CONNECT,
MSG_OPEN_PORT,
MSG_LOOKUP_NAME,
MSG_ADD_DEVICE,
MSG_REMOVE_DEVICE,
MSG_DUMP_LIST,
MSG_CLOSE_CONNECTION,
MSG_ACCEPT_CONNECTION,
MSG_PIN_CODE,
MSG_OPEN_STREAM,
MSG_START_HEART,
MSG_HEARTBEAT,
MSG_INQUIRY_RUNNING,
MSG_INQUIRY_RESULT,
MSG_INQUIRY_STOPPED,
MSG_LOOKUP_NAME_RESULT,
MSG_LOOKUP_NAME_FAILURE,
MSG_CONNECT_RESULT,
MSG_RESET_INDICATION,
MSG_REQUEST_PIN_CODE,
MSG_REQUEST_CONNECTION,
MSG_LIST_RESULT,
MSG_LIST_ITEM,
MSG_LIST_DUMP_STOPPED,
MSG_CLOSE_CONNECTION_RESULT,
MSG_PORT_OPEN_RESULT,
MSG_SET_DISCOVERABLE,
MSG_CLOSE_PORT,
MSG_CLOSE_PORT_RESULT,
MSG_PIN_CODE_ACK,
MSG_DISCOVERABLE_ACK,
MSG_SET_FRIENDLY_NAME,
MSG_SET_FRIENDLY_NAME_ACK,
MSG_GET_LINK_QUALITY,
MSG_LINK_QUALITY_RESULT,
MSG_SET_FACTORY_SETTINGS,
MSG_SET_FACTORY_SETTINGS_ACK,
MSG_GET_LOCAL_ADDR,
MSG_GET_LOCAL_ADDR_RESULT,
MSG_GET_FRIENDLY_NAME,
MSG_GET_DISCOVERABLE,
MSG_GET_PORT_OPEN,
MSG_GET_FRIENDLY_NAME_RESULT,
MSG_GET_DISCOVERABLE_RESULT,
MSG_GET_PORT_OPEN_RESULT,
MSG_GET_VERSION,
MSG_GET_VERSION_RESULT,
MSG_GET_BRICK_STATUSBYTE_RESULT,
MSG_SET_BRICK_STATUSBYTE_RESULT,
MSG_GET_BRICK_STATUSBYTE,
MSG_SET_BRICK_STATUSBYTE
};
#define SIZE_OF_BT_NAME 16
#define SIZE_OF_BRICK_NAME 8
#define SIZE_OF_CLASS_OF_DEVICE 4
#define SIZE_OF_BT_PINCODE 16
#define SIZE_OF_BDADDR 7
#define FILENAME_LENGTH 19 // zero termination not included
#define FILEHEADER_LENGTH 8 // all simple file headers
/* Bluetooth End */
//Clock selection constants
//enum {
// TC_CLKS = 0x7,
// TC_CLKS_MCK2 = 0x0,
// TC_CLKS_MCK8 = 0x1,
// TC_CLKS_MCK32 = 0x2,
// TC_CLKS_MCK128 = 0x3,
// TC_CLKS_MCK1024 = 0x4
//};
// GPIO pins
// See AT91SAM7S256 LEGO MINDSTORMS HW sheet 1
// and J7, J8, J9, and J6 on sheet 3
#define DIGIA0 (23) // Port 1 pin 5 (yellow)
#define DIGIA1 (18) // Port 1 pin 6 (blue)
#define DIGIB0 (28) // Port 2 pin 5
#define DIGIB1 (19) // Port 2 pin 6
#define DIGIC0 (29) // Port 3 pin 5
#define DIGIC1 (20) // Port 3 pin 6
#define DIGID0 (30) // Port 4 pin 5
#define DIGID1 (2) // Port 4 pin 6
// See HW appendix page 1. Pin5 on port 1 is PA18 that is DIGIA1
#define LEDVAL_ (1 << DIGIA0)
// Little function to toggle a pin
// Usage: write {toggle(0);}
// in your code to turn off the led
#define togglepin(toggle)\
{/* GPIO register addresses */\
/* Register use */\
*AT91C_PIOA_PER = LEDVAL_;\
*AT91C_PIOA_OER = LEDVAL_;\
if(toggle == 0)\
*AT91C_PIOA_CODR = LEDVAL_; /* port 1 pin 5 at 0.0 v (enable this line OR the next)*/\
else\
*AT91C_PIOA_SODR = LEDVAL_; /* port 1 pin 5 (blue) at 3.25-3.27 v (GND is on pin 2 (black)) */\
while(1); /* stop here */\
}
#include "nxt.h"
#endif //__NXTMOTE_HARDWARE_H__
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/platforms/nxtmote/nxt.h | <filename>nxtmote/tos/platforms/nxtmote/nxt.h
#ifndef __NXT_H__
#define __NXT_H__
//// m_shed.h ////
/* Defines related to I2c */
#define BYTES_TO_TX 8
#define BYTES_TO_RX 12
enum
{
NOS_OF_AVR_OUTPUTS = 4,
NOS_OF_AVR_BTNS = 4,
NOS_OF_AVR_INPUTS = 4
};
typedef struct
{
UWORD AdValue[NOS_OF_AVR_INPUTS];
UWORD Buttons;
UWORD Battery;
}IOFROMAVR;
typedef struct
{
UBYTE Power;
UBYTE PwmFreq;
SBYTE PwmValue[NOS_OF_AVR_OUTPUTS];
UBYTE OutputMode;
UBYTE InputPower;
}IOTOAVR;
//extern IOTOAVR IoToAvr;
//extern IOFROMAVR IoFromAvr;
IOTOAVR IoToAvr;
IOFROMAVR IoFromAvr;
#endif //__NXT_H__
|
tinyos-io/tinyos-3.x-contrib | tub/apps/PacketSniffer_802_15_4/wiresharkPlugins/cc2420/packet-cc2420.c | /* packet-cc2420.c
* Routines for cc2420 packet dissector.
* Copyright 2007, <NAME> <<EMAIL>>
*
* $Id: packet-cc2420.c,v 1.2 2008/05/13 00:10:30 vlahan Exp $
*
* Wireshark - Network traffic analyzer
* By <NAME> <<EMAIL>>
* Copyright 1998 <NAME>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <glib.h>
#include <epan/packet.h>
#include <epan/prefs.h>
#include "packet-cc2420.h"
/* Forward declaration we need below */
void proto_reg_handoff_cc2420(void);
/* Initialize the protocol and registered fields */
/* phy / cc2420 stuff */
static int proto_cc2420 = -1;
static int hf_cc2420_length = -1;
static int hf_cc2420_fcs = -1;
static int hf_cc2420_crc = -1;
static int hf_cc2420_lqi = -1;
static int hf_cc2420_rssi = -1;
/* Global preferences */
/* pref for AM type to registrate with */
static guint global_serial_type_cc2420 = T2_802154_SERIAL_TYPE;
static guint serial_type_cc2420 = T2_802154_SERIAL_TYPE;
static guint global_channel_cc2420 = CC2420_CHANNEL;
static guint channel_cc2420 = CC2420_CHANNEL;
/* Initialize the subtree pointers */
static gint ett_cc2420 = -1;
/* for sub dissectors */
static dissector_handle_t data_handle;
static heur_dissector_list_t heur_subdissector_list;
/* description for packet dispatch type */
static const true_false_string cc2420_crc_string = {
"16 bit crc correct",
"16 bit crc failed"
};
/* writes the channel given by the pref to a file, hoping that it's the
named pipe read by the app which takes care of switching. any questions!? ;) */
static void setChannel_cc2420() {
FILE* pipe = 0;
pipe = fopen( "./sniffControlPipeIn", "a" );
if (pipe) fprintf(pipe, "setChannel_cc2420 %i\n", channel_cc2420);
fclose(pipe);
}
/* Code to actually dissect general frame fields */
static void dissect_cc2420(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree)
{
/* Set up structures needed to add the protocol subtree and manage it */
proto_item* ti;
proto_item *fc;
proto_tree* tree_cc2420;
proto_tree* fc_tree;
unsigned int cc2420_length, available_length;
tvbuff_t* next_tvb;
tree_cc2420 = NULL;
cc2420_length = tvb_get_guint8(tvb, 0);
/* check if this cc2420 packet is really sane. If length is incorrect this might be another packet */
if (cc2420_length+1 != tvb_length(tvb)) {
call_dissector(data_handle, tvb, pinfo, tree);
return;
}
/* Make entries in Protocol column and Info column on summary display */
if (check_col(pinfo->cinfo, COL_PROTOCOL))
col_set_str(pinfo->cinfo, COL_PROTOCOL, "CC2420");
if (check_col(pinfo->cinfo, COL_INFO)) {
col_set_str(pinfo->cinfo, COL_INFO, "CC2420 Phy Frame");
}
if (tree) {
/* create display subtree for the protocol */
ti = proto_tree_add_item(tree, proto_cc2420, tvb, 0, -1, FALSE);
tree_cc2420 = proto_item_add_subtree(ti, ett_cc2420);
/* print cc2420 phy header */
proto_tree_add_item(tree_cc2420, hf_cc2420_length, tvb, 0, 1, FALSE);
/* tree for cc2420 phy footer / fcs */
fc = proto_tree_add_item(tree_cc2420, hf_cc2420_fcs, tvb, tvb_length(tvb)-2, 2, FALSE);
fc_tree = proto_item_add_subtree(fc, ett_cc2420);
proto_tree_add_item(fc_tree, hf_cc2420_rssi, tvb, tvb_length(tvb)-2, 2, FALSE);
proto_tree_add_item(fc_tree, hf_cc2420_crc, tvb, tvb_length(tvb)-2, 2, FALSE);
proto_tree_add_item(fc_tree, hf_cc2420_lqi, tvb, tvb_length(tvb)-2, 2, FALSE);
}
/* Calculate the available data in the packet,
set this to -1 to use all the data in the tv_buffer (FCS field is passed to next dissector too)*/
available_length = tvb_length(tvb) - CC2420_HEADER_LEN + 2;
/* Create the tvbuffer for the next dissector, this also passes the last two bytes to subdissector */
next_tvb = tvb_new_subset(tvb, CC2420_HEADER_LENGTH_OFFSET, MIN(cc2420_length, available_length), cc2420_length);
/* try "heuristics */
if (dissector_try_heuristic(heur_subdissector_list, next_tvb, pinfo, tree)) {
return;
}
/* call the next dissector */
call_dissector(data_handle, next_tvb, pinfo, tree);
return;
}
/* Register the protocol with Wireshark */
void proto_register_cc2420(void)
{
module_t *module_cc2420;
/* 802.15.4 Header */
static hf_register_info hf[] = {
/* cc2420 specific phy header */
{ &hf_cc2420_length, { "Length", "cc2420.length", FT_UINT8, BASE_DEC, NULL, 0x0, "", HFILL } },
/* cc2420 specific FCS */
{ &hf_cc2420_fcs, { "FCS", "cc2420.fcs", FT_NONE, FT_NONE, NULL, 0x0, "", HFILL } },
{ &hf_cc2420_crc, { "Crc", "cc2420.crc", FT_BOOLEAN, 16, TFS(&cc2420_crc_string), 0x80, "", HFILL } },
/* cc2420 specific FCS fields containing rssi & lqi & crc_pass*/
{ &hf_cc2420_lqi, { "Lqi", "cc2420.lqi", FT_UINT16, BASE_HEX, NULL, 0x7f, "", HFILL } },
{ &hf_cc2420_rssi, { "Rssi", "cc2420.rssi", FT_UINT16, BASE_HEX, NULL, 0xff00, "", HFILL } }
};
/* Setup protocol subtree array */
static gint *ett[] = {
&ett_cc2420
};
/* Register the protocol name and description */
proto_cc2420 = proto_register_protocol("CC2420 Frame Format", "CC2420", "cc2420");
/* Required function calls to register the header fields and subtrees used */
proto_register_field_array(proto_cc2420, hf, array_length(hf));
proto_register_subtree_array(ett, array_length(ett));
/* Register preferences module (See Section 2.6 for more on preferences) */
module_cc2420 = prefs_register_protocol(proto_cc2420, proto_reg_handoff_cc2420);
/* subdissector code */
register_heur_dissector_list("cc2420", &heur_subdissector_list);
/* Register prefs */
prefs_register_uint_preference(module_cc2420, "am_type",
"Serial type ",
"The type of Serial T2 messgaes which "
"contain CC2420 "
"packets as payload",
10, &global_serial_type_cc2420);
prefs_register_uint_preference(module_cc2420, "channel",
"Standard Channel ",
"The channel on which "
"the CC2420 radio"
"receives",
10, &global_channel_cc2420);
}
/* If this dissector uses sub-dissector registration add a registration routine.
This exact format is required because a script is used to find these routines
and create the code that calls these routines.
This function is also called by preferences whenever "Apply" is pressed
(see prefs_register_protocol above) so it should accommodate being called
more than once.
*/
void proto_reg_handoff_cc2420(void)
{
static dissector_handle_t cc2420_handle;
static gboolean inited = FALSE;
if (!inited) {
cc2420_handle = create_dissector_handle(dissect_cc2420, proto_cc2420);
dissector_add("t2sf.type", serial_type_cc2420, cc2420_handle);
inited = TRUE;
} else {
dissector_delete("t2sf.type", serial_type_cc2420, cc2420_handle);
}
setChannel_cc2420();
dissector_add("t2sf.type", global_serial_type_cc2420, cc2420_handle);
data_handle = find_dissector("data");
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/simulator.h | #ifndef SIMULATOR_H
#define SIMULATOR_H
#include <string>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <limits.h>
#include <float.h>
#include <iostream>
#include <fstream>
#include <stdlib.h>
using namespace std;
typedef struct
{
int type;
int64_t time;
int64_t energy;
int source;
string request_types;
} event_t;
#define SIMULATOR
#define MYLONG_MAX 9223372036854775807LL
//#define MYLONG_MAX 0x7FFFFFFF
#define EVALUATE_ENERGY_POLICY 0
#define UPDATE_BATTERY 1
#define SERVICE_REQUEST 2
#define SERVICE_TIMER_NODE 3
#include <vector>
#include "evaluator.h"
#include "nodes.h"
#include <stdint.h>
//typedef null NULL;
void enter_into_log(string log_entry);
void run_request (int64_t request_time, int node_id, string request_types);
void update_power_level (event_t*);
void increase_battery(int64_t energy);
typedef struct
{
string energy_profile;
string::size_type current_index;
string::size_type last_index;
string get_next_line()
{
string ret;
current_index = energy_profile.find('\n', last_index);
if(current_index != string::npos)
{
ret = energy_profile.substr(last_index, current_index-last_index);
last_index = current_index+1;
}
return ret;
}
} energy_in_t;
typedef struct
{
string energy_profile;
string::size_type current_index;
string::size_type last_index;
string get_next_line()
{
string ret;
current_index = energy_profile.find('\n', last_index);
if(current_index != string::npos)
{
ret = energy_profile.substr(last_index, current_index-last_index);
last_index = current_index+1;
}
return ret;
}
} requests_in_t;
typedef struct
{
string cost_profile;
string::size_type current_index;
string::size_type last_index;
string get_next_line()
{
string ret;
current_index = cost_profile.find('\n', last_index);
if(current_index != string::npos)
{
ret = cost_profile.substr(last_index, current_index-last_index);
last_index = current_index+1;
}
return ret;
}
} pathcost_in_t;
pathcost_in_t* read_pathcost_in(char *file_name);
extern int64_t current_time;
extern int64_t current_battery_fullness;
extern int current_power_state;
extern double current_state_grade;
extern int64_t battery_capacity;
extern int64_t loss_per_unit_time;
extern int64_t energy_reeval_interval;
extern vector < string > *str_vector;
vector < event_t > *event_vector;
extern requests_in_t *requests_in;
extern energy_in_t *energy_in;
pathcost_in_t *pathcost_in;
extern FILE *fp;
vector < int64_t > path_costs[NUMPATHS] ;
void log(string str)
{
enter_into_log(str);
}
void load_path_costs()
{
//cost format
//pathid:val,val,val,val,val\n
pathcost_in_t *costs = read_pathcost_in("costs");
string newline = costs->get_next_line();
string tmp;
int pathnum;
int64_t cost;
while (!newline.empty())
{
string::size_type loc = newline.find( ":", 0 );
if (loc != string::npos )
{
tmp = newline.substr(0, loc);
pathnum = atoi((char *) tmp.c_str());
newline.erase(0,loc+1);
//printf("pathnum=%i\n",pathnum);
} else {
printf("Bad cost format\n");
exit(1);
}
do {
loc = newline.find(",",0);
if (loc != string::npos)
{
tmp = newline.substr(0,loc);
cost = atoll((char*) tmp.c_str());
newline.erase(0,loc+1);
//insert cost
path_costs[pathnum].push_back(cost);
//printf("path_cost[%i] <- %lld\n",pathnum,cost);
}
} while (loc != string::npos);
newline = costs->get_next_line();
}
printf("Costs loaded\n");
}
void decrement_power_level (int path_sum ){
int num_samples = path_costs[path_sum].size();
if (num_samples == 0) return;
int r = (rand() % num_samples);
increase_battery(0-path_costs[path_sum].at(r));
if (current_battery_fullness > 0)
{
eval_path_done(path_sum, current_power_state, path_costs[path_sum].at(r), current_time);
//printf("decr_power(%i,%lld)\n",path_sum, path_costs[path_sum].at(r));
char logmsg[256];
sprintf(logmsg,"P:%lld:%d",current_time,path_sum);
log(logmsg);
}
}
pathcost_in_t* read_pathcost_in(char *file_name)
{
int fd = open(file_name, O_RDONLY);
struct stat buf;
int err = fstat(fd, &buf);
int file_size = buf.st_size;
printf("%s File Size: %d\n", file_name, file_size);
pathcost_in_t *ret = new pathcost_in_t;
if (file_size > 0)
{
char *read_it =(char *) mmap (0, file_size, PROT_READ, MAP_SHARED, fd, 0);
std::string str(read_it);
ret->cost_profile = str;
munmap(read_it, file_size);
} else {
ret->cost_profile = "";
}
ret->current_index = 0;
ret->last_index = 0;
std::string::size_type curr_index = 0;
std::string::size_type loc = 0;
//printf("cost profile = %s\n",ret->cost_profile.c_str());
close(fd);
return ret;
}
requests_in_t* read_requests_in(char *file_name)
{
int fd = open(file_name, O_RDONLY);
struct stat buf;
int err = fstat(fd, &buf);
int file_size = buf.st_size;
printf("%s File Size: %d\n", file_name, file_size);
requests_in_t *ret = new requests_in_t;
if (file_size > 0)
{
char *read_it =(char *) mmap (0, file_size, PROT_READ, MAP_SHARED, fd, 0);
std::string str(read_it);
ret->energy_profile = str;
munmap(read_it, file_size);
} else {
ret->energy_profile = "";
}
ret->current_index = 0;
ret->last_index = 0;
std::string::size_type curr_index = 0;
std::string::size_type loc = 0;
close(fd);
return ret;
}
int get_tl_type(string &str)
{
int ret = -1;
string tmp;
string::size_type loc = str.find( ":", 0 );
if (loc != string::npos )
{
tmp = str.substr(0, loc);
ret = atoi((char *) tmp.c_str());
str.erase(0,loc+1);
}
return ret;
}
int64_t getTimerVal(int src, int state, double grade)
{
int64_t max = timerVals[src][state][0];
int64_t min = timerVals[src][state][1];
double dmin = min;
double dmax = max;
double intval = (dmax + ((dmin-dmax)*(1-grade)));
int64_t ret = (int64_t)intval;
return ret;
}
int64_t get_tl_time(string &str)
{
int64_t ret = MYLONG_MAX;
string tmp;
string::size_type loc = str.find( ":", 0 );
if (loc != string::npos )
{
tmp = str.substr(0, loc);
ret = atoll((char *) tmp.c_str());
}
return ret;
}
int64_t get_time(string str)
{
int64_t ret = MYLONG_MAX;
string::size_type loc = str.find( ":", 0 );
if (loc != string::npos )
{
str = str.substr(0, loc);
ret = atoll((char *) str.c_str());
}
return ret;
}
int64_t get_tl_time_erase(string &str)
{
int64_t ret = MYLONG_MAX;
string tmp;
string::size_type loc = str.find( ":", 0 );
if (loc != string::npos )
{
tmp = str.substr(0, loc);
ret = atoll((char *) tmp.c_str());
str.erase(0,loc+1);
}
return ret;
}
energy_in_t* read_energy_in(char *file_name)
{
int fd = open(file_name, O_RDONLY);
struct stat buf;
int err = fstat(fd, &buf);
int file_size = buf.st_size;
printf("%s File Size: %d\n", file_name, file_size);
char *read_it =(char *) mmap (0, file_size, PROT_READ, MAP_SHARED, fd, 0);
std::string str(read_it);
energy_in_t *ret = new energy_in_t;
ret->energy_profile = str;
ret->current_index = 0;
ret->last_index = 0;
std::string::size_type curr_index = 0;
std::string::size_type loc = 0;
munmap(read_it, file_size);
close(fd);
return ret;
}
/*
TODO: Eventually, I should be instering a "re-evaluate energy policy" function call somewhere around here...
*/
//vector<string>* make_timeline(energy_in_t *e_in, requests_in_t *r_in, char *output_file)
vector<string>* make_timeline(energy_in_t *e_in, requests_in_t *r_in)
{
printf("making timeline...%d\n", sizeof(int64_t));
vector<string> *ret = new vector<string>;
//ret->push_back(string("alex"));
string current_energy = e_in->get_next_line();
string current_request = r_in->get_next_line();
int64_t current_energy_time = get_time(current_energy);
int64_t current_request_time = get_time(current_request);
do
{
//printf("loop...%lld, %lld\n", current_request_time, current_energy_time);
// if the next element is an "update energy element"
if (current_energy_time < current_request_time)
{
// print to file current_energy
char buf[64];
sprintf(buf, "%d:", UPDATE_BATTERY);
string str = string(buf) + current_energy;
ret->push_back(str);
//log(str);
// get the next energy input reading
//fprintf(fp, "%s\n", current_energy.c_str());
//fprintf(fp, "%s\n", str.c_str());
if (!current_energy.empty())
{
current_energy = e_in->get_next_line();
//printf("\"%s\" before\n",current_energy.c_str());
current_energy_time = get_time(current_energy);
//printf("\"%s\" -> %lld\n",current_energy.c_str(), current_energy_time);
}
else
{
current_energy_time = MYLONG_MAX;
}
}
else if (current_request_time != MYLONG_MAX)
{
//printf("now, here\n");
// print to file current_request
char buf[64];
sprintf(buf, "%d:", SERVICE_REQUEST);
string str = string(buf) + current_request;
ret->push_back(str);
//log(str);
// get the next request
if (!current_request.empty())
{
current_request = r_in->get_next_line();
current_request_time = get_time(current_request);
}
else
{
current_request_time = MYLONG_MAX;
}
}
//printf("loop...%s, %s\n", current_request.c_str(), current_energy.c_str());
}while( !current_energy.empty() || !current_request.empty());
printf("end loop...\n");
return ret;
}
void decrement_idle (int64_t timestamp)
{
static int64_t diff = 0;
int64_t delta;
diff += (timestamp - current_time);
current_time = timestamp;
if (diff < (15 * 60 * 1000)) //accumulate over 15 minutes
{
return;
}
delta = ((diff * loss_per_unit_time) / 60000) * (-1);
increase_battery(delta);
diff = 0;
}
void increase_battery(int64_t energy){
char buf[512];
int64_t newfullness = current_battery_fullness + energy;
int64_t waste=0;
eval_increase_battery(energy);
if (newfullness > battery_capacity)
{
waste += newfullness - battery_capacity;
newfullness = battery_capacity;
}
if (newfullness < 0){
newfullness= 0;
}
if (newfullness != current_battery_fullness || waste != 0)
{
sprintf(buf,"%lld:%lld:%lld",current_time, newfullness,waste);
log(buf);
}
current_battery_fullness = newfullness;
}
void update_power_level(event_t* event){
int64_t energy_source_power = event->energy;
increase_battery(energy_source_power);
eval_more_energy(energy_source_power, event->time);
}
void insert_event(vector < event_t* > * time_line, event_t *event, int index)
{
vector< event_t* >::iterator it = time_line->begin() + index;
//printf("event_str=%s\n",event.c_str());
event_t* tmp = *it;
int ctype = tmp->type;
int64_t ctime = tmp->time;
int etype = event->type;
int64_t event_time = event->time;
//printf("etype = %d, etime = %lld\n",etype, event_time);
//printf("ctype = %d, ctime = %lld\n",ctype, ctime);
while (it != time_line->end() && ctime <= event_time)
{
it++;
if (it == time_line->end()) break;
tmp = *it;
ctype = tmp->type;
ctime = tmp->time;
//printf("e = (%i,%f)...c=(%i,%f)\n", etype, event_time, ctype, ctime);
}
//insert here
time_line->insert(it, event);
}
void start_eval(vector < event_t* > *time_line)
{
// char buf[512];
// sprintf(buf, "%d:%d:0",
// EVALUATE_ENERGY_POLICY, 0);
event_t *neweval = new event_t;
neweval->type = EVALUATE_ENERGY_POLICY;
neweval->time = 0;
insert_event(time_line, neweval, 0);
}
void insert_eval(vector < event_t* > *time_line, int64_t time, int64_t index)
{
//char buf[512];
int64_t newtime = time + energy_reeval_interval;
//sprintf(buf, "%d:%lld:0:",
// EVALUATE_ENERGY_POLICY, newtime);
event_t *neweval = new event_t;
neweval->type = EVALUATE_ENERGY_POLICY;
neweval->time = newtime;
insert_event(time_line, neweval, index);
}
void start_timers(vector < event_t* > *time_line)
{
int64_t timertime = 0;
int64_t interval;
// char newtimerstr[512];
int src_id;
int node_id;
int i;
for (i=0; i < NUMSOURCES; i++)
{
if (srcNodes[i][0])
{
//it's timed
//get interval
printf("gTV(%i,%i,%f)\n",i,current_power_state, current_state_grade);
printf("i=%d\n",i);
interval = getTimerVal(i, current_power_state, current_state_grade);
printf("i=%d\n",i);
printf("gTV done(%lld)\n",interval);
//sprintf(newtimerstr, "%d:%lld:%d:",
// SERVICE_TIMER_NODE, timertime+interval, i);
event_t *newtimer = new event_t;
newtimer->type = SERVICE_TIMER_NODE;
newtimer->time = timertime+interval;
newtimer->source = i;
printf("i=%d\n",i);
//printf("insert(%s)\n",newtimerstr);
insert_event(time_line, newtimer, 0);
printf("i=%d\n",i);
printf("insert_event done\n");
printf("i=%d\n",i);
}
}
}
void service_timer(event_t* event,
vector < event_t* > * time_line,
int index)
{
//string timerstr = str;
int64_t timertime = event->time;
int64_t interval;
//char newtimerstr[512];
//char runstr[512];
event_t* newtimer = new event_t;
int src_id = event->source;
int node_id = srcNodes[src_id][1];
//sprintf(runstr, "%lld:%i:",
// timertime, node_id);
run_request(timertime, node_id, event->request_types);
//need to insert next timer
//get interval
interval = getTimerVal(src_id, current_power_state, current_state_grade);
//sprintf(newtimerstr, "%i:%lld:%i:",
// SERVICE_TIMER_NODE, timertime+interval, src_id);
newtimer->time = timertime+interval;
newtimer->type = SERVICE_TIMER_NODE;
newtimer->source = src_id;
insert_event(time_line, newtimer, index);
//printf("service_timer %s,%i\n",str.c_str(), index);
}
vector<event_t*> *convert_timeline(vector <string> *time_line)
{
int i;
vector < event_t *> *ret = new vector < event_t * >;
for (i=0; i < time_line->size(); i++)
{
string str = time_line->at(i);
//convert to event_t
event_t *evt = new event_t;
evt->type = get_tl_type(str);
evt->time = get_tl_time(str);
string::size_type loc, loc2;
switch (evt->type)
{
case UPDATE_BATTERY:
loc = str.find(":", 0);
if(loc != string::npos)
{
//string power_time_string = str.substr(0, loc);
string energy_source_power_str = str.substr(loc+1);
evt->energy = atoll(energy_source_power_str.c_str());
} else {
printf("ERROR PARSING UPDATE BATTERY!");
}
break;
case SERVICE_REQUEST:
loc = str.find(":", 0);
loc2 = str.find(":", loc+1);
if(loc != string::npos && loc2 != string::npos)
{
//string time_string = str.substr(0, loc);
string src_str = str.substr(loc+1,loc2);
string type_str = str.substr(loc2);
evt->source = atoi(src_str.c_str());
evt->request_types = type_str;
} else {
printf("ERROR PARSING SERVICE REQUEST!");
}
break;
case SERVICE_TIMER_NODE:
loc = str.find(":", 0);
if(loc != string::npos && loc2 != string::npos)
{
//string time_string = str.substr(0, loc);
string src_str = str.substr(loc+1);
evt->source = atoi(src_str.c_str());
} else {
printf("ERROR PARSING TIMER REQUEST!");
}
break;
case EVALUATE_ENERGY_POLICY:
break;
}//switch
ret->push_back(evt);
}
return ret;
}
void parse_timeline (vector < string > *time_line, int64_t max_time)
{
int size = time_line->size ();
int i = 0;
vector < event_t* > *newtime_line;
//convert from strings to event_t
printf("converting timeline...\n", max_time);
newtime_line = convert_timeline(time_line);
printf("starting sim...(%lld ms)\n", max_time);
init_evaluator();
printf("init_e\n");
//insert initial timers
start_timers(newtime_line);
start_eval(newtime_line);
/*for (i=0; i < time_line->size(); i++)
{
log(time_line->at(i));
}
exit(1);*/
while (i < newtime_line->size() && current_time < max_time)
{
event_t* current_event = newtime_line->at (i);
//log(current_string);
// now we get the type of the event
int event_type = current_event->type;
int64_t event_time = current_event->time;
decrement_idle(event_time);
switch (event_type)
{
case UPDATE_BATTERY:
update_power_level (current_event);
break;
case SERVICE_REQUEST:
run_request (current_event->time, current_event->source, current_event->request_types);
break;
case SERVICE_TIMER_NODE:
service_timer(current_event, newtime_line, i);
break;
case EVALUATE_ENERGY_POLICY:
{
printf("eval policy\n");
energy_evaluation_struct_t *eval_result =
reevaluate_energy_level (newtime_line, i,
current_battery_fullness);
current_power_state = eval_result->energy_state;
current_state_grade = eval_result->state_grade;
increase_battery(eval_result->cost_of_reevaluation);
insert_eval(newtime_line, event_time, i);
char logmsg[256];
sprintf(logmsg,"E:%lld:%d:%lf",event_time,
current_power_state, current_state_grade);
log(logmsg);
fflush(stdout);
usleep(10000);
delete eval_result;
break;
}
default:
printf ("Invalid option selected\n");
break;
}
i++;
}
printf ("Simulation Over \n");
printf ("battery left: %lld\n", current_battery_fullness);
printf ("Percentage battery left: %lld\n",
((current_battery_fullness * 100) / battery_capacity));
}
#endif
|
tinyos-io/tinyos-3.x-contrib | cedt/tos/chips/atm128/sim/atm128const.h | /* $Id: atm128const.h,v 1.3 2007/09/05 06:19:45 venkatesh2012 Exp $
* Copyright (c) 2005 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/*
* const_[u]int[8/16/32]_t types are used to declare single and array
* constants that should live in ROM/FLASH. These constants must be read
* via the corresponding read_[u]int[8/16/32]_t functions.
*
* This file defines the ATmega128 version of these types and functions.
* @author <NAME>
*/
/*
* "Copyright (c) 2007 CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc BE LIABLE TO
* ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc SPECIFICALLY DISCLAIMS
* ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND CENTRE FOR ELECTRONICS
* AND DESIGN TECHNOLOGY,IISc HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*/
/*
* Added the pgm_read functionality
*
* @author <NAME>
* @author <NAME>
*/
#ifndef ATMEGA128CONST_H
#define ATMEGA128CONST_H
typedef uint8_t const_uint8_t PROGMEM;
typedef uint16_t const_uint16_t PROGMEM;
typedef uint32_t const_uint32_t PROGMEM;
typedef int8_t const_int8_t PROGMEM;
typedef int16_t const_int16_t PROGMEM;
typedef int32_t const_int32_t PROGMEM;
#define read_uint8_t(x) pgm_read_byte(x)
#define read_uint16_t(x) pgm_read_word(x)
#define read_uint32_t(x) pgm_read_dword(x)
#define read_int8_t(x) ((int8_t)pgm_read_byte(x))
#define read_int16_t(x) ((int16_t)pgm_read_word(x))
#define read_int32_t(x) ((int32_t)pgm_read_dword(x))
#define pgm_read_byte(x) (*(x))
#define pgm_read_word(x) (*(x))
#define pgm_read_dword(x) (*(x))
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargate/sfaccess/sfsend.c | <filename>eon/eon/src/runtime/stargate/sfaccess/sfsend.c
#include "telossource.h"
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
//#define LOCALDBG
enum
{
AM_STATUS_MSG = 10,
AM_SLEEP_MSG = 11,
};
#define STATUSMSGSIZE 3
int asfpid = 0;
int startasf()
{
int err;
printf("startasf...\n");
pid_t pID = fork();
printf("forked(%i)\n",pID);
if (pID == 0)
{
//child process
#ifdef LOCALDBG
err = execlp("./sf","sf","9000","/dev/ttyUSB0","115200","telos",(char*) 0);
#else
err = execlp("/root/asf","asf","9000","/dev/usb/tts/0","115200","telos",(char*) 0);
#endif
if (err)
{
printf("execlp failed!\n");
exit(1);
}
printf("Hrmmm....should not have reached this point.\n");
}
else if (pID < 0)
{
printf("fork failed\n");
return pID;
}
else
{
return pID;
}
return pID;
}
int stopasf()
{
int err;
err = kill(asfpid, SIGTERM);
if (err)
{
printf("error: could not send SIGTERM to proc %i\n",asfpid);
}
err = waitpid(asfpid, NULL, 0);
printf("asf stopped...\n");
if (err <= 0)
{
return err;
}
return 0;
}
int closedown()
{
int err;
err = stopasf();
if (err)
{
printf("stopasf failed (err=%i)\n",err);
return err;
}
err = intercomm_stop();
if (err)
{
printf("intercomm_stop failed (err=%i)\n",err);
return err;
}
printf("closedown done\n");
//usleep(100000);
return err;
}
int firststartup(const char* host, short port)
{
int err=0;
asfpid = startasf();
if (asfpid <= 0)
{
printf("Error starting asf (err=%i)\n",err);
return asfpid;
}
printf("asf started (err=%i)\n",err);
usleep(700000);
return err;
}
int startup(const char* host, short port)
{
int err=0;
asfpid = startasf();
if (asfpid <= 0)
{
printf("Error starting asf (err=%i)\n",err);
return asfpid;
}
printf("asf started (err=%i)\n",err);
usleep(300000);
err = intercomm_start(port);
if (err)
{
printf("Error in startup (err=%i)\n",err);
return err;
}
printf("Startup succeeded...\n");
return err;
}
int sendStatusPacket(int fd, bool sleepy, uint16_t load)
{
telospacket packet;
uint8_t data[STATUSMSGSIZE];
int err;
packet.length = STATUSMSGSIZE;
packet.addr = TOS_BCAST_ADDR;
packet.type = AM_STATUS_MSG;
packet.data = data;
data[0] = sleepy;
hton_uint16(data+1, load);
err = write_telos_packet(fd, &packet);
if (err)
{
printf("AAAH! Could not send status packet.\n");
return -1;
}
return 0;
}
int main(int argc, char **argv)
{
int fd;
int err;
int sleepy = FALSE;
telospacket *packet;
init(argc,argv);
printf("Starting\n");
sleep(1);
#ifndef LOCALDBG
system("modprobe usbserial");
system("modprobe ftdi_sio");
sleep(1);
firststartup("localhost",9000);
sleep(1);
fd = open_telos_source("localhost", 9000);
if (fd <= 0)
{
printf("o_t_s failed! (fd=%i)\n",fd);
return 1;
}
sendStatusPacket(fd, 1, 0);
sleep(1);
//usleep(100000);
//sendStatusPacket(fd, 1, 0);
//usleep(100000);
close(fd);
usleep(500000);
//sleep(1);
printf("...going to sleep.\n");
err = stopasf();
if (err)
{
printf("stopasf failed (err=%i)\n",err);
return err;
}
usleep(10000);
system("modprobe -r ftdi_sio");
system("modprobe -r usbserial");
system("/sbin/sys_suspend");
#endif
while(TRUE)
{
//wait for device to wake
#ifndef LOCALDBG
//sleep(2);
system("modprobe usbserial");
system("modprobe ftdi_sio");
#endif
sleep(1);
err = startup("localhost",9000);
if (err)
{
printf("Startup failed...\n");
return 1;
}
fd = open_telos_source("localhost", 9000);
if (fd <= 0)
{
printf("o_t_s failed! (fd=%i)\n",fd);
return 1;
}
printf("startup succeeded...\n");
//wait for sleep msg and send status
while (!sleepy)
{
packet = read_telos_packet(fd);
if (packet && packet->type == AM_SLEEP_MSG)
{
sleepy = TRUE;
printf("Sleep Msg!");
sleep(1);
} else {
printf(".");
}
free_telos_packet(&packet);
packet = NULL;
}
sleepy = FALSE;
sleep(1);
//send I'm sleeping packet
sendStatusPacket(fd, 1, 0);
usleep(10000);
close(fd);
err = closedown();
if (err)
{
printf("closedown failed...\n");
} else {
printf("Going to sleep\n");
#ifdef LOCALDBG
sleep(5);
#else
system("modprobe -r ftdi_sio");
system("modprobe -r usbserial");
system("/sbin/sys_suspend");
#endif
}
sleep(1);
}
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | sensorscheme/tos/lib/SensorScheme/SensorSchemeMsg.h | #ifndef SENSORSCHEMEMSG_H
#define SENSORSCHEMEMSG_H
#include "message.h"
typedef nx_struct sensorscheme_msg {
nx_uint8_t sequence;
nx_uint8_t data[TOSH_DATA_LENGTH-sizeof(nx_uint8_t)];
} sensorscheme_msg_t;
enum {
AM_SENSORSCHEME_MSG = 43,
ACK_SENSORSCHEME_MSG = 44,
};
#endif // SENSORSCHEMEMSG_H
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/stargatehelper/adcs.h | <filename>eon/eon/src/runtime/stargatehelper/adcs.h
enum
{
TIMERRES = (uint32_t)500000
};
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/passthru/passthru_test_decomp.c | <reponame>tinyos-io/tinyos-3.x-contrib
#include <inttypes.h>
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include "../buffer.h"
uint8_t membuffer[MEMBUFSIZE];
uint8_t *data;
uint8_t read_count;
uint16_t buffer;
static uint8_t read_bits(uint8_t len)
{
uint8_t res;
// Fill the buffer
while (read_count < len) {
buffer <<= 8;
buffer |= *data++;
read_count += 8;
}
res = (buffer >> (read_count - len)) & ((1 << len) - 1);
read_count -= len;
buffer &= (1 << read_count) - 1;
return res;
}
uint16_t bits_left()
{
uint16_t res = MEMBUFSIZE - (data - membuffer); // Amount of unread data;
/*
printf("Length: %d, data: %p, data_start: %p, diff: %d\n",
length, data, data_start, data - data_start);
*/
res *= 8;
res += read_count; // Bits read, but not outputted yet.
// printf("Bits left: %d\n", res);
return res;
}
uint16_t get_sample()
{
uint16_t tmp = 0;
tmp |= read_bits(8);
tmp |= (uint16_t)read_bits(8) << 8;
return tmp;
}
int decompress_sample(int16_t *digi_x, int16_t *digi_y,
int16_t *digi_z, uint16_t *analog_x,
uint16_t *analog_y)
{
static int first = 1;
if (first || bits_left() < 3 * 12) {
first = 0;
if (fread(membuffer, MEMBUFSIZE, 1, stdin) != 1) {
fprintf(stderr, "Error reading from stdin: %s\n",
strerror(errno));
return 1;
}
read_count = 0;
buffer = 0;
data = membuffer;
}
*digi_x = get_sample();
*digi_y = get_sample();
*digi_z = get_sample();
return 0;
}
|
tinyos-io/tinyos-3.x-contrib | ethz/tinynode184/tos/platforms/tinynode184/tinynodeSEB/tinynodeSEB.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef TINYNODESEB_H
#define TINYNODESEB_H
#define UQ_TEMPDEVICE "TempDeviceP.Resource"
#define UQ_TEMPDEVICE_STREAM "TempDeviceStreamP.Resource"
#define UQ_PHOTODEVICE "PhotoDeviceP.Resource"
#define UQ_PHOTODEVICE_STREAM "PhotoDeviceStreamP.Resource"
#define UQ_BATTDEVICE "ExBattDeviceP.Resource"
#define UQ_BATTDEVICE_STREAM "ExBattDeviceStreamP.Resource"
#include <Msp430Adc12.h>
const msp430adc12_channel_config_t photoAdc = {
INPUT_CHANNEL_A4,
REFERENCE_VREFplus_AVss,
REFVOLT_LEVEL_1_5,
SHT_SOURCE_ACLK,
SHT_CLOCK_DIV_1,
SAMPLE_HOLD_4_CYCLES,
SAMPCON_SOURCE_SMCLK,
SAMPCON_CLOCK_DIV_1
};
const msp430adc12_channel_config_t exBattAdc = {
EXTERNAL_REF_VOLTAGE_CHANNEL,
REFERENCE_AVcc_AVss,
REFVOLT_LEVEL_NONE,
SHT_SOURCE_ACLK,
SHT_CLOCK_DIV_1,
SAMPLE_HOLD_4_CYCLES,
SAMPCON_SOURCE_SMCLK,
SAMPCON_CLOCK_DIV_1
};
const msp430adc12_channel_config_t exTempAdc = {
INPUT_CHANNEL_A5,
REFERENCE_VREFplus_AVss,
REFVOLT_LEVEL_1_5,
SHT_SOURCE_ACLK,
SHT_CLOCK_DIV_1,
SAMPLE_HOLD_4_CYCLES,
SAMPCON_SOURCE_SMCLK,
SAMPCON_CLOCK_DIV_1
};
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/TimerConfig.h | /**
* The M16c/62p hardware timer configuration used by Mulle.
*
* STOP MODE ENABLED:
* TB0 bridges its tics from the RV8564 to TB2 in TMilli speed.
* TA0 and TA1 are used to create a 32 bit counter. TA0 counts
* tics from TB2 and TA1 counts TA0 underflows.
* TA2 and TA3 are used to create a 32 bit Alarm. TA2 counts
* tics from TB2 and TA3 counts TA3 underflows.
*
* STOP MODE DISABLED:
* TA1 generates TMilli tics.
* TA0 is a 16 bit counter that counts tics from TA1.
* TA2 is a 16 bit alarm that counts tics from TA1.
*
* ALWAYS USED:
* NOTE: These timers are turned off when the mcu goes into stop mode.
* TB3 generates TMicro tics.
* TB4 is a 16 bit TMicro counter that counts tics from TB3.
*
* @author <NAME>
*/
#ifndef __TIMERCONFIG_H__
#define __TIMERCONFIG_H__
// Use hw timers alone.
#define MILLI32_SOURCE TimerA1
#define MILLI32_SOURCE_CTRL TimerA1Ctrl
#define COUNTER_MILLI32 TimerA0
#define COUNTER_MILLI32_CTRL TimerA0Ctrl
#define ALARM_MILLI32 TimerA2
#define ALARM_MILLI32_CTRL TimerA2Ctrl
// End
// Use the RV8564 chip to generate tics (stop mode enabled).
#define MILLI32_SOURCE1 TimerB0
#define MILLI32_SOURCE1_CTRL TimerB0Ctrl
#define MILLI32_SOURCE2 TimerB1
#define MILLI32_SOURCE2_CTRL TimerB1Ctrl
#define MILLI32_SOURCE3 TimerB2
#define MILLI32_SOURCE3_CTRL TimerB2Ctrl
#define COUNTER_MILLI32_LOW TimerA0
#define COUNTER_MILLI32_LOW_CTRL TimerA0Ctrl
#define COUNTER_MILLI32_HIGH TimerA1
#define COUNTER_MILLI32_HIGH_CTRL TimerA1Ctrl
#define ALARM_MILLI32_LOW TimerA2
#define ALARM_MILLI32_LOW_CTRL TimerA2Ctrl
#define ALARM_MILLI32_HIGH TimerA3
#define ALARM_MILLI32_HIGH_CTRL TimerA3Ctrl
// end
// Common settings.
#define COUNTER_MICRO16_SOURCE TimerB3
#define COUNTER_MICRO16_SOURCE_CTRL TimerB3Ctrl
#define COUNTER_MICRO16 TimerB4
#define COUNTER_MICRO16_CTRL TimerB4Ctrl
// end.
#endif // __TIMERCONFIG_H__
|
tinyos-io/tinyos-3.x-contrib | diku/sensinode/tos/platforms/micro4/HPLSpi.h | /*
* Copyright (c) 2007 University of Copenhagen
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of University of Copenhagen 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 COPYRIGHT HOLDERS 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 UNIVERSITY
* OF COPENHAGEN OR ITS 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.
*/
/**
*
* @author <NAME> <<EMAIL>>
* @author <NAME> <<EMAIL>>
*/
#ifndef _H_HPLSpi_h
#define _H_HPLSpi_h
#define SPI_RESOURCE "SPI.Resource"
#define configCPU_CLOCK_HZ ( ( unsigned long ) 8000000 )
#ifndef configSMCLK_HZ
#define SPI_115K (configCPU_CLOCK_HZ / 115200)
#define SPI_1M (configCPU_CLOCK_HZ / 1000000)
#define SPI_4M (configCPU_CLOCK_HZ / 4000000)
#else
#define SPI_115K (configSMCLK_HZ / 115200)
#define SPI_1M (configSMCLK_HZ / 1000000)
#define SPI_4M (configSMCLK_HZ / 4000000)
#endif
typedef enum
{
BUS_SPI_DEFAULT = 0x00,
BUS_STE = 0x01,
BUS_PHASE_INVERT = 0x02,
BUS_CLOCK_INVERT = 0x04,
BUS_MULTIMASTER = 0x08,
BUS_CLOCK_115kHZ = 0x20,
BUS_CLOCK_1MHZ = 0x40,
BUS_CLOCK_4MHZ = 0x60,
BUS_SPI_SLAVE = 0x80
}bus_spi_flags;
#endif//_H_HPLSpi_h
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/compress/rgb2ycc.h | /*
* YCbCr is defined per CCIR 601-1, except that Cb and Cr are
* normalized to the range 0..MAXJSAMPLE rather than -0.5 .. 0.5.
* The conversion equations to be implemented are therefore
* Y = 0.29900 * R + 0.58700 * G + 0.11400 * B
* Cb = -0.16874 * R - 0.33126 * G + 0.50000 * B + CENTERJSAMPLE
* Cr = 0.50000 * R - 0.41869 * G - 0.08131 * B + CENTERJSAMPLE
* (These numbers are derived from TIFF 6.0 section 21, dated 3-June-92.)
* Note: older versions of the IJG code used a zero offset of MAXJSAMPLE/2,
* rather than CENTERJSAMPLE, for Cb and Cr. This gave equal positive and
* negative swings for Cb/Cr, but meant that grayscale values (Cb=Cr=0)
* were not represented exactly. Now we sacrifice exact representation of
* maximum red and maximum blue in order to get exact grayscales.
*
* To avoid floating-point arithmetic, we represent the fractional constants
* as integers scaled up by 2^16 (about 4 digits precision); we have to divide
* the products by 2^16, with appropriate rounding, to get the correct answer.
*
* The CENTERJSAMPLE offsets and the rounding fudge-factor of 0.5 are included
* in the tables to save adding them separately in the inner loop.
*/
#define MAXJSAMPLE 255
#define CENTERJSAMPLE 128
#define SCALEBITS 16 /* speediest right-shift on some machines */
#define CBCR_OFFSET ((int32_t) CENTERJSAMPLE << SCALEBITS)
#define ONE_HALF ((int32_t) 1 << (SCALEBITS-1))
#define FIX(x) ((int32_t) ((x) * (1L<<SCALEBITS) + 0.5))
#define R_Y_OFF 0 /* offset to R => Y section */
#define G_Y_OFF (1*(MAXJSAMPLE+1)) /* offset to G => Y section */
#define B_Y_OFF (2*(MAXJSAMPLE+1)) /* etc. */
#define R_CB_OFF (3*(MAXJSAMPLE+1))
#define G_CB_OFF (4*(MAXJSAMPLE+1))
#define B_CB_OFF (5*(MAXJSAMPLE+1))
#define R_CR_OFF B_CB_OFF /* B=>Cb, R=>Cr are the same */
#define G_CR_OFF (6*(MAXJSAMPLE+1))
#define B_CR_OFF (7*(MAXJSAMPLE+1))
#define RGB_YCC_TABLE_SIZE (8*(MAXJSAMPLE+1))
/*
* Initialize for RGB->YCC colorspace conversion.
*/
void rgb_ycc_init (int32_t *rgb_ycc_tab)
{
int32_t i;
for (i = 0; i <= MAXJSAMPLE; i++) {
rgb_ycc_tab[i+R_Y_OFF] = FIX(0.29900) * i;
rgb_ycc_tab[i+G_Y_OFF] = FIX(0.58700) * i;
rgb_ycc_tab[i+B_Y_OFF] = FIX(0.11400) * i + ONE_HALF;
rgb_ycc_tab[i+R_CB_OFF] = (-FIX(0.16874)) * i;
rgb_ycc_tab[i+G_CB_OFF] = (-FIX(0.33126)) * i;
rgb_ycc_tab[i+B_CB_OFF] = FIX(0.50000) * i + CBCR_OFFSET + ONE_HALF-1;
rgb_ycc_tab[i+G_CR_OFF] = (-FIX(0.41869)) * i;
rgb_ycc_tab[i+B_CR_OFF] = (-FIX(0.08131)) * i;
}
}
/*
* Convert some rows of samples to the JPEG colorspace.
*
* Note that we change from the application's interleaved-pixel format
* to our internal noninterleaved, one-plane-per-component format.
* The input buffer is therefore three times as wide as the output buffer.
*
* A starting row offset is provided only for the output buffer. The caller
* can easily adjust the passed input_buf value to accommodate any row
* offset required on that side.
*/
void rgb_ycc_convert (uint8_t *input_buf, uint8_t *output_buf, int32_t *ctab,
uint16_t width, uint16_t height)
{
int32_t r, g, b, i, j;
for (i=0; i<width; i+=3)
for (j=0; j<height; j++)
{
r = input_buf[i+j*width+0];
g = input_buf[i+j*width+1];
b = input_buf[i+j*width+2];
output_buf[i+j*width+0] = (uint8_t)
((ctab[r+R_Y_OFF] + ctab[g+G_Y_OFF] + ctab[b+B_Y_OFF]) >> SCALEBITS);
/* Cb */
output_buf[i+j*width+1] = (uint8_t)
((ctab[r+R_CB_OFF] + ctab[g+G_CB_OFF] + ctab[b+B_CB_OFF])>> SCALEBITS);
/* Cr */
output_buf[i+j*width+2] = (uint8_t)
((ctab[r+R_CR_OFF] + ctab[g+G_CR_OFF] + ctab[b+B_CR_OFF])>> SCALEBITS);
}
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/firmware.c | /**
* NXT bootstrap interface; NXT firmware handling code.
*
* Copyright 2006 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include "error.h"
#include "lowlevel.h"
#include "samba.h"
#include "flash.h"
#include "firmware.h"
#include "flash_routine.h"
static nxt_error_t
nxt_flash_prepare(nxt_t *nxt)
{
// Put the clock in PLL/2 mode
NXT_ERR(nxt_write_word(nxt, 0xFFFFFC30, 0x7));
// Unlock the flash chip
NXT_ERR(nxt_flash_unlock_all_regions(nxt));
// Send the flash writing routine
NXT_ERR(nxt_send_file(nxt, 0x202000, flash_bin, flash_len));
return NXT_OK;
}
static nxt_error_t
nxt_flash_block(nxt_t *nxt, nxt_word_t block_num, char *buf)
{
// Set the target block number
NXT_ERR(nxt_write_word(nxt, 0x202300, block_num));
// Send the block to flash
NXT_ERR(nxt_send_file(nxt, 0x202100, buf, 256));
// Jump into the flash writing routine
NXT_ERR(nxt_jump(nxt, 0x202000));
return NXT_OK;
}
static nxt_error_t
nxt_flash_finish(nxt_t *nxt)
{
return nxt_flash_wait_ready(nxt);
}
static nxt_error_t
nxt_firmware_validate_fd(int fd)
{
struct stat s;
if (fstat(fd, &s) < 0)
return NXT_FILE_ERROR;
if (s.st_size > 256*1024)
return NXT_INVALID_FIRMWARE;
return NXT_OK;
}
nxt_error_t
nxt_firmware_validate(char *fw_path)
{
nxt_error_t err;
int fd;
fd = open(fw_path, O_RDONLY);
if (fd < 0)
return NXT_FILE_ERROR;
err = nxt_firmware_validate_fd(fd);
close(fd);
return err;
}
nxt_error_t
nxt_firmware_flash(nxt_t *nxt, char *fw_path)
{
int fd, i, err;
fd = open(fw_path, O_RDONLY);
if (fd < 0)
return NXT_FILE_ERROR;
err = nxt_firmware_validate_fd(fd);
if (err != NXT_OK)
{
close(fd);
return NXT_INVALID_FIRMWARE;
}
NXT_ERR(nxt_flash_prepare(nxt));
for (i = 0; i < 1024; i++) //256*1024; i += 256)
{
char buf[256];
int ret;
memset(buf, 0, 256);
ret = read(fd, buf, 256);
if (ret != -1)
NXT_ERR(nxt_flash_block(nxt, i, buf));
if (ret < 256)
{
close(fd);
NXT_ERR(nxt_flash_finish(nxt));
return ret == -1 ? NXT_FILE_ERROR : NXT_OK;
}
NXT_ERR(nxt_flash_block(nxt, i, buf));
}
close(fd);
NXT_ERR(nxt_flash_finish(nxt));
return NXT_OK;
}
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/rt_structs.h | #ifndef RT_STRUCTS_H_INCLUDED
#define RT_STRUCTS_H_INCLUDED
#include "nodes.h"
#include "eon_network.h"
#define SRC_QUEUE_SIZE 3
typedef struct rt_data
{
uint16_t sessionID;
uint16_t weight;
uint8_t minstate;
} rt_data;
typedef struct GenericNode
{
rt_data _pdata;
} GenericNode;
#define RTCLOCKINTERVAL (60L * 1024L)
#define EVALINTERVAL (60L*60L * 1024L)
//#define EVALINTERVAL (60L * 1024L)
//save runtime data every hour
#define RT_SAVE_TIME (3L * 60L * 60L * 1024L)
//#define RT_SAVE_TIME (60L * 1024L)
#define RT_RECOVER_TIME (10L * 1024L)
//typedef uint8_t request_t[50];
#define LOAD_WEIGHT (0.04)
enum {
//BATTERY_CAPACITY = (200LL * 360LL * 37LL * 1000LL), //uJ
BATTERY_CAPACITY = (600LL * 360LL * 37LL * 1000LL), //uJ
};
typedef struct __runtime_state
{
uint16_t save_flag;
double load_avg;
uint8_t srcprob[NUMSOURCES];
uint8_t spc[NUMSOURCES];
uint8_t prob[NUMPATHS];
uint8_t pc[NUMPATHS];
int32_t pathenergy[NUMPATHS];
int64_t batt_reserve;
uint8_t curstate;
double curgrade;
} __runtime_state_t;
//__runtime_state_t __rtstate;
//uint16_t *g_lastmem = (uint16_t*)3967;
//uint16_t deadlocked_edge_id = 0xFFFF;
//int16_t alloc_size = 0xFFFF;
//uint16_t rt_clock = 0;
//int save_state;
//int save_retries;
//void *queue_ptr = NULL;
//#define MAX_SAVE_RET 10
//#define SAVE_PAGE 0
#endif
|
tinyos-io/tinyos-3.x-contrib | intelmote2/apps/cameraMultiHop/camNode/cameraJpegTest.h | <filename>intelmote2/apps/cameraMultiHop/camNode/cameraJpegTest.h<gh_stars>1-10
/*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Stanford University 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 COPYRIGHT HOLDERS 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 STANFORD
* UNIVERSITY OR ITS 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.
*/
/**
* @author <NAME> (<EMAIL>)
*/
#ifndef _CAMERAJPEGTEST_H_
#define _CAMERAJPEGTEST_H_
enum {
AM_OV_DBG = 2,
AM_PXA_DBG = 3,
AM_CMD_MSG = 4,
AM_IMG_STAT = 5,
AM_CMD_MSG_ACK = 8,
AM_CTP_IMG_STAT = 0x85,
AM_CTP_CMD_IMG = 0x84,
AM_STATUS = 0x10,
CMD_KEY = 0x1
};
enum {
IMG_COL=1,
IMG_JPG=2,
};
typedef nx_struct img_stat{
nx_uint16_t node_id;
nx_uint8_t type;
nx_uint16_t width;
nx_uint16_t height;
nx_uint32_t data_size;
nx_uint32_t timeAcq;
nx_uint32_t timeProc;
} img_stat_t;
typedef nx_struct cmd_msg{
nx_uint16_t node_id;
nx_uint8_t cmd;
nx_uint16_t val1;
nx_uint16_t val2;
} cmd_msg_t;
typedef nx_struct cmd_msg_ack{
nx_uint16_t node_id;
nx_uint8_t cmd;
nx_uint16_t val1;
nx_uint16_t val2;
nx_uint8_t acked; //0 for unacked, 1 for acked
} cmd_msg_ack_t;
typedef nx_struct status{
nx_uint16_t node_id;
nx_uint16_t seqNo;
nx_uint16_t parent;
nx_uint16_t ETX;
} status_t;
typedef nx_struct {
nx_uint32_t addr;
nx_uint32_t reg_val;
} dbg_msg32_t;
typedef nx_struct {
nx_uint8_t addr;
nx_uint8_t reg_val;
} dbg_msg8_t;
#endif //_CAMERAJPEGTEST_H_
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/compress/dctfstBlk.h | #define CONST_BITS 8
#define PASS1_BITS 2
#define MAXJSAMPLE 255
#define CENTERJSAMPLE 128
#define DCTSIZE 8
#define FIX_0_382683433 ((int32_t) 98)
#define FIX_0_541196100 ((int32_t) 139)
#define FIX_0_707106781 ((int32_t) 181)
#define FIX_1_306562965 ((int32_t) 334)
#define FIX_1_082392200 ((int32_t) 277)
#define FIX_1_414213562 ((int32_t) 362)
#define FIX_1_847759065 ((int32_t) 473)
#define FIX_2_613125930 ((int32_t) 669)
#define RIGHT_SHIFT(x,shft) ((x) >> (shft))
#define DESCALE(x,n) RIGHT_SHIFT(x, n)
#define MULTIPLY(var,const) ((int32_t) DESCALE((var) * (const), CONST_BITS))
#define RANGE_MASK (MAXJSAMPLE * 4 + 3)
static inline int8_t quantize(int32_t _val, uint8_t qval, uint8_t quality, uint8_t isDC)
{
int16_t quant = qval*quality;
int32_t val=_val;
if (val>0)
val+=quant>>1;
else
val-=quant>>1;
if (quant!=0)
val/=quant;
if (!isDC)
{
if (val>127) {val=127;}
else if (val< -128) {val=-128;}
}
else if (val>255) {val=255;}
return (int8_t)val;
}
static inline void dctQuantBlock(uint8_t blkIdx_i, uint8_t blkIdx_j, uint16_t numBlks,
uint8_t *img_data, uint8_t bytesPerPixel, int8_t *out,
uint8_t *qtable, uint8_t quality, uint16_t pixelsPerRow)
{
uint16_t blksPerRow = pixelsPerRow>>3;
uint8_t *dataptr = &img_data[(pixelsPerRow*(blkIdx_j<<3)+(blkIdx_i<<3))*bytesPerPixel];
int8_t *optr = &out[blksPerRow*blkIdx_j+blkIdx_i];
int32_t tmp0, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6, tmp7;
int32_t tmp10, tmp11, tmp12, tmp13;
int32_t z1, z2, z3, z4, z5, z11, z13;
int32_t ctr;
int32_t tmp[64*bytesPerPixel];
int32_t *tmpptr = tmp;
for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
uint8_t idx1=0*bytesPerPixel, idx2=7*bytesPerPixel;//0,7
tmp0 = (int32_t)dataptr[idx1] + dataptr[idx2];
tmp7 = (int32_t)dataptr[idx1] - dataptr[idx2];
idx1+=bytesPerPixel; idx2-=bytesPerPixel;//1.6
tmp1 = (int32_t)dataptr[idx1] + dataptr[idx2];
tmp6 = (int32_t)dataptr[idx1] - dataptr[idx2];
idx1+=bytesPerPixel; idx2-=bytesPerPixel;//2,5
tmp2 = (int32_t)dataptr[idx1] + dataptr[idx2];
tmp5 = (int32_t)dataptr[idx1] - dataptr[idx2];
idx1+=bytesPerPixel; idx2-=bytesPerPixel;//3,4
tmp3 = (int32_t)dataptr[idx1] + dataptr[idx2];
tmp4 = (int32_t)dataptr[idx1] - dataptr[idx2];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
tmpptr[0] = tmp10 + tmp11; /* phase 3 */
tmpptr[4] = tmp10 - tmp11;
z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
tmpptr[2] = tmp13 + z1; /* phase 5 */
tmpptr[6] = tmp13 - z1;
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
tmpptr[5] = z13 + z2; /* phase 6 */
tmpptr[3] = z13 - z2;
tmpptr[1] = z11 + z4;
tmpptr[7] = z11 - z4;
//dataptr += pixelsPerRow<<bytesPerPixel; /* advance pointer to next row */
dataptr += pixelsPerRow*bytesPerPixel; /* advance pointer to next row */
tmpptr += 8;
}
/* Pass 2: process columns. */
tmpptr = tmp;
for (ctr = DCTSIZE-1; ctr >= 0; ctr--) {
tmp0 = (int32_t)tmpptr[8*0] + tmpptr[8*7];
tmp7 = (int32_t)tmpptr[8*0] - tmpptr[8*7];
tmp1 = (int32_t)tmpptr[8*1] + tmpptr[8*6];
tmp6 = (int32_t)tmpptr[8*1] - tmpptr[8*6];
tmp2 = (int32_t)tmpptr[8*2] + tmpptr[8*5];
tmp5 = (int32_t)tmpptr[8*2] - tmpptr[8*5];
tmp3 = (int32_t)tmpptr[8*3] + tmpptr[8*4];
tmp4 = (int32_t)tmpptr[8*3] - tmpptr[8*4];
/* Even part */
tmp10 = tmp0 + tmp3; /* phase 2 */
tmp13 = tmp0 - tmp3;
tmp11 = tmp1 + tmp2;
tmp12 = tmp1 - tmp2;
optr[numBlks*0] = quantize(tmp10 + tmp11,qtable[8*0],quality,
(ctr==DCTSIZE-1)?1:0); /* phase 3 */
optr[numBlks*4] = quantize(tmp10 - tmp11,qtable[8*4],quality,0);
z1 = MULTIPLY(tmp12 + tmp13, FIX_0_707106781); /* c4 */
optr[numBlks*2] = quantize(tmp13 + z1,qtable[8*2],quality,0); /* phase 5 */
optr[numBlks*6] = quantize(tmp13 - z1,qtable[8*6],quality,0);
/* Odd part */
tmp10 = tmp4 + tmp5; /* phase 2 */
tmp11 = tmp5 + tmp6;
tmp12 = tmp6 + tmp7;
/* The rotator is modified from fig 4-8 to avoid extra negations. */
z5 = MULTIPLY(tmp10 - tmp12, FIX_0_382683433); /* c6 */
z2 = MULTIPLY(tmp10, FIX_0_541196100) + z5; /* c2-c6 */
z4 = MULTIPLY(tmp12, FIX_1_306562965) + z5; /* c2+c6 */
z3 = MULTIPLY(tmp11, FIX_0_707106781); /* c4 */
z11 = tmp7 + z3; /* phase 5 */
z13 = tmp7 - z3;
optr[numBlks*5] = quantize(z13 + z2,qtable[8*5],quality,0); /* phase 6 */
optr[numBlks*3] = quantize(z13 - z2,qtable[8*3],quality,0);
optr[numBlks*1] = quantize(z11 + z4,qtable[8*1],quality,0);
optr[numBlks*7] = quantize(z11 - z4,qtable[8*7],quality,0);
optr+=numBlks<<3;
tmpptr++;
qtable++;
}
}
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/simple/simple_comp.c | <reponame>tinyos-io/tinyos-3.x-contrib
/**************************************************************************
*
* simple_comp.c
*
* This file is licensed under the GNU GPL.
*
* (C) 2005, <NAME> <<EMAIL>>
*
*/
#include "../compressor.h"
#include "../buffer.h"
#include <string.h>
#define SHORT_BITS 4
#define SHORT_MASK ((1 << (SHORT_BITS - 1)) - 1)
void write_measurement(int16_t diff, int16_t val)
{
// fprintf(stderr, "Difference is: %d\n", diff);
if (diff <= SHORT_MASK && diff >= -(SHORT_MASK + 1)) {
// fprintf(stderr, "Writing short\n");
write_bits(1, 1);
write_bits(diff & ((1 << SHORT_BITS) - 1), SHORT_BITS);
} else {
write_bits(0, 1);
write_bits((val >> 8) & 0x0F, 4);
write_bits(val & 0xFF, 8);
}
}
int first = 1;
void compress_sample(int16_t digi_x, int16_t digi_y, int16_t digi_z,
uint16_t ana_x, uint16_t ana_y)
{
static int last_val[3];
if (first) {
reset_buffer();
first = 0;
write_bits((digi_x >> 8) & 0x0F, 4);
write_bits(digi_x & 0xFF, 8);
write_bits((digi_y >> 8) & 0x0F, 4);
write_bits(digi_y & 0xFF, 8);
write_bits((digi_z >> 8) & 0x0F, 4);
write_bits(digi_z & 0xFF, 8);
last_val[0] = digi_x;
last_val[1] = digi_y;
last_val[2] = digi_z;
return;
}
if (bits_left() < 3 * 13) {
handle_full_buffer(get_buffer(), bits_left()/(uint8_t)8);
reset_buffer();
}
write_measurement(digi_x - last_val[0], digi_x);
write_measurement(digi_y - last_val[1], digi_y);
write_measurement(digi_z - last_val[2], digi_z);
last_val[0] = digi_x;
last_val[1] = digi_y;
last_val[2] = digi_z;
}
void flush()
{
uint8_t *tmp = get_unwritten();
memset(tmp, 0, MEMBUFSIZE - (tmp - get_buffer()));
handle_full_buffer(get_buffer(), bits_left()/(uint8_t)8);
first = 1;
}
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/lib6lowpan/tests/test_unpack_tcfl.c | <filename>berkeley/blip-2.0/support/sdk/c/blip/lib6lowpan/tests/test_unpack_tcfl.c
#include <stdint.h>
#include <stdio.h>
#include "Ieee154.h"
#include "ip.h"
#include "lib6lowpan.h"
#include "nwbyte.h"
#include "6lowpan.h"
uint8_t *unpack_tcfl(struct ip6_hdr *hdr, uint8_t dispatch, uint8_t *buf);
struct {
uint32_t result;
/* the result of executing the test case */
uint8_t test_dispatch;
int test_len;
uint8_t test[4];
} test_cases[] = {
{0x60000000, LOWPAN_IPHC_TF_NONE, 0, {}},
{0x60000000, LOWPAN_IPHC_TF_NONE | ~LOWPAN_IPHC_TF_MASK, 0, {}},
// ECN bit
{0x60100000, LOWPAN_IPHC_TF_ECN_DSCP, 1, {0x40}},
// ecn and DSCP
{0x6ab00000, LOWPAN_IPHC_TF_ECN_DSCP, 1, {0xea}},
// ECN + FL
{0x60301234, LOWPAN_IPHC_TF_ECN_FL, 3, {0xc0, 0x12, 0x34}},
// full
{0x6f012345, LOWPAN_IPHC_TF_ECN_DSCP_FL, 4, {0x3c, 0x01, 0x23, 0x45}},
};
int run_tests() {
int i;
int success = 0, total = 0;
for (i = 0; i < (sizeof(test_cases) / sizeof(test_cases[0])); i++) {
struct ip6_hdr hdr;
uint8_t *rb;
total ++;
rb = unpack_tcfl(&hdr, test_cases[i].test_dispatch, test_cases[i].test);
printf("result: 0x%x correct: 0x%x\n", ntohl(hdr.ip6_flow), test_cases[i].result);
printf("length: %i\n", rb - test_cases[i].test);
if (test_cases[i].test_len != rb - test_cases[i].test)
continue;
if (test_cases[i].result != ntohl(hdr.ip6_flow))
continue;
success ++;
}
printf("%s: %i/%i tests succeeded\n", __FILE__, success, total);
if (success == total) return 0;
return 1;
}
int main() {
return run_tests();
}
|
tinyos-io/tinyos-3.x-contrib | stanford-sing/s4-tinyos-2.x/tos/lib/linkestimator/ReverseLinkInfo.h | <filename>stanford-sing/s4-tinyos-2.x/tos/lib/linkestimator/ReverseLinkInfo.h
// ex: set tabstop=2 shiftwidth=2 expandtab syn=c:
// $Id: ReverseLinkInfo.h,v 1.1 2008/10/23 22:22:41 genie1 Exp $
/*
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/*
* Authors: <NAME>
* Date Last Modified: 2005/05/26
*/
#ifndef REV_LINK_H
#define REV_LINK_H
#include "LinkEstimator.h"
enum {
NUM_REVERSE_LINK_ENTRIES = 7,
REVERSE_LINK_INVALID_ADDR = 65535u,
};
typedef nx_struct {
nx_uint16_t addr;
nx_uint8_t quality;
} ReverseLinkEntry;
typedef nx_struct {
nx_uint8_t num_elements;
nx_uint8_t total_links;
ReverseLinkEntry entries[NUM_REVERSE_LINK_ENTRIES];
} ReverseLinkInfo;
typedef nx_struct LE_Reverse_Link_Estimation_Msg {
LEHeader header;
ReverseLinkInfo info;
} ReverseLinkMsg;
error_t reverseLinkInfoInit(ReverseLinkInfo* ptr) {
int i;
if (ptr == NULL)
return FAIL;
ptr->num_elements = 0;
for (i = 0; i < NUM_REVERSE_LINK_ENTRIES; i++) {
ptr->entries[i].addr = REVERSE_LINK_INVALID_ADDR;
ptr->entries[i].quality = 0;
}
return SUCCESS;
}
error_t reverseLinkInfoGetQuality(ReverseLinkInfo* rliPtr, uint16_t addr, uint8_t *quality) {
int i;
bool found = FALSE;
if (rliPtr == NULL)
return FAIL;
for (i = 0; i < rliPtr->num_elements && !found; i++) {
dbg("S4-debug", "%d\n", rliPtr->entries[i].addr);
found = (rliPtr->entries[i].addr == addr);
if (found) {
*quality = rliPtr->entries[i].quality;
}
}
return (found)?SUCCESS:FAIL;
}
error_t reverseLinkInfoReset(ReverseLinkInfo* rliPtr) {
int i;
if (rliPtr == NULL)
return FAIL;
for (i = 1; i < rliPtr->num_elements; i++) {
rliPtr->entries[i].addr = REVERSE_LINK_INVALID_ADDR;
rliPtr->entries[i].quality = 0;
}
rliPtr->num_elements = 0;
return SUCCESS;
}
/* Appends an entry to this ReverseLinkInfo structure, unless it is full, in which case
* it returns false. It is up to the caller to save state in order to, for example,
* add elements in a round robin fashion across messages.
* @return FAIL is not able to append
*/
error_t reverseLinkInfoAppend(ReverseLinkInfo* rliPtr, uint16_t addr, uint8_t quality) {
if (rliPtr == NULL)
return FAIL;
if (rliPtr->num_elements >= NUM_REVERSE_LINK_ENTRIES)
return FAIL;
rliPtr->entries[rliPtr->num_elements].addr = addr;
rliPtr->entries[rliPtr->num_elements].quality = quality;
rliPtr->num_elements++;
return SUCCESS;
}
error_t reverseLinkInfoFromMsg(ReverseLinkInfo* rliPtr, ReverseLinkMsg* msg) {
*rliPtr = msg->info;
if (rliPtr->num_elements > NUM_REVERSE_LINK_ENTRIES) {
rliPtr->num_elements = NUM_REVERSE_LINK_ENTRIES;
}
return SUCCESS;
}
error_t reverseLinkInfoToMsg(ReverseLinkInfo* rliPtr, ReverseLinkMsg* msg) {
if (rliPtr == NULL || msg == NULL)
return FAIL;
msg->info = *rliPtr;
return SUCCESS;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | csau/ub/apps/UnifiedBroadcastTest/src/UnifiedBroadcastApp.h |
/**
* @author <NAME> <mth at cs dot au dot dk>
* @date June 6 2010
*/
#ifndef UNIFIEDBROADCASTAPP_H
#define UNIFIEDBROADCASTAPP_H
#include "AM.h"
#ifndef TOSSIM
#include "CC2420.h"
#include "CC2420TimeSyncMessage.h"
#endif
typedef struct test_msg {
nx_uint32_t counter;
nx_uint32_t timestamp;
} test_msg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | ethz/snpk/apps/tests/SyncMacStress/SyncMacStress.h | /**
* @author <NAME>
*/
#ifndef SYNCMACSTRESS_H
#define SYNCMACSTRESS_H
#include <AM.h>
enum {
AM_TEST = 0x10,
LPL_INT = 300UL,
MSG_LEN = 30,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/platform.h | <gh_stars>1-10
#ifndef __PLATFORM_H__
#define __PLATFORM_H__
#define MCU_SPEED_10MHz M16C62P_MAIN_CLK_DIV_0
#define MCU_SPEED_5MHz M16C62P_MAIN_CLK_DIV_2
#define MCU_SPEED_2_5MHz M16C62P_MAIN_CLK_DIV_4
#define MCU_SPEED_1_25MHz M16C62P_MAIN_CLK_DIV_8
#define MCU_SPEED_0_625MHz M16C62P_MAIN_CLK_DIV_16
#endif // __PLATFORM_H__
|
tinyos-io/tinyos-3.x-contrib | eon/apps/turtle_snapper/impl/tinynode/typechecks.h | <filename>eon/apps/turtle_snapper/impl/tinynode/typechecks.h<gh_stars>1-10
#ifndef TYPECHECKS_H_INCLUDED
#define TYPECHECKS_H_INCLUDED
bool IsAccept(bool value)
{
return value;
}
#endif // TYPECHECKS_H_INCLUDED
|
tinyos-io/tinyos-3.x-contrib | ethz/tinynode184/tos/chips/sx1211/SX1211.h | <filename>ethz/tinynode184/tos/chips/sx1211/SX1211.h
/*
* Copyright (c) 2005, Ecole Polytechnique Federale de Lausanne (EPFL)
* and Shockfish SA, Switzerland.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Ecole Polytechnique Federale de Lausanne (EPFL)
* and Shockfish SA, 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 COPYRIGHT HOLDERS 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 COPYRIGHT
* OWNER 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.
*
* ========================================================================
*/
/*
* XE1205 constants and helper macros and functions.
*
*/
/**
* @author <NAME>
* @author <NAME>
*
*/
#ifndef _SX1211CONST_H
#define _SX1211CONST_H
#include "AM.h"
typedef nx_struct sx1211_header_t {
nx_uint8_t len;
nx_am_addr_t dest;
nx_am_addr_t source;
nx_am_id_t type;
nx_am_group_t group;
nx_uint8_t ack;
} sx1211_header_t;
typedef nx_struct sx1211_footer_t {
#ifdef LOW_POWER_LISTENING
nx_uint16_t rxInterval;
#endif
// nxle_uint16_t crc;
} sx1211_footer_t;
typedef nx_struct sx1211_metadata_t {
nx_uint16_t time;
nx_uint8_t length;
nx_uint8_t strength;
} sx1211_metadata_t;
/*
* Register address generators.
*/
#define SX1211_WRITE(register_) (((register_) << 1) & 0x3E)
#define SX1211_READ(register_) ((((register_) << 1) & 0x7E) | 0x40)
/**
* Register addresses.
*/
enum sx1211_register_enums {
MCParam_0 = 0,
MCParam_1 = 1,
MCParam_2 = 2,
MCParam_3 = 3,
MCParam_4 = 4,
IrqParam_5 = 5,
IrqParam_6 = 6,
TXParam_7 = 7,
RXParam_8 = 8,
RXParam_9 = 9,
RXParam_10 = 10,
RXParam_11 = 11,
RXParam_12 = 12,
Pattern_13 = 13,
Pattern_14 = 14,
Pattern_15 = 15,
Pattern_16 = 16,
OscParam_17 = 17,
OscParam_18 = 18,
TParam_19 = 19,
TParam_21 = 21,
TParam_22 = 22,
SX1211_RegCount
};
enum sx1211_reg_addr {
// Main Configuration Param
REG_MCPARAM1 = 0x00,
REG_MCPARAM2 = 0x01,
REG_FDEV = 0x02,
REG_BITRATE = 0x03,
REG_OOKFLOORTHRESH = 0x04,
REG_MCPARAM6 = 0x05,
REG_R1 = 0x06,
REG_P1 = 0x07,
REG_S1 = 0x08,
REG_R2 = 0x09,
REG_P2 = 0x0A,
REG_S2 = 0x0B,
REG_PARAMP = 0x0C,
// IRQ Param
REG_IRQ0PARAM = 0x0D,
REG_IRQ1PARAM = 0x0E,
REG_RSSIIRQTHRESH = 0x0F,
// RX Param
REG_RXPARAM1 = 0x10,
REG_RXPARAM2 = 0x11,
REG_RXPARAM3 = 0x12,
REG_RES19 = 0x13,
REG_RSSIVALUE = 0x14,
REG_RXPARAM6 = 0x15,
// Sync Param
REG_SYNCBYTE1 = 0x16,
REG_SYNCBYTE2 = 0x17,
REG_SYNCBYTE3 = 0x18,
REG_SYNCBYTE4 = 0x19,
// TX Param
REG_TXPARAM = 0x1A,
// OSC Param
REG_OSCPARAM = 0x1B,
// Pckt Param
REG_PKTPARAM1 = 0x1C,
REG_NODEADRS = 0x1D,
REG_PKTPARAM3 = 0x1E,
REG_PKTPARAM4 = 0x1F,
// SX1211_RegCount
};
// Chip operating mode
#define MC1_SLEEP 0x00
#define MC1_STANDBY 0x20
#define MC1_SYNTHESIZER 0x40
#define MC1_RECEIVER 0x60
#define MC1_TRANSMITTER 0x80
// Frequency band
#define MC1_BAND_915L 0x00
#define MC1_BAND_915H 0x08
#define MC1_BAND_868 0x10
#define MC1_BAND_950 0x10
// VCO trimming
#define MC1_VCO_TRIM_00 0x00
#define MC1_VCO_TRIM_01 0x02
#define MC1_VCO_TRIM_10 0x04
#define MC1_VCO_TRIM_11 0x06
// RF frequency selection
#define MC1_RPS_SELECT_1 0x00
#define MC1_RPS_SELECT_2 0x01
// MC Param 2
// Modulation scheme selection
#define MC2_MODULATION_OOK 0x40
#define MC2_MODULATION_FSK 0x80
// Data operation mode
#define MC2_DATA_MODE_CONTINUOUS 0x00
#define MC2_DATA_MODE_BUFFERED 0x20
#define MC2_DATA_MODE_PACKET 0x04
// Rx OOK threshold mode selection
#define MC2_OOK_THRESH_TYPE_FIXED 0x00
#define MC2_OOK_THRESH_TYPE_PEAK 0x08
#define MC2_OOK_THRESH_TYPE_AVERAGE 0x10
// Gain on IF chain
#define MC2_GAIN_IF_00 0x00
#define MC2_GAIN_IF_01 0x01
#define MC2_GAIN_IF_10 0x02
#define MC2_GAIN_IF_11 0x03
// Frequency deviation (kHz)
/**
* RF_FDEV >= RF_BITRATE
**/
#define RF_FDEV_33 0x0B
#define RF_FDEV_40 0x09
#define RF_FDEV_50 0x07
#define RF_FDEV_80 0x04
#define RF_FDEV_100 0x03
#define RF_FDEV_133 0x02
#define RF_FDEV_200 0x01
// Bitrate (bit/sec)
#define RF_BITRATE_1600 0x7C
#define RF_BITRATE_2000 0x63
#define RF_BITRATE_2500 0x4F
#define RF_BITRATE_5000 0x27
#define RF_BITRATE_8000 0x18
#define RF_BITRATE_10000 0x13
#define RF_BITRATE_20000 0x09
#define RF_BITRATE_25000 0x07
#define RF_BITRATE_40000 0x04
#define RF_BITRATE_50000 0x03
#define RF_BITRATE_66700 0x02
#define RF_BITRATE_100000 0x01
#define RF_BITRATE_200000 0x00
// MC Param 6
// FIFO size
#define MC6_FIFO_SIZE_16 0x00
#define MC6_FIFO_SIZE_32 0x40
#define MC6_FIFO_SIZE_48 0x80
#define MC6_FIFO_SIZE_64 0xC0
// FIFO threshold
#define RF_MC6_FIFO_THRESH_VALUE 0x0F
// SynthR1
#define RF_R1_VALUE 0x77
// SynthP1
#define RF_P1_VALUE 0x64
// SynthS1
#define RF_S1_VALUE 0x32
// SynthR2
#define RF_R2_VALUE 0x74
// SynthP2
#define RF_P2_VALUE 0x62
// SynthS2
#define RF_S2_VALUE 0x32
// PA ramp times in OOK
#define RF_PARAMP_00 0x00
#define RF_PARAMP_01 0x08
#define RF_PARAMP_10 0x10
#define RF_PARAMP_11 0x18
// IRQ Param 1
// Select RX&STDBY IRQ_0 sources (Packet mode)
#define RF_IRQ0_RX_STDBY_PAYLOADREADY 0x00
#define RF_IRQ0_RX_STDBY_WRITEBYTE 0x40
#define RF_IRQ0_RX_STDBY_FIFOEMPTY 0x80
#define RF_IRQ0_RX_STDBY_SYNCADRS 0xC0
// Select RX&STDBY IRQ_1 sources (Packet mode)
#define RF_IRQ1_RX_STDBY_CRCOK 0x00
#define RF_IRQ1_RX_STDBY_FIFOFULL 0x10
#define RF_IRQ1_RX_STDBY_RSSI 0x20
#define RF_IRQ1_RX_STDBY_FIFOTHRESH 0x30
// Select TX IRQ_1 sources (Packet mode)
#define RF_IRQ1_TX_FIFOFULL 0x00
#define RF_IRQ1_TX_TXDONE 0x08
// FIFO overrun/clear
#define RF_IRQ1_FIFO_OVERRUN_CLEAR 0x01
// IRQ Param 2
// Select TX start condition and IRQ_0 source (Packet mode)
#define RF_IRQ0_TX_FIFOTHRESH_START_FIFOTHRESH 0x00
#define RF_IRQ0_TX_FIFOEMPTY_START_FIFONOTEMPTY 0x10
// RSSI IRQ flag
#define RF_IRQ2_RSSI_IRQ_CLEAR 0x04
// PLL_Locked flag
#define RF_IRQ2_PLL_LOCK_CLEAR 0x02
// PLL_Locked pin
#define RF_IRQ2_PLL_LOCK_PIN_OFF 0x00
#define RF_IRQ2_PLL_LOCK_PIN_ON 0x01
// RSSI threshold for interrupt
#define RF_RSSIIRQTHRESH_VALUE 0x00
// RX Param 1
// Passive filter (kHz)
/*
* RX1_PASSIVEFILT ~= 3(RF_FDEV + RF_BITRATE/2)
*/
#define RX1_PASSIVEFILT_65 0x00
#define RX1_PASSIVEFILT_82 0x10
#define RX1_PASSIVEFILT_109 0x20
#define RX1_PASSIVEFILT_137 0x30
#define RX1_PASSIVEFILT_157 0x40
#define RX1_PASSIVEFILT_184 0x50
#define RX1_PASSIVEFILT_211 0x60
#define RX1_PASSIVEFILT_234 0x70
#define RX1_PASSIVEFILT_262 0x80
#define RX1_PASSIVEFILT_321 0x90
#define RX1_PASSIVEFILT_378 0xA0
#define RX1_PASSIVEFILT_414 0xB0
#define RX1_PASSIVEFILT_458 0xC0
#define RX1_PASSIVEFILT_514 0xD0
#define RX1_PASSIVEFILT_676 0xE0
#define RX1_PASSIVEFILT_987 0xF0
// Butterworth filter (kHz)
/*
* 3*RX1_FC_FOPLUS <= RX1_PASSIVEFILT <= 4*RX1_FC_FOPLUS
*/
#define RX1_FC_VALUE 0x03
// !!! Values defined below only apply if RFCLKREF = DEFAULT VALUE = 0x07 !!!
#define RX1_FC_FOPLUS25 0x00
#define RX1_FC_FOPLUS50 0x01
#define RX1_FC_FOPLUS75 0x02
#define RX1_FC_FOPLUS100 0x03
#define RX1_FC_FOPLUS125 0x04
#define RX1_FC_FOPLUS150 0x05
#define RX1_FC_FOPLUS175 0x06
#define RX1_FC_FOPLUS200 0x07
#define RX1_FC_FOPLUS225 0x08
#define RX1_FC_FOPLUS250 0x09
#define RX1_FC_FOPLUS275 0x0A
#define RX1_FC_FOPLUS300 0x0B
#define RX1_FC_FOPLUS325 0x0C
#define RX1_FC_FOPLUS350 0x0D
#define RX1_FC_FOPLUS375 0x0E
#define RX1_FC_FOPLUS400 0x0F
// RX Param 2
// Polyphase filter center value (kHz)
/*
* RX2_FO >=RX1_PASSIVEFILT/2
*/
#define RX2_FO_VALUE 0x03
// !!! Values defined below only apply if RFCLKREF = DEFAULT VALUE = 0x07 !!!
#define RX2_FO_50 0x10
#define RX2_FO_75 0x20
#define RX2_FO_100 0x30
#define RX2_FO_125 0x40
#define RX2_FO_150 0x50
#define RX2_FO_175 0x60
#define RX2_FO_200 0x70
#define RX2_FO_225 0x80
#define RX2_FO_250 0x90
#define RX2_FO_275 0xA0
#define RX2_FO_300 0xB0
#define RX2_FO_325 0xC0
#define RX2_FO_350 0xD0
#define RX2_FO_375 0xE0
#define RX2_FO_400 0xF0
// Rx Param 3
// Polyphase filter enable
#define RX3_POLYPFILT_ON 0x80
#define RX3_POLYPFILT_OFF 0x00
// Bit synchronizer
// Automatically activated in Packet mode
#define RX3_SYNC_RECOG_ON 0x20
#define RX3_SYNC_RECOG_OFF 0x00
// Sync word recognition
// Automatically activated in Packet mode
// Size of the reference sync word
#define RX3_SYNC_SIZE_8 0x00
#define RX3_SYNC_SIZE_16 0x08
#define RX3_SYNC_SIZE_24 0x10
#define RX3_SYNC_SIZE_32 0x18
// Number of tolerated errors for the sync word recognition
#define RX3_SYNC_TOL_0 0x00
#define RX3_SYNC_TOL_1 0x02
#define RX3_SYNC_TOL_2 0x04
#define RX3_SYNC_TOL_3 0x06
// TX Param
// Interpolator filter Tx (kHz)
#define TX_FC_VALUE 0x70
// !!! Values defined below only apply if RFCLKREF = DEFAULT VALUE = 0x07 !!!
#define TX_FC_25 0x00
#define TX_FC_50 0x10
#define TX_FC_75 0x20
#define TX_FC_100 0x30
#define TX_FC_125 0x40
#define TX_FC_150 0x50
#define TX_FC_175 0x60
#define TX_FC_200 0x70
#define TX_FC_225 0x80
#define TX_FC_250 0x90
#define TX_FC_275 0xA0
#define TX_FC_300 0xB0
#define TX_FC_325 0xC0
#define TX_FC_350 0xD0
#define TX_FC_375 0xE0
#define TX_FC_400 0xF0
#define TX_POWER_13DB 0x00
#define TX_POWER_10DB 0x01
#define TX_POWER_7DB 0x02
#define TX_POWER_4DB 0x03
#define TX_POWER_1DB 0x04
#define TX_POWER_MIN2DB 0x05
#define TX_POWER_MIN5DB 0x06
#define TX_POWER_MIN8DB 0x07
// PKT Param 1
// Manchester enable
#define PKT1_MANCHESTER_ON 0x80
#define PKT1_MANCHESTER_OFF 0x00
// Payload length
#define PKT1_LENGTH_VALUE 0x00
// Node Address
#define NODEADRS_VALUE 0x00
// PKT Param 3
//Packet format
#define PKT3_FORMAT_FIXED 0x00
#define PKT3_FORMAT_VARIABLE 0x80
// Preamble size
#define PKT3_PREAMBLE_SIZE_8 0x00
#define PKT3_PREAMBLE_SIZE_16 0x20
#define PKT3_PREAMBLE_SIZE_24 0x40
#define PKT3_PREAMBLE_SIZE_32 0x60
// Whitening enable
#define PKT3_WHITENING_ON 0x10
#define PKT3_WHITENING_OFF 0x00
// CRC enable
#define PKT3_CRC_ON 0x08
#define PKT3_CRC_OFF 0x00
// Address filtering
#define PKT3_ADRSFILT_00 0x00
#define PKT3_ADRSFILT_01 0x02
#define PKT3_ADRSFILT_10 0x04
#define PKT3_ADRSFILT_11 0x06
//CRC status (Read only)
#define PKT3_CRC_STATUS 0x01
// PKT Param 4
// FIFO autoclear if CRC failed for current packet
#define PKT4_AUTOCLEAR_ON 0x00
#define PKT4_AUTOCLEAR_OFF 0x80
// Select FIFO access in standby mode (read or write)
#define PKT4_FIFO_STANDBY_WRITE 0x00
#define PKT4_FIFO_STANDBY_READ 0x40
#define TS_OS 160 // Quartz Osc wake up time, typ 1.5 ms, max 5 ms
#define TS_FS 26 // Freq Synth wake-up time from OS, max 800 us
#define TS_RE 16 // Receiver wake-up time from FS, max 500 us
#define TS_TR 16 // Transmitter wake-up time from FS, max 500 us
#ifndef TOSH_DATA_LENGTH
#define TOSH_DATA_LENGTH 28
#endif
enum {
sx1211_mtu=TOSH_DATA_LENGTH + sizeof(sx1211_header_t) + sizeof(sx1211_footer_t),
sx1211_ack_timeout=8000,
};
typedef enum {
data_pattern = 0x893456,
ack_pattern = 0x123fed,
buf_pattern = 0xAAAAAA,
} pattern_t;
typedef enum {
rx_irq0_none=0,
rx_irq0_write_byte=1,
rx_irq0_nFifoEmpty=2,
rx_irq0_Pattern=3,
} sx1211_rx_irq0_src_t;
typedef enum sx1211_rx_irq1_src_t {
rx_irq1_none=0,
rx_irq1_FifoFull=1,
rx_irq1_Rssi=2
} sx1211_rx_irq1_src_t;
// In TX, IRQ0 is always mapped to nFifoEmpty
typedef enum {
tx_irq1_FifoFull=0,
tx_irq1_TxStopped=1
} sx1211_tx_irq1_src_t;
typedef enum {
sx1211_channelpreset_868mhz=0,
sx1211_channelpreset_869mhz=1,
sx1211_channelpreset_870mhz=2,
sx1211_channelpreset_433mhz=3,
sx1211_channelpreset_434mhz=4,
sx1211_channelpreset_435mhz=5,
} sx1211_channelpreset_t;
typedef enum {
sx1211_bitrate_152340=152340U,
sx1211_bitrate_76170=76170U,
sx1211_bitrate_50780=50780U,
sx1211_bitrate_38085=38085U,
// xe1205_bitrate_30468=30468,
// xe1205_bitrate_19042=19042,
// xe1205_bitrate_12695=12695,
// xe1205_bitrate_8017=8017,
// xe1205_bitrate_4760=4760
} sx1211_bitrate_t;
typedef enum {
reg1 = 0,
reg2 = 1,
} sx1211_regFreq_t;
typedef enum {
freq_867_075 = 0,
freq_867_225 = 1,
freq_867_375 = 2,
freq_867_524 = 3,
freq_867_674 = 4,
freq_867_825 = 5,
freq_867_975 = 6,
freq_868_126 = 7,
freq_868_275 = 8,
freq_868_424 = 9,
freq_868_575 = 10,
freq_868_725 = 11,
freq_868_875 = 12,
freq_869_025 = 13,
freq_869_175 = 14,
freq_869_324 = 15,
freq_869_474 = 16, // 500mW ISM
freq_869_625 = 17, // 500mW ISM
freq_869_777 = 18,
freq_869_924 = 19,
} sx1211_freq_t;
uint8_t const rpsPllTable[] = {
102, 81, 52, //867.075728
124, 99, 28, //867.225600
127, 101, 60, //867.375000
142, 113, 65, //867.524476
144, 115, 37, //867.674483
127, 101, 64, //867.825000
162, 130, 0, //867.975460
163, 130, 62, //868.126829
127, 101, 68, //868.275000
165, 132, 36, //868.424096
106, 85, 4, //868.575701
// 167, 134, 22,
127, 101, 72, //868.725000
126, 101, 13, //868.875591
148, 118, 67, //869.025503
127, 102, 1, //869.175000
118, 94, 59, //869.324370
120, 96, 31, //869.474380
127, 102, 5, //869.625000
166, 133, 37, //869.777246
157, 126, 20, //869.924051
};
#endif /* _SX1211CONST_H */
|
tinyos-io/tinyos-3.x-contrib | wustl/upma/chips/cc2420/PowerCycle.h | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/*
* Copyright (c) 2005-2006 Rincon Research Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Rincon Research Corporation 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 COPYRIGHT HOLDERS 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
* RINCON RESEARCH OR ITS 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
*/
/**
* @author <NAME>
*/
#ifndef POWERCYCLE_H
#define POWERCYCLE_H
/**
* The maximum number of CCA checks performed on each wakeup.
* If there are too few, the receiver may wake up between messages
* and not detect the transmitter.
*
* The on-time had to increase from the original version to allow multiple
* transmitters to co-exist. This is due to using ack's, which then requires us
* to extend the backoff period. In networks that transmit frequently, possibly
* with multiple transmitters, this power scheme makes sense.
*
* In networks that transmit very infrequently or without multiple transmitters,
* it makes more sense to go with no acks and no backoffs and make the
* receive check as short as possible.
*/
#ifndef MAX_LPL_CCA_CHECKS
#if defined(PLATFORM_TELOSB) || defined(PLATFORM_TMOTE)
#define MAX_LPL_CCA_CHECKS 400
#else
#define MAX_LPL_CCA_CHECKS 400
#endif
#endif
/**
* The minimum number of samples that must be taken in CC2420DutyCycleP
* that show the channel is not clear before a detection event is issued
*/
#ifndef MIN_SAMPLES_BEFORE_DETECT
#define MIN_SAMPLES_BEFORE_DETECT 3
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | hitdke/support/sdk/c/synsb/sds.h | // $Id: sds.h,v 1.1 2010/06/22 08:32:17 pineapple_liu Exp $
/*
* Copyright (c) 2010 Data & Knowledge Engineering Research Center,
* Harbin Institute of Technology, P. R. China.
* All rights reserved.
*/
/**
* HITDKE Synthetic DataSource (SDS) API's.
*
* @author <NAME> <<EMAIL>>
* @date Jun 22, 2010
*/
#ifndef __HITDKE_SDS_H__
#define __HITDKE_SDS_H__
#include "DataSource.h"
#endif /* __HITDKE_SDS_H__ */
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/lib/quanto/activity.h | #ifndef _ACTIVITY_H
#define _ACTIVITY_H
/* act_t has two parts: a node and an activity type. To save space,
* we are using a single, 16-bit value to store both. We'll use the
* 10 msb to store the host and the 6 lsb to store the activity.
* This will break if the node id is greater than 1024, or if the
* activity is greater than 64.
*/
typedef uint16_t act_t;
typedef uint8_t act_type_t;
enum {
ACT_INVALID = 0xFFFF,
ACT_NODE_MASK = 0x01FF,
ACT_NODE_OFF = 7,
ACT_NODE_INVALID = 0x1FF,
ACT_TYPE_MASK = 0x007F,
ACT_TYPE_OFF = 0,
ACT_TYPE_IDLE = 0,
ACT_TYPE_UNKNOWN = 0x7F,
ACT_TYPE_QUANTO = 0x7E,
ACT_TYPE_QUANTO_WRITER = 0x77,
};
#if 0
#define mk_act_local(a) ( (act_t)(TOS_NODE_ID & ACT_NODE_MASK) << ACT_NODE_OFF |\
((a) & ACT_TYPE_MASK) << ACT_TYPE_OFF )
#endif
#ifndef MIG
inline act_t mk_act_local(act_type_t a) {
return (act_t) ((TOS_NODE_ID & ACT_NODE_MASK) << ACT_NODE_OFF |
(a & ACT_TYPE_MASK));
}
inline uint8_t is_idle(act_type_t a) {
return (!(a & ACT_TYPE_MASK));
}
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/chips/cc1000_sync/CC1000Msg.h | <filename>rincon/tos/chips/cc1000_sync/CC1000Msg.h<gh_stars>1-10
#ifndef CC1K_RADIO_MSG_H
#define CC1K_RADIO_MSG_H
#include "AM.h"
typedef nx_struct CC1KHeader {
nx_am_addr_t dest;
nx_am_addr_t source;
nx_uint8_t length;
nx_am_group_t group;
nx_uint8_t dsn;
nx_am_id_t type;
} cc1000_header_t;
typedef nx_struct CC1KFooter {
nxle_uint16_t crc;
} cc1000_footer_t;
typedef nx_struct CC1KMetadata {
nx_int16_t strength_or_preamble; /* negative when used for preamble length */
nx_uint8_t ack;
nx_uint16_t time;
nx_uint8_t sendSecurityMode;
nx_uint8_t receiveSecurityMode;
nx_uint16_t rxInterval;
nx_uint16_t maxRetries;
nx_uint16_t retryDelay;
} cc1000_metadata_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | ucc/PLScheduler/tos/chips/msp430/context_switch.h | <gh_stars>1-10
#ifndef __context_switch_h__
#define __context_switch_h__
#include "TaskPriority.h"
#define GET_SP(sp) {asm volatile("mov.w r1, %0\n\t" :"=r" (sp) : ); }
#define CONTEXT_SWITCH_PREAMBLE(FROM, TO) \
{ \
asm volatile("mov.w r1, %0\n\t" \
:"=r"(contexts[FROM].sp) : ); \
\
asm volatile("mov.w %0, r1\n\t" \
:: "r"(stack_addr) ); \
\
asm volatile("push %0\n\t" \
::"r"(preemption_handler)); \
\
for(idex = 0; idex < 13; idex++) \
asm volatile("push r3\n\t"); \
\
asm volatile("mov.w r1, %0\n\t" \
:"=r"(contexts[TO].sp) : ); \
\
asm volatile("mov.w %0, r1\n\t" \
::"r"(contexts[FROM].sp) ); \
\
}
#define PUSH_CONTEXT(ID) \
{ \
asm volatile( \
"push r2\n\t" \
"dint\n\t" \
); \
asm volatile( \
"push r15\n\t" \
"push r14\n\t" \
"push r13\n\t" \
"push r12\n\t" \
"push r11\n\t" \
"push r10\n\t" \
"push r9\n\t" \
"push r8\n\t" \
"push r7\n\t" \
"push r6\n\t" \
"push r5\n\t" \
"push r4\n\t" \
); \
asm volatile( \
"mov.w r1, %0\n\t" \
:"=r"(contexts[ID].sp) : ); \
}
#define POP_CONTEXT(ID) \
{ \
asm volatile("mov.w %0, r1\n\t" \
::"r"(contexts[ID].sp)); \
\
asm volatile( \
"pop r4\n\t" \
"pop r5\n\t" \
"pop r6\n\t" \
"pop r7\n\t" \
"pop r8\n\t" \
"pop r9\n\t" \
"pop r10\n\t" \
"pop r11\n\t" \
"pop r12\n\t" \
"pop r13\n\t" \
"pop r14\n\t" \
"pop r15\n\t" \
); \
\
asm volatile("pop r2\n\t"); \
asm volatile("eint\n\t"); \
}
#define CONTEXT_DIFF 50
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/apps/turtle_snapper/impl/mica2dot/beacon.h | #ifndef BEACON_H_
#define BEACON_H_
#define BEACON_COUNT 5
#define BEACON_IVAL 600
#endif
|
tinyos-io/tinyos-3.x-contrib | stanford-sing/s4-tinyos-2.x/tos/lib/util/Logging.h | // ex: set tabstop=2 shiftwidth=2 expandtab syn=c:
// $Id: Logging.h,v 1.1 2008/10/23 22:22:41 genie1 Exp $
/*
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
* Copyright (c) 2002-2003 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/*
* Authors: <NAME>
* Date Last Modified: 2005/05/26
*/
#ifndef _NOGEO_LOG
#define _NOGEO_LOG
/*
* The logging is done in message_t packets
*
*/
#include "BVR.h"
enum {
//Constants
AM_S4_LOG_MSG = 60,
AM_BVR_LOG_MSG = 61,
SELF_LOG_INTERVAL = 60000u,
UART_LOG_INTERVAL = 60000u,
};
enum {
//Packets
LOG_SEND_BEACON = 1,
LOG_RECEIVE_BEACON = 3,
LOG_SEND_ROOT_BEACON = 2,
LOG_RECEIVE_ROOT_BEACON = 4,
LOG_SEND_LINK_INFO = 5,
LOG_RECEIVE_LINK_INFO = 6,
LOG_SEND_APP_MSG = 7,
LOG_RECEIVE_APP_MSG = 8,
//Link table
LOG_ADD_LINK = 10, //0x0A
LOG_CHANGE_LINK = 11, //0x0B
LOG_DROP_LINK = 12, //0x0C
//Neighbor table (neighbor's coordinates)
LOG_ADD_NEIGHBOR = 20, //14
LOG_CHANGE_NEIGHBOR = 21,//15
LOG_DROP_NEIGHBOR = 22, //16
//State
LOG_CHANGE_COORDS = 30, //1E
LOG_CHANGE_COORD = 31, //1F
//Routing
LOG_ROUTE_START = 39, //27
LOG_ROUTE_FAIL_STUCK_0 = 40, //28
LOG_ROUTE_FAIL_STUCK = 42, //2A
LOG_ROUTE_FAIL_BEACON = 41, //29
//LOG_ROUTE_SAME_COORDS = 42, //2A
LOG_ROUTE_SUCCESS = 43, //2B
LOG_ROUTE_FAIL_NO_LOCAL_BUFFER = 44, //2C
LOG_ROUTE_FAIL_NO_QUEUE_BUFFER = 45, //2D
LOG_ROUTE_INVALID_STATUS = 46, //2E
LOG_ROUTE_TO_SELF = 47, //2F
LOG_ROUTE_STATUS_NEXT_ROUTE = 38, //26
LOG_ROUTE_BUFFER_ERROR = 37, //25
LOG_ROUTE_SENT_NORMAL_OK = 32, //20
LOG_ROUTE_SENT_FALLBACK_OK = 33, //21
LOG_ROUTE_RECEIVED_OK = 34, //22
LOG_ROUTE_RECEIVED_DUPLICATE = 35, //23
//Logging for Scoped Flood
LOG_ROUTE_BCAST_START = 64, //40
LOG_ROUTE_STATUS_BCAST_RETRY = 65, //41
LOG_ROUTE_STATUS_BCAST_FAIL = 66, //42
LOG_ROUTE_SENT_BCAST_OK = 67, //43
LOG_ROUTE_RECEIVED_BCAST_OK = 68, //44
LOG_ROUTE_BCAST_END_SCOPE = 69, //45
LOG_ROUTE_BCAST_ERROR_TIMER_FAILED = 70, //46
LOG_ROUTE_BCAST_ERROR_TIMER_PENDING = 71, //47
//Logging self logging
LOG_LOGGER_STATS = 50, //32
LOG_UART_COMM_STATS = 51, //33
//Logging For QueuedSendM
LOG_LRX_SEND = 101,
LOG_LRX_RECEIVE = 102,
LOG_LRX_SXFER_START = 103,
LOG_LRX_SXFER_FINISH = 104,
LOG_LRX_RXFER_START = 105,
LOG_LRX_RXFER_FINISH = 106,
//Logging temporary - for debugging
LOG_DBG1 = 129, //81
LOG_DBG2 = 130, //82
LOG_DBG3 = 131, //83
//Logging for retransmit test
LOG_ROUTE_RETRANSMIT_SUCCESS = 132, //84
LOG_ROUTE_RETRANSMIT_FAIL = 133, //85
};
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t total;
} LogEntrySentDV;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t total;
} LogEntrySentBV;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t total;
} LogEntrySentData;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t total;
} LogEntryRTState;
/*Packets*/
//Send a coordinate beacon with coordinate info
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t seqno;
} LogEntrySendBeacon;
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t seqno;
nx_uint16_t from;
} LogEntryReceiveBeacon;
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t seqno;
nx_uint8_t hopcount;
} LogEntrySendRootBeacon;
typedef nx_struct {
nx_uint8_t type; //LOG_RECEIVE_ROOT_BEACON
nx_uint8_t id; //which beacon
nx_uint8_t seqno;
nx_uint8_t hopcount; //how distant
nx_uint16_t last_hop; //from
nx_uint8_t quality; //combined_quality
} LogEntryReceiveRootBeacon;
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t id; //the message id from the application data, if it makes sense
nx_uint16_t to; //next hop
nx_uint8_t mode; //fallback or not
nx_uint8_t fallback_thresh; //threshold to return to normal mode, if in fallback
Coordinates dest; //final destination
} LogEntrySendAppMsg;
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t id;
nx_uint8_t result; //whether this will be forwarded, received, or failed
} LogEntryReceiveAppMsg;
/*Events*/
typedef nx_struct {
nx_uint8_t type;
LinkNeighbor link;
} LogEntryChangeLink;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t addr;
} LogEntryDropLink;
typedef nx_struct {
nx_uint8_t type;
CoordinateTableEntry neighbor;
} LogEntryChangeNeighbor;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t addr;
} LogEntryDropNeighbor;
//Packet type: 1E
typedef nx_struct {
nx_uint8_t type;
Coordinates Coords;
CoordsParents parents;
} LogEntryUpdateCoordinates;
//Packet type: 1F
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t beacon;
nx_uint8_t hopcount;
nx_uint16_t parent;
nx_uint8_t combined_quality;
} LogEntryUpdateCoordinate;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t id;
nx_uint16_t origin_addr;
nx_uint16_t dest_addr;
nx_uint8_t hopcount;
Coordinates dest_coords;
Coordinates my_coords;
} LogEntryRouteReport;
//For link_level retransmission test
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t id;
nx_uint16_t origin_addr;
nx_uint16_t dest_addr;
nx_uint8_t hopcount;
nx_uint16_t next_hop;
nx_uint8_t retransmit_count;
} LogEntryRetransmitReport;
typedef nx_struct {
nx_uint8_t type;
nx_uint8_t free_pos;
nx_uint8_t max_queue;
nx_uint32_t stat_received; // A total requests received
nx_uint32_t stat_written; // B total successfully written
nx_uint32_t stat_no_buffer; // C total failed no buffer
nx_uint32_t stat_send_failed; // D total send failed
nx_uint32_t stat_send_done_failed; //E total send done returned fail
// A = B + C + D + E
} LogEntryLoggerStats;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t stat_receive_duplicate_no_buffer; // a
nx_uint16_t stat_receive_duplicate_send_failed; // b
nx_uint16_t stat_receive_total; // c
nx_uint16_t stat_send_duplicate_no_buffer; // d
nx_uint16_t stat_send_duplicate_send_fail; // e
nx_uint16_t stat_send_duplicate_send_done_fail; // f
nx_uint16_t stat_send_duplicate_success; // g
nx_uint16_t stat_send_duplicate_total; // h
nx_uint16_t stat_send_original_send_done_fail; // i
nx_uint16_t stat_send_original_send_failed; // j
nx_uint16_t stat_send_original_success; // k
nx_uint16_t stat_send_original_total; // l
} LogEntryUARTCommStats;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t sender;
nx_uint16_t sender_session_id;
nx_uint8_t sender_msg_id;
nx_uint16_t receiver;
nx_uint16_t receiver_session_id;
nx_uint8_t receiver_msg_id;
nx_uint8_t ctrl;
nx_uint8_t blockNum;
nx_uint8_t subCtrl;
nx_uint8_t state;
} LogEntryLRXPkt;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t sender;
nx_uint16_t receiver;
nx_uint16_t session_id;
nx_uint8_t msg_id;
nx_uint8_t numofBlock;
nx_uint8_t success;
nx_uint8_t state;
} LogEntryLRXXfer;
typedef nx_struct {
nx_uint8_t type;
nx_uint16_t arg1;
nx_uint16_t arg2;
nx_uint16_t arg3;
} LogEntryDebug;
/* This is a union with a hack: to reuse the structs above, which are all
assumed to have a first field type, I define the first field of the
union to be type, so that it can be checked invariably. */
typedef nx_union {
nx_uint8_t type;
LogEntryReceiveRootBeacon receive_root_beacon;
LogEntryDropLink drop_link;
LogEntryChangeLink add_link;
LogEntryChangeLink change_link;
LogEntryChangeNeighbor add_neighbor;
LogEntryChangeNeighbor change_neighbor;
LogEntryDropNeighbor drop_neighbor;
LogEntryUpdateCoordinates update_coordinates;
LogEntryUpdateCoordinate update_coordinate;
LogEntryRouteReport route_report;
LogEntryLoggerStats logger_stats;
LogEntryUARTCommStats UART_comm_stats;
LogEntryLRXPkt lrx_pkt;
LogEntryLRXXfer lrx_xfer;
LogEntryDebug debug;
LogEntryRetransmitReport retransmit_report;
} BVRLogMsg;
typedef nx_struct BVR_Log_Msg{
LEHeader header;
BVRLogMsg log_msg;
} BVRLogMsgWrapper;
/* This is a union with a hack: to reuse the structs above, which are all
assumed to have a first field type, I define the first field of the
union to be type, so that it can be checked invariably. */
typedef nx_union {
nx_uint8_t type;
LogEntryReceiveBeacon receive_beacon;
LogEntryReceiveRootBeacon receive_root_beacon;
LogEntryDropLink drop_link;
LogEntryChangeLink add_link;
LogEntryChangeLink change_link;
LogEntryChangeNeighbor add_neighbor;
LogEntryChangeNeighbor change_neighbor;
LogEntryDropNeighbor drop_neighbor;
LogEntryUpdateCoordinates update_coordinates;
LogEntryUpdateCoordinate update_coordinate;
LogEntryRouteReport route_report;
LogEntryLoggerStats logger_stats;
LogEntryUARTCommStats UART_comm_stats;
LogEntryLRXPkt lrx_pkt;
LogEntryLRXXfer lrx_xfer;
LogEntryDebug debug;
LogEntryRetransmitReport retransmit_report;
//added by <NAME> on Sept. 22, for more statistics logging
LogEntrySentDV sent_dv;
LogEntrySentBV sent_bv;
LogEntrySentData sent_data;
LogEntryRTState rt_state;
} S4LogMsg;
typedef nx_struct S4_Log_Msg{
LEHeader header;
S4LogMsg log_msg;
} S4LogMsgWrapper;
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/util/collect/platform.c | <reponame>tinyos-io/tinyos-3.x-contrib
#include <sys/types.h>
#include "platform.h"
uint32_t platform;
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/pgm_util.h | #ifndef _PGM_UTIL_H_
#define _PGM_UTIL_H_
#define PROGMEM
inline int32_t read_pgm_int32(int32_t* pptr)
{
//int32_t result;
//memcpy((void*)&result, pptr, sizeof(int32_t));
return (*pptr);
}
inline int16_t read_pgm_int16(int16_t* pptr)
{
//int16_t result;
//memcpy(&result, pptr, sizeof(int16_t));
//return result;
return (*pptr);
}
inline int8_t read_pgm_int8(int8_t* pptr)
{
//int8_t result;
//memcpy(&result, pptr, sizeof(int8_t));
//return result;
return (*pptr);
}
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/cip51/iocip51.h | /*
* Copyright (c) 2008 Polaric
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Polaric 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 COPYRIGHT HOLDERS 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 POLARIC OR ITS 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.
*/
/**
* @author <NAME> <<EMAIL>>
*/
#ifndef _H_iocip51_H
#define _H_iocip51_H
/*
* Bit locations for SCON
*/
enum {
cip51_SCON_S0MODE = 0x7,
cip51_SCON_MCE0 = 0x5,
cip51_SCON_REN0 = 0x4,
cip51_SCON_TB80 = 0x3,
cip51_SCON_RB80 = 0x2,
cip51_SCON_TI0 = 0x1,
cip51_SCON_RI0 = 0x0
};
/*
* Bit locations for SPI0CFG
*/
enum {
CIP51_SPI0CFG_SPIBSY = 0x7,
CIP51_SPI0CFG_MSTEN = 0x6,
CIP51_SPI0CFG_CKPHA = 0x5,
CIP51_SPI0CFG_CKPOL = 0x4,
CIP51_SPI0CFG_SLVSEL = 0x3,
CIP51_SPI0CFG_NSSIN = 0x2,
CIP51_SPI0CFG_SRMT = 0x1,
CIP51_SPI0CFG_RXBMT = 0x0
};
/*
* Bit locations for CLKMUL
*/
enum {
CIP51_CLKMUL_MULEN = 0x7,
CIP51_CLKMUL_MULINT = 0x6,
CIP51_CLKMUL_MULRDY = 0x5
};
/*
* Bit locations for IT01CF
*/
enum {
CIP51_IT01CF_IN1PL = 0x7,
CIP51_IT01CF_IN0PL = 0x3,
CIP51_IT01CF_IN0SL_MASK = 0x7,
CIP51_IT01CF_IN1SL_MASK = 0x70
};
/**
* Special Function Register (sfr) definitions
*/
uint8_t volatile OSCLCN __attribute((sfrAT0x86)); // Internal Low-Freq Oscillator Control
uint8_t volatile PSCTL __attribute((sfrAT0x8F)); // Program Store R/W Control
//uint8_t volatile P1 __attribute((sfrAT0x90)); // Port 1 Latch
uint8_t volatile TMR3CN __attribute((sfrAT0x91)); // Timer/Counter 3 Control
uint8_t volatile TMR3RLL __attribute((sfrAT0x92)); // Timer/Counter 3 Reload Low
uint8_t volatile TMR3RLH __attribute((sfrAT0x93)); // Timer/Counter 3 Reload High
uint8_t volatile TMR3L __attribute((sfrAT0x94)); // Timer/Counter 3Low
uint8_t volatile TMR3H __attribute((sfrAT0x95)); // Timer/Counter 3 High
uint8_t volatile USB0ADR __attribute((sfrAT0x96)); // USB0 Indirect Address
uint8_t volatile USB0DAT __attribute((sfrAT0x97)); // USB0 Data Register
uint8_t volatile SCON0 __attribute((sfrAT0x98)); // UART0 Control
uint8_t volatile SBUF0 __attribute((sfrAT0x99)); // UART0 Data Buffer
uint8_t volatile CPT1CN __attribute((sfrAT0x9A)); // Comparator1 Control
uint8_t volatile CPT0CN __attribute((sfrAT0x9B)); // Comparator0 Control
uint8_t volatile CPT1MD __attribute((sfrAT0x9C)); // Comparator1 Mode Selection
uint8_t volatile CPT0MD __attribute((sfrAT0x9D)); // Comparator0 Mode Selection
uint8_t volatile CPT1MX __attribute((sfrAT0x9E)); // Comparator1 MUX Selection
uint8_t volatile CPT0MX __attribute((sfrAT0x9F)); // Comparator0 MUX Selection
//uint8_t volatile P2 __attribute((sfrAT0xA0)); // Port 2 Latch
uint8_t volatile SPI0CFG __attribute((sfrAT0xA1)); // SPI Configuration
uint8_t volatile SPI0CKR __attribute((sfrAT0xA2)); // SPI Clock Rate Control
uint8_t volatile SPI0DAT __attribute((sfrAT0xA3)); // SPI Data
uint8_t volatile P0MDOUT __attribute((sfrAT0xA4)); // Port 0 Output Mode Config
uint8_t volatile P1MDOUT __attribute((sfrAT0xA5)); // Port 1 Output Mode Configuration
uint8_t volatile P2MDOUT __attribute((sfrAT0xA6)); // Port 2 Output Mode Configuration
uint8_t volatile P3MDOUT __attribute((sfrAT0xA7)); // Port 3 Output Mode Configuration
uint8_t volatile IE __attribute((sfrAT0xA8)); // Interrupt Enable
uint8_t volatile CLKSEL __attribute((sfrAT0xA9)); // Clock Select
uint8_t volatile EMI0CN __attribute((sfrAT0xAA)); // External Memory Interface Control
uint8_t volatile SBCON1 __attribute((sfrAT0xAC)); // UART1 Baud Rate Generator Control
uint8_t volatile P4MDOUT __attribute((sfrAT0xAE)); // Port 4 Output Mode Configuration
uint8_t volatile PFE0CN __attribute((sfrAT0xAF)); // Prefetch Engine Control
uint8_t volatile P3 __attribute((sfrAT0xB0)); // Port 4 Input Mode Config
uint8_t volatile OSCXCN __attribute((sfrAT0xB1)); //External Oscillator Control
uint8_t volatile OSCICN __attribute((sfrAT0xB2)); //Internal Oscillator Control
uint8_t volatile OSCICL __attribute((sfrAT0xB3)); //Internal Oscillator Calibration
uint8_t volatile SBRLL1 __attribute((sfrAT0xB4)); //UART1 Baud Rate Generator Low
uint8_t volatile SBRLH1 __attribute((sfrAT0xB5)); //UART1 Baud Rate Generator High
uint8_t volatile FLSCL __attribute((sfrAT0xB6)); //Flash Scale
uint8_t volatile FLKEY __attribute((sfrAT0xB7)); //Flash Lock and Key
uint8_t volatile IP __attribute((sfrAT0xB8)); //Interrupt Priority
uint8_t volatile CLKMUL __attribute((sfrAT0xB9)); //Clock Multiplier
uint8_t volatile AMX0N __attribute((sfrAT0xBA)); //AMUX0 Negative Channel Select
uint8_t volatile AMX0P __attribute((sfrAT0xBB)); //AMUX0 Positive Channel Select
uint8_t volatile ADC0CF __attribute((sfrAT0xBC)); //ADC0 Configuration
uint8_t volatile ADC0L __attribute((sfrAT0xBD)); //ADC0 Low
uint8_t volatile ADC0H __attribute((sfrAT0xBE)); //ADC0 High
uint8_t volatile SMB0CN __attribute((sfrAT0xC0)); //SMBus Control
uint8_t volatile SMB0CF __attribute((sfrAT0xC1)); //SMBus Configuration
uint8_t volatile SMB0DA __attribute((sfrAT0xC2)); //SMBus Data
uint8_t volatile ADC0GT __attribute((sfrAT0xC3)); //ADC0 Greater-Than Compare Low
uint8_t volatile ADC0GT __attribute((sfrAT0xC4)); //ADC0 Greater-Than Compare High
uint8_t volatile ADC0LT __attribute((sfrAT0xC5)); //ADC0 Less-Than Compare Word Low
uint8_t volatile ADC0LT __attribute((sfrAT0xC6)); //ADC0 Less-Than Compare Word High
uint8_t volatile P4 __attribute((sfrAT0xC7)); //Port 4 Latch
uint8_t volatile TMR2CN __attribute((sfrAT0xC8)); //Timer/Counter 2 Control
uint8_t volatile REG0CN __attribute((sfrAT0xC9)); //Voltage Regulator Control
uint8_t volatile TMR2RL __attribute((sfrAT0xCA)); //Timer/Counter 2 Reload Low
uint8_t volatile TMR2RL __attribute((sfrAT0xCB)); //Timer/Counter 2 Reload High
uint8_t volatile TMR2L __attribute((sfrAT0xCC)); //Timer/Counter 2 Low
uint8_t volatile TMR2H __attribute((sfrAT0xCD)); //Timer/Counter 2 High
uint8_t volatile PSW __attribute((sfrAT0xD0)); //Program Status Word
uint8_t volatile REF0CN __attribute((sfrAT0xD1)); //Voltage Reference Control
uint8_t volatile SCON1 __attribute((sfrAT0xD2)); //UART1 Control
uint8_t volatile SBUF1 __attribute((sfrAT0xD3)); //UART1 Data Buffer
uint8_t volatile P0SKIP __attribute((sfrAT0xD4)); //Port 0 Skip
uint8_t volatile P1SKIP __attribute((sfrAT0xD5)); //Port 1 Skip
uint8_t volatile P2SKIP __attribute((sfrAT0xD6)); //Port 2 Skip
uint8_t volatile USB0XCN __attribute((sfrAT0xD7)); //USB0 Transceiver Control
uint8_t volatile PCA0CN __attribute((sfrAT0xD8)); //PCA Control
uint8_t volatile PCA0MD __attribute((sfrAT0xD9)); //PCA Mode
uint8_t volatile P3SKIP __attribute((sfrAT0xDF)); // Port 2 Skip
uint8_t volatile XBR0 __attribute((sfrAT0xE1));
uint8_t volatile XBR1 __attribute((sfrAT0xE2));
uint8_t volatile XBR2 __attribute((sfrAT0xE3));
uint8_t volatile IT01CF __attribute((sfrAT0xE4)); // INT0/INT1 Configuration
uint8_t volatile SMOD1 __attribute((sfrAT0xE5)); // UART1 Mode
uint8_t volatile EIE1 __attribute((sfrAT0xE6)); // Extended Interrupt Enable 1
uint8_t volatile EIE2 __attribute((sfrAT0xE7)); // Extended Interrupt Enable 2
uint8_t volatile ADC0CN __attribute((sfrAT0xE8)); // ADC0 Control
uint8_t volatile PCA0CPL1 __attribute((sfrAT0xE9)); // PCA0 Capture 1 Low
uint8_t volatile PCA0CPH1 __attribute((sfrAT0xEA)); // PCA0 Capture 1 High
uint8_t volatile PCA0CPL2 __attribute((sfrAT0xEB)); // PCA0 Capture 2 Low
uint8_t volatile PCA0CPH2 __attribute((sfrAT0xEC)); // PCA0 Capture 2 High
uint8_t volatile PCA0CPL3 __attribute((sfrAT0xED)); // PCA0 Capture 3 Low
uint8_t volatile PCA0CPH3 __attribute((sfrAT0xEE)); // PCA0 Capture 3 High
uint8_t volatile RSTSRC __attribute((sfrAT0xEF)); // Reset Source Configuration/Status
uint8_t volatile B __attribute((sfrAT0xF0)); // B Register
uint8_t volatile P0MDIN __attribute((sfrAT0xF1)); // Port 0 Input Mode Config
uint8_t volatile P1MDIN __attribute((sfrAT0xF2)); // Port 1 Input Mode Config
uint8_t volatile P2MDIN __attribute((sfrAT0xF3)); // Port 2 Input Mode Config
uint8_t volatile P3MDIN __attribute((sfrAT0xF4)); // Port 4 Input Mode Config
uint8_t volatile P4MDIN __attribute((sfrAT0xF5)); // Port 4 Input Mode Config
uint8_t volatile EIP1 __attribute((sfrAT0xF6)); // Extended Interrupt Priority 1
uint8_t volatile EIP2 __attribute((sfrAT0xF7)); // Extended Interrupt Priority 2
uint8_t volatile SPI0CN __attribute((sfrAT0xF8)); // SPI0 Control
uint8_t volatile PCA0L __attribute((sfrAT0xF9)); // PCA0 Counter Low
uint8_t volatile PCA0H __attribute((sfrAT0xFA)); // PCA0 Counter High
uint8_t volatile PCA0CPL0 __attribute((sfrAT0xFB)); // PCA0 Capture 0 Low
uint8_t volatile PCA0CPH0 __attribute((sfrAT0xFC)); // PCA0 Capture 0 High
uint8_t volatile PCA0CPL4 __attribute((sfrAT0xFD)); // PCA0 Capture 4 Low
uint8_t volatile PCA0CPH4 __attribute((sfrAT0xFE)); // PCA0 Capture 4 High
uint8_t volatile VDM0CN __attribute((sfrAT0xFF)); // VDD Monitor Control
/**
* Bit adresseable locations
*/
// SCON0 0x98
uint8_t volatile S0MODE __attribute((sbitAT0x9F)); // Serial mode control bit 0
uint8_t volatile MCE0 __attribute((sbitAT0x9E)); // Multiprocessor communication enable
uint8_t volatile REN0 __attribute((sbitAT0x9C)); // Receive enable
uint8_t volatile TB80 __attribute((sbitAT0x9B)); // Transmit bit 8
uint8_t volatile RB80 __attribute((sbitAT0x9A)); // Receive bit 8
uint8_t volatile TI0 __attribute((sbitAT0x99)); // Transmit interrupt flag
uint8_t volatile RI0 __attribute((sbitAT0x98)); // Receive interrupt flag
// IE 0xA8
//uint8_t volatile EA __attribute((sbitAT0xAF)); // Global interrupt enable
uint8_t volatile ESPI0 __attribute((sbitAT0xAE)); // SPI0 interrupt enable
uint8_t volatile ET2 __attribute((sbitAT0xAD)); // Timer2 interrupt enable
uint8_t volatile ES0 __attribute((sbitAT0xAC)); // UART0 interrupt enable
uint8_t volatile ET1 __attribute((sbitAT0xAB)); // Timer1 interrupt enable
uint8_t volatile EX1 __attribute((sbitAT0xAA)); // External interrupt 1 enable
uint8_t volatile ET0 __attribute((sbitAT0xA9)); // Timer0 interrupt enable
uint8_t volatile EX0 __attribute((sbitAT0xA8)); // External interrupt 0 enable
/* P3 (0xB0) bit adressable locations */
uint8_t volatile P3_0 __attribute((sbitAT0xB0));
uint8_t volatile P3_1 __attribute((sbitAT0xB1));
uint8_t volatile P3_2 __attribute((sbitAT0xB2));
uint8_t volatile P3_3 __attribute((sbitAT0xB3));
uint8_t volatile P3_4 __attribute((sbitAT0xB4));
uint8_t volatile P3_5 __attribute((sbitAT0xB5));
uint8_t volatile P3_6 __attribute((sbitAT0xB6));
uint8_t volatile P3_7 __attribute((sbitAT0xB7));
/* SPICN (0xF8) bit adressable locations */
uint8_t volatile SPIF __attribute((sbitAT0xFF)); // SPI0 interrupt flag
uint8_t volatile WCOL __attribute((sbitAT0xFE)); // SPI0 write collision flag
uint8_t volatile MODF __attribute((sbitAT0xFD)); // SPI0 mode fault flag
uint8_t volatile RXOVRN __attribute((sbitAT0xFC)); // SPI0 rx overrun flag
uint8_t volatile NSSMD1 __attribute((sbitAT0xFB)); // SPI0 slave select mode 1
uint8_t volatile NSSMD0 __attribute((sbitAT0xFA)); // SPI0 slave select mode 0
uint8_t volatile TXBMT __attribute((sbitAT0xF9)); // SPI0 transmit buffer empty
uint8_t volatile SPIEN __attribute((sbitAT0xF8)); // SPI0 SPI enable
/* Interrupt vector definitions */
#define SIG_INT0 __vector_0 // External Interrupt 0
#define SIG_TIMER0 __vector_1 // Timer0 Overflow
#define SIG_INT1 __vector_2 // External Interrupt 1
#define SIG_TIMER1 __vector_3 // Timer1 Overflow
#define SIG_UART0 __vector_4 // Serial Port 0
#define SIG_TIMER2 __vector_5 // Timer2 Overflow
#define SIG_SPI0 __vector_6 // Serial Peripheral Interface 0
#define SIG_SMBUS0 __vector_7 // SMBus0 Interface
#define SIG_USB0 __vector_8 // USB Interface
#define SIG_ADC0_WINDOW __vector_9 // ADC0 Window Comparison
#define SIG_ADC0_EOC __vector_10 // ADC0 End Of Conversion
#define SIG_PCA0 __vector_11 // PCA0 Peripheral
#define SIG_COMPARATOR0 __vector_12 // Comparator0
#define SIG_COMPARATOR1 __vector_13 // Comparator1
#define SIG_TIMER3 __vector_14 // Timer3 Overflow
#define SIG_VBUS_LEVEL __vector_15 // VBUS level-triggered interrupt
#define SIG_UART1 __vector_16 // Serial Port 1
#endif //_H_iocip51_H
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/ewmapredictor.h | <gh_stars>1-10
#ifndef ENERGYPREDICTOR_H
#define ENERGYPREDICTOR_H
#include "simulator.h"
#include "nodes.h"
using namespace std;
#ifndef EP_WINDOW
#define EP_WINDOW 24
#endif
#ifndef EP_SCALE
#define EP_SCALE 60
#endif
#ifndef EP_FILTER_WT
#define EP_FILTER_WT 25
#endif
int64_t start_energy;
int64_t min_time;
int64_t ep_last_prediction;
int64_t ep_cur_prediction;
int64_t ep_last_error;
int64_t last_day[EP_WINDOW];
int64_t ep_prediction[EP_WINDOW];
int64_t ep_start_epoch;
int64_t ep_energy_counter;
int ep_cur_idx;
void init_energy_predictor()
{
int i;
ep_start_epoch = 0;
ep_energy_counter = 0;
ep_cur_prediction = 0;
ep_cur_idx = 0;
for (i=0; i < EP_WINDOW; i++)
{
last_day[i] = 0;
ep_prediction[i] = 0;
}
}
void ep_more_energy(int64_t energy, int64_t timestamp)
{
int64_t diff = timestamp - ep_start_epoch;
if (diff > (EP_SCALE * 60 * 1000))
{
ep_prediction[ep_cur_idx] = ((ep_energy_counter * EP_FILTER_WT) + (ep_prediction[ep_cur_idx] * (100-EP_FILTER_WT)))/100;
ep_energy_counter = 0;
ep_start_epoch = ep_start_epoch + (EP_SCALE * 60 * 1000);
ep_cur_idx = (ep_cur_idx + 1) % EP_WINDOW;
printf("ep(%lld)\n",ep_prediction[ep_cur_idx]);
}
ep_energy_counter += energy;
}
int64_t predict_energy(vector<event_t*>* timeline,
int64_t current_index,
int64_t hours)
{
int64_t result;
double confidence;
int16_t i;
int idx = ep_cur_idx;
/*if (ep_last_error < ep_cur_prediction)
{
confidence =1.0 - ((double)ep_last_error / (double)ep_cur_prediction);
} else {
confidence = 0;
}*/
result = 0;
for (i=0; i < hours; i++)
{
result += ep_prediction[idx];
idx = (idx + 1) % EP_WINDOW;
}
//result = (int64_t)(confidence * (double)((ep_cur_prediction / 24) * hours));
return result;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/runtime/tinyos2/userstructs.h | #ifndef USERSTRUCTS_H_
#define USERSTRUCTS_H_
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/daq/pci1202_lib.c | // For open
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
// For close and usleep
#include <unistd.h>
// For ioctl
#include <sys/ioctl.h>
// For pci1202 ioctls
#include <ixpci.h>
#include "daq_lib.h"
int daq_open(const char* dev_file, daq_card_t *daq)
{
int fd;
fd = open(dev_file, O_RDWR);
if (fd >= 0) {
daq_reset(&fd);
*daq = fd;
return 0;
}
return fd;
}
int daq_close(const daq_card_t *daq)
{
return close(*daq);
}
int daq_reset(const daq_card_t *daq)
{
int err = ioctl(*daq, IXPCI_RESET);
return err;
}
int daq_config_channel(const daq_card_t *daq,
int channel, daq_gain_t gain, daq_range_t range)
{
int res, settle_time = daq_settle_time(gain, range);
if (settle_time > 0) {
res = daq_config_channel_nowait(daq, channel, gain, range);
if (res)
return res;
res = daq_wait_usec(daq, settle_time);
return res;
}
return -1;
}
const int CONTROL_KEEP_FIFO = 0x8000;
const int CONTROL_HANDSHAKE = 0x2000;
const int CONTROL_COMMAND_RESET = 0x0000;
const int CONTROL_COMMAND_SET_GAIN = 0x0400;
const int CONTROL_COMMAND_ADD_QUEUE = 0x1000;
const int CONTROL_COMMAND_START_MAGIC_SCAN = 0x1400;
const int CONTROL_COMMAND_STOP_MAGIC_SCAN = 0x0800;
const int CONTROL_COMMAND_GET_ODM_NUMBER = 0x1800;
const int CONTROL_PIC_RECOVERY = 0xFFFF;
const int STATUS_NOT_FIFO_HALF_FULL = 0x80;
const int STATUS_NOT_FIFO_FULL = 0x40;
const int STATUS_NOT_FIFO_EMPTY = 0x20;
const int STATUS_NOT_ADC_BUSY = 0x10;
const int STATUS_EXTERNAL_TRIGGER = 0x08;
const int STATUS_HANDSHAKE = 0x04;
const int STATUS_ODM_INDICATOR = 0x02;
const int STATUS_NOT_TIMER_START = 0x01;
static int do_set_config(const daq_card_t *daq, int config)
{
return ioctl(*daq, IXPCI_PIC_CONTROL, config);
}
static inline int encode_cgr(int channel, daq_gain_t gain, daq_range_t range)
{
int config = 0;
/* The numbers in these two switches are taken from the Users manual
page 38/39 */
switch (gain) {
case DG_1000:
config |= 0xC0;
break;
case DG_100:
config |= 0x80;
break;
case DG_10:
config |= 0x40;
break;
case DG_1:
config |= 0;
break;
default:
return -1;
}
switch (range) {
case DR_BIPOL5V:
config |= 0x0000;
break;
case DR_BIPOL10V:
config |= 0x0100;
break;
case DR_UNIPOL5V:
config |= 0x0300;
break;
case DR_UNIPOL10V:
config |= 0x0200;
break;
default:
return -2;
}
if (channel > 31 || channel < 0)
return -3;
return config | channel;
}
int daq_config_channel_nowait(const daq_card_t *daq,
int channel, daq_gain_t gain, daq_range_t range)
{
int channel_config = encode_cgr(channel, gain, range);
/* Now channel_config contains what we want */
return do_set_config(daq, channel_config | CONTROL_KEEP_FIFO
| CONTROL_COMMAND_SET_GAIN);
}
int daq_settle_time(daq_gain_t gain, daq_range_t range)
{
/* From the users manual (page 39), it can be seen that the
settlement time only is dependent of the gain */
switch (gain) {
case DG_1000:
return 1300;
case DG_100:
return 140;
case DG_10:
return 28;
case DG_1:
return 23;
}
return 0;
}
int daq_wait_usec(const daq_card_t *daq, unsigned int usec)
{
usleep(usec);
return 0;
}
static int clear_fifo(const daq_card_t *daq)
{
ixpci_reg_t reg;
int res;
reg.id = IXPCI_CR;
reg.value = CONTROL_HANDSHAKE; /* Clear the FIFO */
if ((res = ioctl(*daq, IXPCI_WRITE_REG, ®)))
return res;
reg.value = CONTROL_KEEP_FIFO | CONTROL_HANDSHAKE;
if ((res = ioctl(*daq, IXPCI_WRITE_REG, ®)))
return res;
return 0;
}
int daq_get_sample(const daq_card_t *daq, uint16_t *sample)
{
ixpci_reg_t reg;
int res;
if ((res = clear_fifo(daq)))
return res;
/* Write to the software trigger */
reg.id = IXPCI_ADST;
reg.value = 0xFFFF;
if ((res = ioctl(*daq, IXPCI_WRITE_REG, ®)))
return res;
/* Wait until the STATUS_NOT_FIFO_EMPTY flag is set. */
reg.id = IXPCI_SR;
do {
if ((res = ioctl(*daq, IXPCI_READ_REG, ®)))
return res;
} while (!(reg.value & STATUS_NOT_FIFO_EMPTY));
/* Now we have a value in the FIFO. Read it! */
reg.id = IXPCI_AD;
if ((res = ioctl(*daq, IXPCI_READ_REG, ®)))
return res;
*sample = reg.value;
return 0;
}
static int enable_timer0(const daq_card_t *daq, int divv)
{
ixpci_reg_t reg;
int res;
reg.id = IXPCI_8254CR;
reg.value = 0x34; // Magic value!!!
if ((res = ioctl(*daq, IXPCI_WRITE_REG, ®)))
return res;
reg.id = IXPCI_8254C0;
reg.value = divv & 0xFF; // Lower 8 bits
if ((res = ioctl(*daq, IXPCI_WRITE_REG, ®)))
return res;
reg.value = (divv >> 8) & 0xFF; // Higher 8 bits
if ((res = ioctl(*daq, IXPCI_WRITE_REG, ®)))
return res;
return 0;
}
static int disable_timer0(const daq_card_t *daq)
{
return enable_timer0(daq, 0x0001);
}
int daq_clear_scan(const daq_card_t *daq)
{
int res;
if ((res = disable_timer0(daq)))
return res;
return do_set_config(daq, CONTROL_KEEP_FIFO | CONTROL_COMMAND_RESET);
}
int daq_add_scan(const daq_card_t *daq, int channel, daq_gain_t gain,
daq_range_t range)
{
int command = encode_cgr(channel, gain, range);
return do_set_config(daq, command | CONTROL_KEEP_FIFO
| CONTROL_COMMAND_ADD_QUEUE);
}
int daq_start_scan(const daq_card_t *daq, int sample_rate)
{
int res;
if ((res = do_set_config(daq, CONTROL_KEEP_FIFO
| CONTROL_COMMAND_START_MAGIC_SCAN)))
return res;
if ((res = clear_fifo(daq)))
return res;
if ((res = enable_timer0(daq, sample_rate)))
return res;
return 0;
}
int daq_stop_scan(const daq_card_t *daq)
{
return disable_timer0(daq);
}
int daq_get_scan_sample(const daq_card_t *daq, uint16_t *sample)
{
ixpci_reg_t reg;
int res;
reg.id = IXPCI_SR;
do {
if ((res = ioctl(*daq, IXPCI_READ_REG, ®)))
return res;
} while (!(reg.value & STATUS_NOT_FIFO_EMPTY));
if (!(reg.value & STATUS_NOT_FIFO_FULL))
return -1;
reg.id = IXPCI_AD;
if ((res = ioctl(*daq, IXPCI_READ_REG, ®)))
return res;
*sample = reg.value;
return 0;
}
double daq_convert_result(const daq_card_t *daq, uint16_t sample,
daq_gain_t gain, daq_range_t range)
{
int zero;
int max;
double divisor;
switch (range) {
case DR_BIPOL5V:
zero = 2048;
max = 10;
break;
case DR_BIPOL10V:
zero = 2048;
max = 20;
break;
case DR_UNIPOL5V:
zero = 0;
max = 5;
break;
case DR_UNIPOL10V:
zero = 0;
max = 10;
break;
}
switch (gain) {
case DG_1000:
divisor = 4096000.0;
break;
case DG_100:
divisor = 409600.0;
break;
case DG_10:
divisor = 40960.0;
break;
case DG_1:
divisor = 4096.0;
break;
}
return (((int)sample - zero) * max) / divisor;
}
|
tinyos-io/tinyos-3.x-contrib | marionette/tos/lib/RamSymbols/RamSymbols.h | //$Id: RamSymbols.h,v 1.1 2008/03/03 19:50:40 okola Exp $
/* tab:4
* "Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
/**
* @author <NAME>
*/
enum{
MAX_RAM_SYMBOL_SIZE = 13- sizeof(unsigned int)-sizeof(uint8_t)-sizeof(bool)
};
typedef struct ramSymbol_t {
unsigned int memAddress;
uint8_t length;
bool dereference;
uint8_t data[MAX_RAM_SYMBOL_SIZE];
} __attribute__ ((packed)) ramSymbol_t;
|
tinyos-io/tinyos-3.x-contrib | diku/common/tools/compression/passthru/passthru_comp.c | /**************************************************************************
*
* passthru_comp.c
*
* The passthru compression algorith. This will simply store the
* results from the digital acceleromter as 3 times 12 bits.
*
* This file is licensed under the GNU GPL.
*
* (C) 2005, <NAME> <<EMAIL>>
*
*/
#include "../compressor.h"
#include "../buffer.h"
#include <string.h>
int first = 1;
void compress_sample(int16_t digi_x, int16_t digi_y, int16_t digi_z,
uint16_t ana_x, uint16_t ana_y)
{
if (first) {
reset_buffer();
first = 0;
}
if (bits_left() < 3 * 12) {
handle_full_buffer(get_buffer(), bits_left()/(uint8_t)8);
reset_buffer();
}
write_bits((digi_x >> 8) & 0x0F, 4);
write_bits(digi_x & 0xFF, 8);
write_bits((digi_y >> 8) & 0x0F, 4);
write_bits(digi_y & 0xFF, 8);
write_bits((digi_z >> 8) & 0x0F, 4);
write_bits(digi_z & 0xFF, 8);
}
void flush()
{
uint8_t *tmp = get_unwritten();
memset(tmp, 0, MEMBUFSIZE - (tmp - get_buffer()));
handle_full_buffer(get_buffer(), bits_left()/(uint8_t)8);
first = 1;
}
|
tinyos-io/tinyos-3.x-contrib | yuceg/tos/chips/atm128/context_switch.h | #ifndef __context_switch_h__
#define __context_switch_h__
/*
* Copyright (c) 2006, Cleveland State University
* All rights reserved.
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * 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.
* * Neither the name of Cleveland State University 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 COPYRIGHT HOLDERS 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 COPYRIGHT HOLDERS AND 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.
*/
/*
* Author: <NAME>
* Last modified: Nov 15, 2006
*/
// ---------------
// Summary: This file contains AVR platform-specific routines for TinyThread.
// ---------------
//short int * sp = 0;
//short int * original = 0;
//Push General Purpose Registers
#define PUSH_GPR() \
__asm__("push r0"); \
__asm__("push r1"); \
__asm__("push r2"); \
__asm__("push r3"); \
__asm__("push r4"); \
__asm__("push r5"); \
__asm__("push r6"); \
__asm__("push r7"); \
__asm__("push r8"); \
__asm__("push r9"); \
__asm__("push r10"); \
__asm__("push r11"); \
__asm__("push r12"); \
__asm__("push r13"); \
__asm__("push r14"); \
__asm__("push r15"); \
__asm__("push r16"); \
__asm__("push r17"); \
__asm__("push r18"); \
__asm__("push r19"); \
__asm__("push r20"); \
__asm__("push r21"); \
__asm__("push r22"); \
__asm__("push r23"); \
__asm__("push r24"); \
__asm__("push r25"); \
__asm__("push r26"); \
__asm__("push r27"); \
__asm__("push r28"); \
__asm__("push r29"); \
__asm__("push r30"); \
__asm__("push r31")
#define PUSH_PC() \
__asm__("push r0")
#define PUSH_STATUS() \
__asm__("push r31"); \
__asm__("in r31,__SREG__"); \
__asm__("push r31")
#define POP_PC() \
__asm__("pop r0")
#define POP_STATUS() \
__asm__("pop r31"); \
__asm__("out __SREG__,r31");\
__asm__("pop r31")
//Pop the general purpose registers
#define POP_GPR() \
__asm__("pop r31"); \
__asm__("pop r30"); \
__asm__("pop r29"); \
__asm__("pop r28"); \
__asm__("pop r27"); \
__asm__("pop r26"); \
__asm__("pop r25"); \
__asm__("pop r24"); \
__asm__("pop r23"); \
__asm__("pop r22"); \
__asm__("pop r21"); \
__asm__("pop r20"); \
__asm__("pop r19"); \
__asm__("pop r18"); \
__asm__("pop r17"); \
__asm__("pop r16"); \
__asm__("pop r15"); \
__asm__("pop r14"); \
__asm__("pop r13"); \
__asm__("pop r12"); \
__asm__("pop r11"); \
__asm__("pop r10"); \
__asm__("pop r9"); \
__asm__("pop r8"); \
__asm__("pop r7"); \
__asm__("pop r6"); \
__asm__("pop r5"); \
__asm__("pop r4"); \
__asm__("pop r3"); \
__asm__("pop r2"); \
__asm__("pop r1"); \
__asm__("pop r0")
/* __asm__("pop r1"); \
__asm__("pop r0")
*/
#define SWAP_STACK_PTR(OLD, NEW) \
__asm__("in %A0, __SP_L__\n\t in %B0, __SP_H__":"=r"(OLD):);\
__asm__("out __SP_H__,%B0\n\t out __SP_L__,%A0"::"r"(NEW))
#define PREPARE_STACK() \
SWAP_STACK_PTR(sys_sp,j_list[id].sp); \
__asm__("push %A0\n push %B0"::"r"(job_wrapper));\
for(i=0;i<34;i++) \
__asm__("push __zero_reg__"); \
SWAP_STACK_PTR(j_list[id].sp, sys_sp)
#endif
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/sim_mac.c | <filename>tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/sim_mac.c
/*
* "Copyright (c) 2005 Stanford University. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
* HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS."
*/
/**
*
* This file is where you change which MAC and radio models TOSSIM
* incorporates.
*
* @author <NAME>
* @date Dec 10 2005
*/
#include <sim_csma.c>
#include <sim_gain.c>
//Added by <NAME>
#include <randomlib.c>
#include <sim_noise.c>
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/transfer.c | /* LIBUSB-WIN32, Generic Windows USB Library
* Copyright (c) 2002-2005 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "libusb_driver.h"
typedef struct {
URB *urb;
int sequence;
} context_t;
static int sequence = 0;
NTSTATUS DDKAPI transfer_complete(DEVICE_OBJECT *device_object,
IRP *irp, void *context);
static NTSTATUS create_urb(libusb_device_t *dev, URB **urb, int direction,
int urb_function, int endpoint, int packet_size,
MDL *buffer, int size);
NTSTATUS transfer(libusb_device_t *dev, IRP *irp,
int direction, int urb_function, int endpoint,
int packet_size, MDL *buffer, int size)
{
IO_STACK_LOCATION *stack_location = NULL;
context_t *context;
NTSTATUS status = STATUS_SUCCESS;
DEBUG_PRINT_NL();
if(urb_function == URB_FUNCTION_ISOCH_TRANSFER)
DEBUG_MESSAGE("transfer(): isochronous transfer");
else
DEBUG_MESSAGE("transfer(): bulk or interrupt transfer");
if(direction == USBD_TRANSFER_DIRECTION_IN)
DEBUG_MESSAGE("transfer(): direction in");
else
DEBUG_MESSAGE("transfer(): direction out");
DEBUG_MESSAGE("transfer(): endpoint 0x%02x", endpoint);
if(urb_function == URB_FUNCTION_ISOCH_TRANSFER)
DEBUG_MESSAGE("transfer(): packet_size 0x%x", packet_size);
DEBUG_MESSAGE("transfer(): size %d", size);
DEBUG_MESSAGE("transfer(): sequence %d", sequence);
DEBUG_PRINT_NL();
if(!dev->config.value)
{
DEBUG_ERROR("transfer(): invalid configuration 0");
remove_lock_release(dev);
return complete_irp(irp, STATUS_INVALID_DEVICE_STATE, 0);
}
context = ExAllocatePool(NonPagedPool, sizeof(context_t));
if(!context)
{
remove_lock_release(dev);
return complete_irp(irp, STATUS_NO_MEMORY, 0);
}
status = create_urb(dev, &context->urb, direction, urb_function,
endpoint, packet_size, buffer, size);
if(!NT_SUCCESS(status))
{
ExFreePool(context);
remove_lock_release(dev);
return complete_irp(irp, status, 0);
}
context->sequence = sequence++;
stack_location = IoGetNextIrpStackLocation(irp);
stack_location->MajorFunction = IRP_MJ_INTERNAL_DEVICE_CONTROL;
stack_location->Parameters.Others.Argument1 = context->urb;
stack_location->Parameters.DeviceIoControl.IoControlCode
= IOCTL_INTERNAL_USB_SUBMIT_URB;
IoSetCompletionRoutine(irp, transfer_complete, context,
TRUE, TRUE, TRUE);
return IoCallDriver(dev->target_device, irp);
}
NTSTATUS DDKAPI transfer_complete(DEVICE_OBJECT *device_object, IRP *irp,
void *context)
{
context_t *c = (context_t *)context;
int transmitted = 0;
libusb_device_t *dev = device_object->DeviceExtension;
if(irp->PendingReturned)
{
IoMarkIrpPending(irp);
}
if(NT_SUCCESS(irp->IoStatus.Status)
&& USBD_SUCCESS(c->urb->UrbHeader.Status))
{
if(c->urb->UrbHeader.Function == URB_FUNCTION_ISOCH_TRANSFER)
{
transmitted = c->urb->UrbIsochronousTransfer.TransferBufferLength;
}
if(c->urb->UrbHeader.Function == URB_FUNCTION_BULK_OR_INTERRUPT_TRANSFER)
{
transmitted
= c->urb->UrbBulkOrInterruptTransfer.TransferBufferLength;
}
DEBUG_MESSAGE("transfer_complete(): sequence %d: %d bytes transmitted",
c->sequence, transmitted);
}
else
{
if(irp->IoStatus.Status == STATUS_CANCELLED)
{
DEBUG_ERROR("transfer_complete(): sequence %d: timeout error",
c->sequence);
}
else
{
DEBUG_ERROR("transfer_complete(): sequence %d: transfer failed: "
"status: 0x%x, urb-status: 0x%x",
c->sequence, irp->IoStatus.Status,
c->urb->UrbHeader.Status);
}
}
ExFreePool(c->urb);
ExFreePool(c);
irp->IoStatus.Information = transmitted;
remove_lock_release(dev);
return STATUS_SUCCESS;
}
static NTSTATUS create_urb(libusb_device_t *dev, URB **urb, int direction,
int urb_function, int endpoint, int packet_size,
MDL *buffer, int size)
{
USBD_PIPE_HANDLE pipe_handle = NULL;
int num_packets = 0;
int i, urb_size;
*urb = NULL;
if(!get_pipe_handle(dev, endpoint, &pipe_handle))
{
DEBUG_ERROR("create_urb(): getting endpoint pipe failed");
return STATUS_INVALID_PARAMETER;
}
/* isochronous transfer */
if(urb_function == URB_FUNCTION_ISOCH_TRANSFER)
{
num_packets = (size + packet_size - 1) / packet_size;
if(num_packets > 255)
{
DEBUG_ERROR("create_urb(): transfer size too large");
return STATUS_INVALID_PARAMETER;
}
urb_size = sizeof(struct _URB_ISOCH_TRANSFER)
+ sizeof(USBD_ISO_PACKET_DESCRIPTOR) * num_packets;
}
else /* bulk or interrupt transfer */
{
urb_size = sizeof(struct _URB_BULK_OR_INTERRUPT_TRANSFER);
}
*urb = ExAllocatePool(NonPagedPool, urb_size);
if(!*urb)
{
DEBUG_ERROR("create_urb(): memory allocation error");
return STATUS_NO_MEMORY;
}
memset(*urb, 0, urb_size);
(*urb)->UrbHeader.Length = (USHORT)urb_size;
(*urb)->UrbHeader.Function = (USHORT)urb_function;
/* isochronous transfer */
if(urb_function == URB_FUNCTION_ISOCH_TRANSFER)
{
(*urb)->UrbIsochronousTransfer.PipeHandle = pipe_handle;
(*urb)->UrbIsochronousTransfer.TransferFlags
= direction | USBD_SHORT_TRANSFER_OK | USBD_START_ISO_TRANSFER_ASAP;
(*urb)->UrbIsochronousTransfer.TransferBufferLength = size;
(*urb)->UrbIsochronousTransfer.TransferBufferMDL = buffer;
(*urb)->UrbIsochronousTransfer.NumberOfPackets = num_packets;
for(i = 0; i < num_packets; i++)
{
(*urb)->UrbIsochronousTransfer.IsoPacket[i].Offset = i * packet_size;
(*urb)->UrbIsochronousTransfer.IsoPacket[i].Length = packet_size;
}
}
/* bulk or interrupt transfer */
else
{
(*urb)->UrbBulkOrInterruptTransfer.PipeHandle = pipe_handle;
(*urb)->UrbBulkOrInterruptTransfer.TransferFlags
= direction | USBD_SHORT_TRANSFER_OK;
(*urb)->UrbBulkOrInterruptTransfer.TransferBufferLength = size;
(*urb)->UrbBulkOrInterruptTransfer.TransferBufferMDL = buffer;
}
return STATUS_SUCCESS;
}
|
tinyos-io/tinyos-3.x-contrib | tinybt/tos/lib/bluetooth/bluetooth.h | /*
BlueZ - Bluetooth protocol stack for Linux
Copyright (C) 2000-2001 Qualcomm Incorporated
Written 2000,2001 by <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/*
* $Id: bluetooth.h,v 1.1 2011/12/09 19:48:58 sengg Exp $
*/
#ifndef __BLUETOOTH_H__
#define __BLUETOOTH_H__
#ifdef __cplusplus
extern "C" {
#endif
//#include <stdint.h>
//#include <endian.h>
//#include <byteswap.h>
//#include <string.h>
#ifndef AF_BLUETOOTH
#define AF_BLUETOOTH 31
#define PF_BLUETOOTH AF_BLUETOOTH
#endif
#define BTPROTO_L2CAP 0
#define BTPROTO_HCI 1
#define BTPROTO_SCO 2
#define BTPROTO_RFCOMM 3
#define BTPROTO_BNEP 4
#define SOL_HCI 0
#define SOL_L2CAP 6
#define SOL_SCO 17
#define SOL_RFCOMM 18
/* Byte order conversions */
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define htobs(d) (d)
#define htobl(d) (d)
#define btohs(d) (d)
#define btohl(d) (d)
#elif __BYTE_ORDER == __BIG_ENDIAN
#define htobs(d) bswap_16(d)
#define htobl(d) bswap_32(d)
#define btohs(d) bswap_16(d)
#define btohl(d) bswap_32(d)
#else
#error "Unknown byte order"
#endif
/* BD Address */
typedef struct {
uint8_t b[6];
} __attribute__((packed)) bdaddr_t;
#define BDADDR_ANY (&(bdaddr_t) {{0, 0, 0, 0, 0, 0}})
#define BDADDR_LOCAL (&(bdaddr_t) {{0, 0, 0, 0xff, 0xff, 0xff}})
/* Copy, swap, convert BD Address */
static inline int bacmp(bdaddr_t *ba1, bdaddr_t *ba2)
{
return memcmp(ba1, ba2, sizeof(bdaddr_t));
}
static inline void bacpy(bdaddr_t *dst, bdaddr_t *src)
{
memcpy(dst, src, sizeof(bdaddr_t));
}
void baswap(bdaddr_t *dst, bdaddr_t *src);
bdaddr_t *strtoba(char *str);
char *batostr(bdaddr_t *ba);
int ba2str(bdaddr_t *ba, char *str);
int str2ba(char *str, bdaddr_t *ba);
int bt_error(uint16_t code);
char *bt_compidtostr(int id);
#ifdef __cplusplus
}
#endif
#endif /* __BLUETOOTH_H */
|
tinyos-io/tinyos-3.x-contrib | tinymulle/apps/TestMac/TestMac.h | /*
* Copyright (c) 2007, Vanderbilt University
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE VANDERBILT UNIVERSITY BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE VANDERBILT
* UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE VANDERBILT UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE VANDERBILT UNIVERSITY HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
*
* Author: <NAME>
*/
#ifndef __TESTMAC_H__
#define __TESTMAC_H__
/**
* SEND_RATE the rate in milliseconds a source message should be sent out,
* if this value is 0, then the message is sent from a task as fast as it can.
* Set this value to -1 for turning off source messages.
*
* SEND_SOURCE the id of the source message. Each ping message contains a source
* identifier and a sequence number.
*
* SEND_TARGET the active message address of the source messages sent out by
* this node. Use AM_BROADCAST_ADDR to broadcast the message.
*
* SEND_ACK if it is set to 1, then packet acknowledgements are requested,
* otherwise set it to 0
*
* SOURCE_COUNT the number of data sources in the network whose progress we
* need to monitor.
*/
#define TESTCASE 0 // fanzha 2009-02-17
// everybody transmit as fast as we can for up to five nodes with IDs 0 through 4
#if TESTCASE == 0
#define SOURCE_COUNT 5
#define SEND_TARGET AM_BROADCAST_ADDR
#define SEND_SOURCE TOS_NODE_ID
#define SEND_RATE 0
#define SEND_ACK 1
// one node sending message to another as fast as it can
#elif TESTCASE == 1
#define SOURCE_COUNT 2
#define SEND_TARGET 1
#define SEND_SOURCE (TOS_NODE_ID == 0 ? 0 : -1)
#define SEND_RATE (TOS_NODE_ID == 0 ? 0 : -1)
#define SEND_ACK 1
// two nodes sending messages to one another 200 msgs per second
#elif TESTCASE == 2
#define SOURCE_COUNT 2
#define SEND_TARGET ((TOS_NODE_ID+1) % SOURCE_COUNT)
#define SEND_SOURCE TOS_NODE_ID
#define SEND_RATE 5
#define SEND_ACK 1
// two nodes sending messages to one another as fast as they can
#elif TESTCASE == 3
#define SOURCE_COUNT 2
#define SEND_TARGET ((TOS_NODE_ID+1) % SOURCE_COUNT)
#define SEND_SOURCE TOS_NODE_ID
#define SEND_RATE 0
#define SEND_ACK 1
// three nodes sending messages to one another as fast as they can
#elif TESTCASE == 4
#define SOURCE_COUNT 3
#define SEND_TARGET ((TOS_NODE_ID+1) % SOURCE_COUNT)
#define SEND_SOURCE TOS_NODE_ID
#define SEND_RATE 0
#define SEND_ACK 1
#endif
#endif//__TESTMAC_H__
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/pnp.c | /* LIBUSB-WIN32, Generic Windows USB Library
* Copyright (c) 2002-2005 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "libusb_driver.h"
static NTSTATUS DDKAPI
on_start_complete(DEVICE_OBJECT *device_object, IRP *irp,
void *context);
static NTSTATUS DDKAPI
on_device_usage_notification_complete(DEVICE_OBJECT *device_object,
IRP *irp, void *context);
static NTSTATUS DDKAPI
on_query_capabilities_complete(DEVICE_OBJECT *device_object,
IRP *irp, void *context);
NTSTATUS dispatch_pnp(libusb_device_t *dev, IRP *irp)
{
NTSTATUS status = STATUS_SUCCESS;
IO_STACK_LOCATION *stack_location = IoGetCurrentIrpStackLocation(irp);
UNICODE_STRING symbolic_link_name;
WCHAR tmp_name[128];
status = remove_lock_acquire(dev);
if(!NT_SUCCESS(status))
{
return complete_irp(irp, status, 0);
}
DEBUG_PRINT_NL();
switch(stack_location->MinorFunction)
{
case IRP_MN_REMOVE_DEVICE:
DEBUG_MESSAGE("dispatch_pnp(): IRP_MN_REMOVE_DEVICE");
dev->is_started = FALSE;
/* wait until all outstanding requests are finished */
remove_lock_release_and_wait(dev);
status = pass_irp_down(dev, irp, NULL, NULL);
DEBUG_MESSAGE("dispatch_pnp(): deleting device #%d", dev->id);
_snwprintf(tmp_name, sizeof(tmp_name)/sizeof(WCHAR), L"%s%04d",
LIBUSB_SYMBOLIC_LINK_NAME, dev->id);
/* delete the symbolic link */
RtlInitUnicodeString(&symbolic_link_name, tmp_name);
IoDeleteSymbolicLink(&symbolic_link_name);
/* delete the device object */
IoDetachDevice(dev->next_stack_device);
IoDeleteDevice(dev->self);
return status;
case IRP_MN_SURPRISE_REMOVAL:
DEBUG_MESSAGE("dispatch_pnp(): IRP_MN_SURPRISE_REMOVAL");
dev->is_started = FALSE;
break;
case IRP_MN_START_DEVICE:
DEBUG_MESSAGE("dispatch_pnp(): IRP_MN_START_DEVICE");
/* if(!NT_SUCCESS(set_configuration(dev, 1, 1000))) */
/* { */
/* DEBUG_ERROR("dispatch_pnp(): IRP_MN_START_DEVICE: selecting " */
/* "configuration failed"); */
/* } */
/* report device state to Power Manager */
/* power_state.DeviceState has been set to D0 by add_device() */
PoSetPowerState(dev->self, DevicePowerState, dev->power_state);
return pass_irp_down(dev, irp, on_start_complete, NULL);
case IRP_MN_STOP_DEVICE:
dev->is_started = FALSE;
DEBUG_MESSAGE("dispatch_pnp(): IRP_MN_STOP_DEVICE");
break;
case IRP_MN_DEVICE_USAGE_NOTIFICATION:
DEBUG_MESSAGE("dispatch_pnp(): IRP_MN_DEVICE_USAGE_NOTIFICATION");
if(!dev->self->AttachedDevice
|| (dev->self->AttachedDevice->Flags & DO_POWER_PAGABLE))
{
dev->self->Flags |= DO_POWER_PAGABLE;
}
return pass_irp_down(dev, irp, on_device_usage_notification_complete,
NULL);
case IRP_MN_QUERY_CAPABILITIES:
DEBUG_MESSAGE("dispatch_pnp(): IRP_MN_QUERY_CAPABILITIES");
if(!dev->is_filter)
{
/* apply registry setting */
stack_location->Parameters.DeviceCapabilities.Capabilities
->SurpriseRemovalOK = dev->surprise_removal_ok;
}
return pass_irp_down(dev, irp, on_query_capabilities_complete, NULL);
default:
;
}
remove_lock_release(dev);
return pass_irp_down(dev, irp, NULL, NULL);
}
static NTSTATUS DDKAPI
on_start_complete(DEVICE_OBJECT *device_object, IRP *irp, void *context)
{
libusb_device_t *dev = device_object->DeviceExtension;
if(irp->PendingReturned)
{
IoMarkIrpPending(irp);
}
if(dev->next_stack_device->Characteristics & FILE_REMOVABLE_MEDIA)
{
device_object->Characteristics |= FILE_REMOVABLE_MEDIA;
}
dev->is_started = TRUE;
remove_lock_release(dev);
return STATUS_SUCCESS;
}
static NTSTATUS DDKAPI
on_device_usage_notification_complete(DEVICE_OBJECT *device_object,
IRP *irp, void *context)
{
libusb_device_t *dev = device_object->DeviceExtension;
if(irp->PendingReturned)
{
IoMarkIrpPending(irp);
}
if(!(dev->next_stack_device->Flags & DO_POWER_PAGABLE))
{
device_object->Flags &= ~DO_POWER_PAGABLE;
}
remove_lock_release(dev);
return STATUS_SUCCESS;
}
static NTSTATUS DDKAPI
on_query_capabilities_complete(DEVICE_OBJECT *device_object,
IRP *irp, void *context)
{
libusb_device_t *dev = device_object->DeviceExtension;
IO_STACK_LOCATION *stack_location = IoGetCurrentIrpStackLocation(irp);
if(irp->PendingReturned)
{
IoMarkIrpPending(irp);
}
if(NT_SUCCESS(irp->IoStatus.Status))
{
if(!dev->is_filter)
{
/* apply registry setting */
stack_location->Parameters.DeviceCapabilities.Capabilities
->SurpriseRemovalOK = dev->surprise_removal_ok;
}
/* save supported device power states */
memcpy(dev->device_power_states, stack_location
->Parameters.DeviceCapabilities.Capabilities->DeviceState,
sizeof(dev->device_power_states));
}
remove_lock_release(dev);
return STATUS_SUCCESS;
}
|
tinyos-io/tinyos-3.x-contrib | unlpt/PowerTossim-TelosB/tos/lib/tossim/sim_energy_estimate.h | /**
* "Copyright (c) 2007 CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc BE LIABLE TO
* ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc HAS BEEN ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* CENTRE FOR ELECTRONICS AND DESIGN TECHNOLOGY,IISc SPECIFICALLY DISCLAIMS
* ANY WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND CENTRE FOR ELECTRONICS
* AND DESIGN TECHNOLOGY,IISc HAS NO OBLIGATION TO PROVIDE MAINTENANCE,
* SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
/**
*
* @author <NAME>
* @author <NAME>
*/
#ifndef _SIM_ENERGY_ESTIMATE_H_
#define _SIM_ENERGY_ESTIMATE_H_
#ifdef __cplusplus
extern "C" {
#endif
typedef struct LedsEnergy_t {
double led0;
double led1;
double led2;
double total;
} LedsEnergy_t;
typedef struct MCUEnergy_t{
double idle;
double adc;
double extStandby;
double save;
double standby;
double down;
double on;
double total;
} MCUEnergy_t;
typedef struct RadioEnergy_t {
double core;
double coreBias;
double coreBiasSyn;
double tx;
double rx;
double rxPacket;
double total;
} RadioEnergy_t;
typedef struct MemEnergy_t {
double write;
double read;
double total;
}MemEnergy_t;
typedef struct sim_energy_t {
MCUEnergy_t MCUEnergy;
LedsEnergy_t LedEnergy;
RadioEnergy_t RadioEnergy;
MemEnergy_t MemEnergy;
double total;
} sim_energy_t;
void sim_energy_estimator_init();
void sim_update_cpuIdleEnergy(double val) ;
void sim_update_cpuAdcEnergy(double val) ;
void sim_update_cpuExtStandbyEnergy(double val) ;
void sim_update_cpuSaveEnergy(double val) ;
void sim_update_cpuStandbyEnergy(double val) ;
void sim_update_cpuPowerDownEnergy(double val) ;
void sim_update_cpuOnEnergy(double val) ;
void sim_update_led0Energy(double val) ;
void sim_update_led1Energy(double val) ;
void sim_update_led2Energy(double val) ;
void sim_update_cyrsOscEnergy(double val);
void sim_update_cyrsOscBiasEnergy(double val);
void sim_update_cyrsOscBiasSynEnergy(double val);
void sim_update_radioTxEnergy(double val) ;
void sim_update_radioRxEnergy(double val) ;
void sim_update_radioRxPacketEnergy(double val);
void sim_update_memWriteEnergy(double val);
void sim_update_memReadEnergy(double val);
void sim_node_energy(int nodeId);
#ifdef __cplusplus
}
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | uob/tossdr/tos/chips/atm128/sdr/atm128hardware.h | <filename>uob/tossdr/tos/chips/atm128/sdr/atm128hardware.h
/*
* IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. By
* downloading, copying, installing or using the software you agree to
* this license. If you do not agree to this license, do not download,
* install, copy or use the software.
*
* Copyright (c) 2004-2005 Crossbow Technology, Inc.
* Copyright (c) 2002-2003 Intel Corporation.
* Copyright (c) 2000-2003 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the (updated) modification history and the author appear in
* all copies of this source code.
*
* Permission is also granted to distribute this software under the
* standard BSD license as contained in the TinyOS distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 INTEL OR ITS
* 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.
*
* @author <NAME>, <NAME>, <NAME>, <NAME>
* @author <NAME> <<EMAIL>>
*
* $Id: atm128hardware.h,v 1.2 2009/05/28 21:13:06 mab-cn Exp $
*/
#ifndef _H_atmega128hardware_H
#define _H_atmega128hardware_H
#include <atm128_sim.h>
#include <sim_tossdr.h>
uint8_t atm128RegFile[TOSSIM_MAX_NODES][0xa0];
#define REG_ACCESS(x) atm128RegFile[sim_node()][x]
/* We need slightly different defs than SIGNAL, INTERRUPT */
#define AVR_ATOMIC_HANDLER(signame) \
void signame() @spontaneous() @C()
#define AVR_NONATOMIC_HANDLER(signame) \
void signame() @spontaneous() @C()
/* Macro to create union casting functions. */
#define DEFINE_UNION_CAST(func_name, from_type, to_type) \
to_type func_name(from_type x_type) { \
union {from_type f_type; to_type t_type;} c_type = {f_type:x_type}; return c_type.t_type; }
// Bit operators using bit number
#define SET_BIT(port, bit) ((REG_ACCESS(port)) |= _BV(bit))
#define CLR_BIT(port, bit) ((REG_ACCESS(port)) &= ~_BV(bit))
#define READ_BIT(port, bit) (((REG_ACCESS(port)) & _BV(bit)) != 0)
#define FLIP_BIT(port, bit) ((REG_ACCESS(port)) ^= _BV(bit))
#define WRITE_BIT(port, bit, value) \
if (value) SET_BIT((port), (bit)); \
else CLR_BIT((port), (bit))
// Bit operators using bit flag mask
#define SET_FLAG(port, flag) ((REG_ACCESS(port)) |= (flag))
#define CLR_FLAG(port, flag) ((REG_ACCESS(port)) &= ~(flag))
#define READ_FLAG(port, flag) ((REG_ACCESS(port)) & (flag))
#define sei() (SET_BIT(SREG, 7))
#define cli() (CLR_BIT(SREG, 7))
/* Enables interrupts. */
inline void __nesc_enable_interrupt() {
sei();
}
/* Disables all interrupts. */
inline void __nesc_disable_interrupt() {
cli();
}
/* Defines data type for storing interrupt mask state during atomic. */
typedef uint8_t __nesc_atomic_t;
/* Saves current interrupt mask state and disables interrupts. */
inline __nesc_atomic_t
__nesc_atomic_start(void) @spontaneous()
{
__nesc_atomic_t result = SREG;
__nesc_disable_interrupt();
return result;
}
/* Restores interrupt mask to original state. */
inline void
__nesc_atomic_end(__nesc_atomic_t original_SREG) @spontaneous()
{
SREG = original_SREG;
}
inline void
__nesc_atomic_sleep()
{
//sbi(MCUCR, SE); power manager will enable/disable sleep
sei(); // Make sure interrupts are on, so we can wake up!
asm volatile ("sleep");
}
typedef uint8_t mcu_power_t @combine("mcombine");
/* Combine function. */
mcu_power_t mcombine(mcu_power_t m1, mcu_power_t m2) {
return (m1 < m2)? m1: m2;
}
enum {
ATM128_POWER_IDLE = 0,
ATM128_POWER_ADC_NR = 1,
ATM128_POWER_EXT_STANDBY = 2,
ATM128_POWER_SAVE = 3,
ATM128_POWER_STANDBY = 4,
ATM128_POWER_DOWN = 5,
};
#endif //_H_atmega128hardware_H
|
tinyos-io/tinyos-3.x-contrib | kasetsart/tos/chips/atm328/timer/Atm328Timer.h | /*
* This file contains the configuration constants for the Atmega328
* clocks and timers.
*
* @author <NAME> (<EMAIL>)
*/
#ifndef _H_Atm328Timer_h
#define _H_Atm328Timer_h
//====================== 8 bit Timers ==================================
/*************************************************************/
/* Timer0 Clock Source. Page 110: ATmega48/88/168 (DOC8161) */
/*************************************************************/
enum {
ATM328_T0_OFF = 0x0,
ATM328_T0_DIV_1 = 0x1,
ATM328_T0_DIV_8 = 0x2,
ATM328_T0_DIV_64 = 0x3,
ATM328_T0_DIV_256 = 0x4,
ATM328_T0_DIV_1024 = 0x5,
ATM328_T0_EXT_FALLING = 0x6,
ATM328_T0_EXT_RISING = 0x7,
};
/*************************************************************/
/* Timer2 Clock Source. Page 162: ATmega48/88/168 (DOC8161) */
/*************************************************************/
enum {
ATM328_T2_OFF = 0x0,
ATM328_T2_NORMAL = 0x1,
ATM328_T2_DIVIDE_8 = 0x2,
ATM328_T2_DIVIDE_32 = 0x3,
ATM328_T2_DIVIDE_64 = 0x4,
ATM328_T2_DIVIDE_128 = 0x5,
ATM328_T2_DIVIDE_256 = 0x6,
ATM328_T2_DIVIDE_1024 = 0x7,
};
/*****************************************************************/
/* TCCR0A - Timer/Counter Control Register A (DOC8161, page 106) */
/*****************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t wgm0 : 1; //!< Waveform generation mode bit 0
uint8_t wgm1 : 1; //!< Waveform generation mode bit 1
uint8_t na : 2; //!< Not used
uint8_t com0b : 2; //!< Compare match output B
uint8_t com0a : 2; //!< Compare match output A
} bits;
} Atm328_TCCR0A_t;
/*******************************************************************/
/* TCCR0B - Timer/Counter 0 Control Register B (DOC8161, page 109) */
/*******************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t cs : 3; //!< Clock Source Select
uint8_t wgm2 : 1; //!< Waveform generation mode bit 2
uint8_t na : 2; //!< Not used
uint8_t foc0b : 1; //!< Force output compare B
uint8_t foc0a : 1; //!< Force output compare A
} bits;
} Atm328_TCCR0B_t;
/************************************************************************/
/* TIMSK0 - Timer/Counter 0 Interrupt Mask Register (DOC8161, page 111) */
/************************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t na : 5; //!< Not used
uint8_t ocie0b : 1; //!< TC0 output compare match B interrupt enable
uint8_t ocie0a : 1; //!< TC0 output compare match A interrupt enable
uint8_t toie0 : 1; //!< TC0 overflow interrupt enable
} bits;
} Atm328_TIMSK0_t;
/***********************************************************************/
/* TIFR0 - Timer/Counter 0 Interrupt Flag Register (DOC8161, page 111) */
/***********************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t na : 5; //!< Not used
uint8_t ocf0b : 1; //!< TC0 output compare B match flag
uint8_t ocf0a : 1; //!< TC0 output compare A match flag
uint8_t tov0 : 1; //!< TC0 overflow flag
} bits;
} Atm328_TIFR0_t;
/*******************************************************************/
/* TCCR2A - Timer/Counter 2 Control Register A (DOC8161, page 158) */
/*******************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t com2a : 2; //!< Compare match output A mode
uint8_t com2b : 2; //!< Compare match output B mode
uint8_t na : 2; //!< Not used
uint8_t wgm21 : 1; //!< Waveform generation mode bit 1
uint8_t wgm20 : 1; //!< Waveform generation mode bit 0
} bits;
} Atm328_TCCR2A_t;
/*******************************************************************/
/* TCCR2B - Timer/Counter 2 Control Register B (DOC8161, page 161) */
/*******************************************************************/
typedef union
{
uint8_t flat; struct {
uint8_t foc2a : 1; //!< Force output compare A
uint8_t foc2b : 1; //!< Force output compare B
uint8_t na : 2; //!< Not used
uint8_t wgm22 : 1; //!< Waveform generation mode bit 2
uint8_t cs2 : 3; //!< Clock source
} bits;
} Atm328_TCCR2B_t;
/************************************************************************/
/* TIMSK2 - Timer/Counter 2 Interrupt Mask Register (DOC8161, page 163) */
/************************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t na : 5; //!< Not used
uint8_t ocie2b : 1; //!< TC2 output compare match B interrupt enable
uint8_t ocie2a : 1; //!< TC2 output compare match A interrupt enable
uint8_t toie2 : 1; //!< TC2 overflow interrupt enable
} bits;
} Atm328_TIMSK2_t;
/***********************************************************************/
/* TIFR2 - Timer/Counter 2 Interrupt Flag Register (DOC8161, page 163) */
/***********************************************************************/
typedef union
{
uint8_t flat;
struct {
uint8_t na : 5; //!< Not used
uint8_t ocf2b : 1; //!< TC2 output compare B match flag
uint8_t ocf2a : 1; //!< TC2 output compare A match flag
uint8_t tov2 : 1; //!< TC2 overflow flag
} bits;
} Atm328_TIFR2_t;
#endif //_H_Atm328Timer_h
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/chips/atm128/atm128uartconf.h | /*
* Copyright (c) 2008 Rincon Research Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Rincon Research Corporation 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 COPYRIGHT HOLDERS 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
* RINCON RESEARCH OR ITS 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
*
* @author <NAME>
*/
#ifndef __atm128uart_h__
#define __atm128uart_h__
typedef struct atm128_uart_config {
// UBRRx
uint16_t br; // baud rate in hundreds of bps
// UCSRxA
uint8_t u2x : 1; // double speed mode
// UCSRxB
uint8_t ucsz : 2; // char size 5678
uint8_t upar : 2; // parity NEO
uint8_t usb : 1; // stop bits 12
} atm128_uart_config_t;
typedef enum atm128_uart_baud {
ATM128_UART_BAUD_300 = 3,
ATM128_UART_BAUD_600 = 6,
ATM128_UART_BAUD_1200 = 12,
ATM128_UART_BAUD_2400 = 24,
ATM128_UART_BAUD_4800 = 48,
ATM128_UART_BAUD_9600 = 96,
ATM128_UART_BAUD_14400 = 144,
ATM128_UART_BAUD_19200 = 192,
ATM128_UART_BAUD_28800 = 288,
ATM128_UART_BAUD_38400 = 384,
ATM128_UART_BAUD_57600 = 576,
ATM128_UART_BAUD_76800 = 768,
ATM128_UART_BAUD_115200 = 1152,
} atm128_uart_baud_t;
typedef enum atm128_uart_clock {
ATM128_UART_CLOCK_NORMAL = 0,
ATM128_UART_CLOCK_DOUBLE = 1,
} atm128_uart_clock_t;
typedef enum atm128_uart_charsize {
ATM128_UART_CHARSIZE_5 = 0,
ATM128_UART_CHARSIZE_6 = 1,
ATM128_UART_CHARSIZE_7 = 2,
ATM128_UART_CHARSIZE_8 = 3,
} atm128_uart_charsize_t;
typedef enum atm128_uart_parity {
ATM128_UART_PARITY_NONE = 0,
ATM128_UART_PARITY_EVEN = 2,
ATM128_UART_PARITY_ODD = 3,
} atm128_uart_parity_t;
typedef enum atm128_uart_stopbits {
ATM128_UART_STOPBITS_1 = 0,
ATM128_UART_STOPBITS_2 = 1,
} atm128_uart_stopbits_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | ethz/rest-api/tos/lib/net/blip/http/Http.h | <reponame>tinyos-io/tinyos-3.x-contrib<gh_stars>1-10
/* Copyright (c) 2009, Distributed Computing Group (DCG), ETH Zurich.
* 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 copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS 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 COPYRIGHT HOLDERS OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, LOSS OF USE, DATA,
* OR PROFITS) 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.
*
* @author <NAME> <<EMAIL>>
*
*/
#ifndef HTTP_H
#define HTTP_H
enum {
HTTP_CONTINUE = 100,
HTTP_SWITCHING_PROTOCOLS = 101,
HTTP_PROCESSING = 102,
HTTP_OK = 200,
HTTP_CREATED = 201,
HTTP_ACCEPTED = 202,
HTTP_NON_AUTHORITATIVE_INFORMATION = 203,
HTTP_NO_CONTENT = 204,
HTTP_RESET_CONTENT = 205,
HTTP_PARTIAL_CONTENT = 206,
HTTP_MULTI_STATUS = 207,
HTTP_IM_USED = 226,
HTTP_MULTIPLE_CHOICES = 300,
HTTP_MOVED_PERMANENTLY = 301,
HTTP_FOUND = 302,
HTTP_SEE_OTHER = 303,
HTTP_NOT_MODIFIED = 304,
HTTP_USE_PROXY = 305,
HTTP_RESERVED = 306,
HTTP_TEMPORARY_REDIRECT = 307,
HTTP_BAD_REQUEST = 400,
HTTP_UNAUTHORIZED = 401,
HTTP_PAYMENT_REQUIRED = 402,
HTTP_FORBIDDEN = 403,
HTTP_NOT_FOUND = 404,
HTTP_METHOD_NOT_ALLOWED = 405,
HTTP_NOT_ACCEPTABLE = 406,
HTTP_PROXY_AUTHENTICATION_REQUIRED = 407,
HTTP_REQUEST_TIMEOUT = 408,
HTTP_CONFLICT = 409,
HTTP_GONE = 410,
HTTP_LENGTH_REQUIRED = 411,
HTTP_PRECONDITION_FAILED = 412,
HTTP_REQUEST_ENTITY_TOO_LARGE = 413,
HTTP_REQUEST_URI_TOO_LONG = 414,
HTTP_UNSUPPORTED_MEDIA_TYPE = 415,
HTTP_REQUESTED_RANGE_NOT_SATISFIABLE_ = 416,
HTTP_EXPECTATION_FAILED = 417,
HTTP_UNPROCESSABLE_ENTITY = 422,
HTTP_LOCKED = 423,
HTTP_FAILED_DEPENDENCY = 424,
HTTP_UPGRADE_REQUIRED = 426,
HTTP_INTERNAL_SERVER_ERROR = 500,
HTTP_NOT_IMPLEMENTED = 501,
HTTP_BAD_GATEWAY = 502,
HTTP_SERVICE_UNAVAILABLE = 503,
HTTP_GATEWAY_TIMEOUT_ = 504,
HTTP_HTTP_VERSION_NOT_SUPPORTED = 505,
HTTP_VARIANT_ALSO_NEGOTIATES = 506,
HTTP_INSUFFICIENT_STORAGE = 507,
HTTP_NOT_EXTENDED = 510,
};
enum {
HTTP_GET = 0,
HTTP_POST = 1,
HTTP_PUT = 2,
HTTP_DELETE = 3,
};
enum {
HTTP_1_0 = 0,
HTTP_1_1 = 1,
};
enum {
HTTP_LEN_START = 33,
};
#define END_LINE "\r\n"
#endif /* HTTP_H */
|
tinyos-io/tinyos-3.x-contrib | eon/apps/server-e/impl/telos/ServerE.h | <gh_stars>1-10
#include <AM.h>
#ifndef SERVERE_H_INCLUDED
#define SERVERE_H_INCLUDED
#ifndef HEADER_LENGTH
#define HEADER_LENGTH 4
#endif
#ifndef DATA_HEADER_LENGTH
#define DATA_HEADER_LENGTH 8
#endif
#ifndef URL_LENGTH
#define URL_LENGTH (TOSH_DATA_LENGTH-HEADER_LENGTH)
#endif
#ifndef PKT_DATA_LENGTH
#define PKT_DATA_LENGTH (TOSH_DATA_LENGTH-DATA_HEADER_LENGTH)
#endif
typedef struct RequestMsg {
uint16_t src;
uint16_t suid; //chosen by connection requestor
uint8_t url[URL_LENGTH];
} __attribute((packed)) RequestMsg;
typedef struct RedirectMsg {
uint16_t src;
uint16_t suid;
uint16_t port;
uint16_t delay_ms;
} __attribute((packed)) RedirectMsg;
typedef struct MetaMsg {
uint16_t src;
uint16_t suid;
uint32_t size;
uint16_t error;
} __attribute((packed)) MetaMsg;
typedef struct DataMsg {
uint16_t src;
uint16_t suid;
uint16_t segment;
uint16_t size;
uint8_t data[PKT_DATA_LENGTH];
} __attribute((packed)) DataMsg;
typedef struct DataAck {
uint16_t src;
uint16_t suid;
uint16_t segment;
} __attribute((packed)) DataAck;
enum {
AM_REQUESTMSG = 0x14,
AM_REDIRECTMSG = 0x15,
AM_METAMSG = 0x16,
AM_DATAMSG = 0x17,
AM_DATAACK = 0x18
};
typedef RequestMsg* RequestMsgPtr;
typedef RedirectMsg* RedirectMsgPtr;
typedef MetaMsg* MetaMsgPtr;
typedef DataMsg* DataMsgPtr;
typedef DataAck* DataAckPtr;
#endif
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/sim_csma.c | /*
* "Copyright (c) 2005 Stanford University. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
* HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS."
*/
/**
*
* C implementation of configuration parameters for a CSMA link.
*
* @author <NAME>
* @date Dec 10 2005
*/
// $Id: sim_csma.c,v 1.1 2014/11/26 19:31:35 carbajor Exp $
#include <sim_csma.h>
int csmaInitHigh = SIM_CSMA_INIT_HIGH;
int csmaInitLow = SIM_CSMA_INIT_LOW;
int csmaHigh = SIM_CSMA_HIGH;
int csmaLow = SIM_CSMA_LOW;
int csmaSymbolsPerSec = SIM_CSMA_SYMBOLS_PER_SEC;
int csmaBitsPerSymbol = SIM_CSMA_BITS_PER_SYMBOL;
int csmaPreambleLength = SIM_CSMA_PREAMBLE_LENGTH;
int csmaExponentBase = SIM_CSMA_EXPONENT_BASE;
int csmaMaxIterations = SIM_CSMA_MAX_ITERATIONS;
int csmaMinFreeSamples = SIM_CSMA_MIN_FREE_SAMPLES;
int csmaRxTxDelay = SIM_CSMA_RXTX_DELAY;
int csmaAckTime = SIM_CSMA_ACK_TIME;
int sim_csma_init_high() __attribute__ ((C, spontaneous)) {
return csmaInitHigh;
}
int sim_csma_init_low() __attribute__ ((C, spontaneous)) {
return csmaInitLow;
}
int sim_csma_high() __attribute__ ((C, spontaneous)) {
return csmaHigh;
}
int sim_csma_low() __attribute__ ((C, spontaneous)) {
return csmaLow;
}
int sim_csma_symbols_per_sec() __attribute__ ((C, spontaneous)) {
return csmaSymbolsPerSec;
}
int sim_csma_bits_per_symbol() __attribute__ ((C, spontaneous)) {
return csmaBitsPerSymbol;
}
int sim_csma_preamble_length() __attribute__ ((C, spontaneous)) {
return csmaPreambleLength;
}
int sim_csma_exponent_base() __attribute__ ((C, spontaneous)) {
return csmaExponentBase;;
}
int sim_csma_max_iterations() __attribute__ ((C, spontaneous)) {
return csmaMaxIterations;
}
int sim_csma_min_free_samples() __attribute__ ((C, spontaneous)) {
return csmaMinFreeSamples;
}
int sim_csma_rxtx_delay() __attribute__ ((C, spontaneous)) {
return csmaRxTxDelay;
}
int sim_csma_ack_time() __attribute__ ((C, spontaneous)) {
return csmaAckTime;
}
void sim_csma_set_init_high(int val) __attribute__ ((C, spontaneous)) {
csmaInitHigh = val;
}
void sim_csma_set_init_low(int val) __attribute__ ((C, spontaneous)) {
csmaInitLow = val;
}
void sim_csma_set_high(int val) __attribute__ ((C, spontaneous)) {
csmaHigh = val;
}
void sim_csma_set_low(int val) __attribute__ ((C, spontaneous)) {
csmaLow = val;
}
void sim_csma_set_symbols_per_sec(int val) __attribute__ ((C, spontaneous)) {
csmaSymbolsPerSec = val;
}
void sim_csma_set_bits_per_symbol(int val) __attribute__ ((C, spontaneous)) {
csmaBitsPerSymbol = val;
}
void sim_csma_set_preamble_length(int val) __attribute__ ((C, spontaneous)) {
csmaPreambleLength = val;
}
void sim_csma_set_exponent_base(int val) __attribute__ ((C, spontaneous)) {
csmaExponentBase = val;
}
void sim_csma_set_max_iterations(int val) __attribute__ ((C, spontaneous)) {
csmaMaxIterations = val;
}
void sim_csma_set_min_free_samples(int val) __attribute__ ((C, spontaneous)) {
csmaMinFreeSamples = val;
}
void sim_csma_set_rxtx_delay(int val) __attribute__ ((C, spontaneous)) {
csmaRxTxDelay = val;
}
void sim_csma_set_ack_time(int val) __attribute__ ((C, spontaneous)) {
csmaAckTime = val;
}
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/chips/rf230/RF230TimerConfig.h | /**
* The M16c/62p hardware timer configuration used by Mulle
* together with the RF230 chip.
*
* STOP MODE ENABLED:
* TA4 generates a 16 bit TRF230 counter.
* TB5 generates a 16 bit TRF230 alarm.
*
* STOP MODE DISABLED:
* TA4 generates TMicro tics.
* TA3 is a 16 bit alarm that counts tics from TA4.
*
* @author <NAME>
*/
#ifndef __RF230TIMERCONFIG_H__
#define __RF230TIMERCONFIG_H__
// No stop mode.
#define ALARM_MICRO16_SOURCE TimerA4
#define ALARM_MICRO16_SOURCE_CTRL TimerA4Ctrl
#define ALARM_MICRO16 TimerA3
#define ALARM_MICRO16_CTRL TimerA3Ctrl
// End
// Stop mode enabled.
#define COUNTER_RF23016 TimerA4
#define COUNTER_RF23016_CTRL TimerA4Ctrl
#define ALARM_RF23016 TimerB5
#define ALARM_RF23016_CTRL TimerB5Ctrl
// End
#endif // __RF230TIMERCONFIG_H__
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/squelch/Squelch.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef SQUELCH_H
#define SQUELCH_H
/**
* The size of each squelch table
*/
#ifndef SQUELCH_TABLE_SIZE
#define SQUELCH_TABLE_SIZE 10
#endif
/**
* Minimum number of measurements before being settled
*/
#ifndef SQUELCH_MIN_COUNT
#define SQUELCH_MIN_COUNT 20
#endif
/**
* Initial squelch threshold
*/
#ifndef SQUELCH_INITIAL_THRESHOLD
#define SQUELCH_INITIAL_THRESHOLD 70
#endif
/**
* Scaling numerator
*/
#ifndef SQUELCH_NUMERATOR
#define SQUELCH_NUMERATOR 7
#endif
/**
* Scaling denominator
*/
#ifndef SQUELCH_DENOMINATOR
#define SQUELCH_DENOMINATOR 8
#endif
/**
* Unique identifier for squelch clients
*/
#ifndef UQ_SQUELCH_CLIENT
#define UQ_SQUELCH_CLIENT "Unique.Squelch.Client"
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | rincon/tos/lib/blackbook/core/BDictionary.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>rincon/tos/lib/blackbook/core/BDictionary.h
/*
* Copyright (c) 2005-2006 Rincon Research Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Rincon Research Corporation 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 COPYRIGHT HOLDERS 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
* ARCHED ROCK OR ITS 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
*/
/**
* @author <NAME>
*/
#ifndef BDICTIONARY_H
#define BDICTIONARY_H
#include "Blackbook.h"
#define UQ_BDICTIONARY "BDictionary"
/**
* Keeping the most recently used keys from a file_t in memory
* decreases search time at the expense of RAM.
*/
typedef struct keycache_t {
/** The key */
uint32_t key;
/**
* The data offset in the file_t to reach the beginning of the key
* 0xFFFF means this entire cache key is invalid
*/
uint32_t keyOffset;
} keycache_t;
/**
* This is a key-value pair to be inserted into
* a Dictionary file. The value can be any size,
* and the address of the valueStart variable
* is where to start writing the data
*/
typedef struct keymeta_t {
/** The magic number for a valid key-value pair entry */
uint16_t magicNumber;
/** The key */
uint32_t key;
/** The CRC of the value */
uint16_t valueCrc;
/** The length of the value */
uint16_t valueLength;
} keymeta_t;
/**
* Dictionary Magic Words
*/
enum {
KEY_EMPTY = 0xFFFF, // binary 1111
KEY_VALID = 0xAAAA, // binary 1010
KEY_INVALID = 0x8888, // binary 1000
ENTRY_INVALID = 0xFFFFFFFF,
DICTIONARY_HEADER = 0xD1C7,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | blaze/tos/chips/ccxx00_single/radios/cc1100/CC1100_433MHz_150kBaud.h | /*
* Copyright (c) 2005-2006 Rincon Research Corporation
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Rincon Research Corporation 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 COPYRIGHT HOLDERS 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
* RINCON RESEARCH OR ITS 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
*/
/**
* All frequency settings assume a 26 MHz crystal.
* If you have a 27 MHz crystal, you'll need to fix the defined FREQ registers
*
* @author <NAME>
* @author <NAME>
* @author <NAME>
*/
#ifndef CC1100_H
#define CC1100_H
#include "Blaze.h"
enum {
CC1100_RADIO_ID = unique( UQ_BLAZE_RADIO ),
};
/**
* All default channels and FREQx registers obtained from SmartRF studio. We
* are not trying to define channel frequencies to match up with any sort of
* specification; instead, we want flexibility. If you want to align with
* specs, then go for it.
*
* Note you can setup the CC1100 to match your antenna characteristics.
* Maybe your antenna is tuned to +/- 5 MHz with a center frequency of 315 MHz.
* You want your center frequency to be 314.996 MHz, and your lower edge to be
* 310 MHz and your upper edge to be 320 MHz.
*
* Lower Channel Calculation:
* CC1100_CHANNEL_MIN = [(310000 desired kHz) - (CC1100_LOWEST_FREQ)]
* ---------------------------------------------
* 199 kHz channel spacing
*
* Where CC1100_LOWEST_FREQ is defined for each band and 199 kHz is
* approximately the channel spacing, CC1100_CHANNEL_WIDTH
*
* CC1100_CHANNEL_MIN ~= 45
*
*
* Upper Channel Calculation:
* CC1100_CHANNEL_MAX = [(320000 desired kHz) - (CC1100_LOWEST_FREQ)]
* ---------------------------------------------
* 199 kHz channel spacing
*
* CC1100_CHANNEL_MAX ~= 95
*
* Incidentally, (95+45)/2 = 70, which is our default center channel.
*
* When you apply the MAX and MIN values, the radio stack will automatically
* make sure you're within bounds when you set the frequency or channel during
* runtime.
*
* We defined the minimum and maximum channels for the various bands below
* so they generally stay within the limits of the CC1100 radio defined in the
* datasheet.
*/
/***************** 433 MHz Matching Network ****************/
// Default channel is at 433.191833 MHz
#define CC1100_CRYSTAL_HZ 26000000
#define CC1100_433_MHZ 1
#define CC1100_MATCHING_NETWORK CC1100_433_MHZ
// NOTE: these are used for calculating channels at runtime
#define CC1100_LOWEST_FREQ 400998
#define CC1100_CHANNEL_WIDTH 199
#define CC1100_DEFAULT_CHANNEL 161
#define CC1100_CHANNEL_MIN 0
#define CC1100_CHANNEL_MAX 255
/* register settings, many of which calculated by RF Smart Studio */
/* Reset changes registers to Default values */
enum CC1100_config_reg_state_enums {
/* Registers preserve programming values in SLEEP */
CC1100_CONFIG_IOCFG2 = 0x29, // 0x00, GDO2 Output Pin Config
// 7, RO, not used
// 6, R/W, GDO2_INV, Invert output. Default active high = 0x0.
// 5:0, R/W, GDO2_CFG, Default CHP_RDYn = 0x29.
CC1100_CONFIG_IOCFG1 = 0x2E, // 0x01, GDO1 Output Pin Config
// 7, R/W, GDO_DS, Output drive strength on GD0 pins. Default low = 0x0.
// 6, R/W, GDO1_INV, Invert output. Default active high = 0x0.
// 5:0, R/W, GDO2_CFG, Default Tri-state = 0x2E.
CC1100_CONFIG_IOCFG0 = 0x01, // 0x02, GDO0 Output Pin Config
// 7, R/W, TEMP_SENSOR_ENABLE, Enable analog temp sensor. Default disable = 0x0. write 0 in all other bits if enabled
// 6, R/W, GDO0_INV, Invert output. default active high = 0x0.
// 5:0, R/W, GDO0_CFG, Default CLK_XOSC/192 = 0x3F.
// 0x01 = Associated to RX_FIFO
CC1100_CONFIG_FIFOTHR = 0x0F, // 0x03, RX FIFO and TX FIFO Thresholds
// 7, RO, reserved, write 0 for future compatability
// 6, R/W, ADC_RETENTION, Waking from SLEEP default = 0x0, TEST1 = 0x31 and TEST2 = 0x88.
// Set = 0x1, TEST1 = 0x35 and TEST2 = 0x81.
// 5:4, R/W, CLOSE_IN_RX, RX Attenuation, Default 0dB = 0x0.
// 3:0, R/W, FIFO_THR, FIFO threshold in bytes. Default = 0x7, TX = 33 and RX = 32.
// Set = 0xF, TX = 1 and RX = 64.
CC1100_CONFIG_SYNC1 = 0xD3, // 0x04, Sync Word, High Byte
// 7:0, R/W, SYNC_H, 8 MSB of 16 bit sync word. Default 0xD3
CC1100_CONFIG_SYNC0 = 0x91, // 0x05, Sync Word, Low Byte
// 7:0, R/W, SYNC_L, 8 LSB of 16 bit sync word. Default 0x91
CC1100_CONFIG_PKTLEN = 0x3D, // 0x06, Packet Length
// 7:0, R/W, PACKET_LENGTH, Maximum variable packet length is 61 per Errata
CC1100_CONFIG_PKTCTRL1 = 0x24, // 0x07, Packet Automation Control
// 7:5, R/W, PQT, Preamble quality estimator threshold, Default = 0x0
// 4, RO, not used
// 3, R/W, CRC_AUTOFLUSH, Enable automatic flush of RX FIFO when CRC is not OK. Default disable = 0x0
// 2, R/W, APPEND_STATUS, Default enabled = 0x1, CRC OK + LQI byte and RSSI byte appended to payload.
// 1:0, R/W, ADR_CHK, Received packets address check config. Default No address check = 0x0.
CC1100_CONFIG_PKTCTRL0 = 0x45, // 0x08, Packet Automation Control
// 7, RO, not used
// 6, R/W, WHITE_BIT, Turn data whitening on/off. Default on = 0x1.
// 5:4, R/W, PKT_FORMAT, Format of RX/TX data, Default normal = 0x0.
// 2, R/W, CRC_EN, CRC check. Default on = 0x1
// 1:0, R/W, LENGTH_CONFIG, Config packet length, Default variable packet length mode = 0x1.
CC1100_CONFIG_ADDR = 0x00, // 0x09, Device Address
// 7:0, R/W, DEVICE_ADDR, Address used for packet filtration. Default 0x00
CC1100_CONFIG_CHANNR = CC1100_DEFAULT_CHANNEL, // 0x0A, Channel Number
// 7:0, R/W, CHAN, 8bit usigned channel number. Default = 0x00
CC1100_CONFIG_FSCTRL1 = 0x0E, // 0x0B, Frequency Synthesizer Control
// 7:6, RO, not used
// 5, R/W, reserved, write 0 for future compatability.
// 4:0, R/W, FREQ_IF, Desired IF Frequency to employ in RX. Default = 0x0F
CC1100_CONFIG_FSCTRL0 = 0x00, // 0x0C, Frequency Synthesizer Control
// 7:0, R/W, FREQOFF, Offset added to base Frequency for synthesizer. Default = 0x00
CC1100_CONFIG_FREQ2 = 0x0F, // 0x0D, Frequency Control Word, High
// 7:6, RO, FREQ, not used
// 5:0, R/W, FREQ_H, Base frequency for synthesizer. Default = 0x1E
CC1100_CONFIG_FREQ1 = 0x6C, // 0x0E, Frequency Control Word, Middle
// 7:0, R/W, FREQ_M, Ref FREQ2 register. Default = 0xC4
CC1100_CONFIG_FREQ0 = 0x4E, // 0x0F, Frequency Control Word, Low
// 7:0, R/W, FREQ_L, Ref FREQ2 register. Default 0xEC
CC1100_CONFIG_MDMCFG4 = 0x0C, // 0x10, Modem Config
// 7:6, R/W. CHANBW_E, channel bandwidth decimation ratio exponent. Default = 0x2
// 5:4, R/W, CHANBW_M, channel bandwidth decimation ratio mantissa. Default = 0x0
// 3:0, R/W, DRATE_E, User specified symbol rate exponent. Default = 0xC
CC1100_CONFIG_MDMCFG3 = 0x3B, // 0x11, Modem Config
// 7:0, R/W. DRATE_M, User specified symbol rate mantissa. Default enable = 0x22
CC1100_CONFIG_MDMCFG2 = 0x73, // 0x12, Modem Config
// 7, R/W. DEM_DCFILT_OFF, Disable digital DC blocking filter. Default enable = 0x0
// 6:4, R/W, MOD_FORMAT, Modulation format. Default 2-FSK = 0x0
// 0x7 = MSK
// 3, R/W, MANCHESTER_EN, . Enable Manchester. Default disable = 0x0
// 2:0, R/W, SYNC_MODE, Combined sync-word qualifier mode. Default 16bit TX/RX sync word = 0x2
// 0x3 = repeated sync word TX, 30 of 32bit sync word bits detected RX
CC1100_CONFIG_MDMCFG1 = 0x42, // 0x13, Modem Config
// 7, R/W. FEC_EN, Enable forward error correction. Default disabled = 0x0
// 6:4, R/W, NUM_PREAMBLE, Minimum number of preable bytes. Default 4 preamble bytes = 0x2
// 0x4 = 8 preamble bytes
// 3:2, RO, not used
// 1:0, R/W, CHANSPC_E, Channel spacing exponent. Default = 0x2
CC1100_CONFIG_MDMCFG0 = 0xF8, // 0x14, Modem Config
// 7:0, R/W. CHANSPC_M, Channel spacing mantissa. Default = 0xF8
CC1100_CONFIG_DEVIATN = 0x00, // 0x15, Modem Deviation Setting
// 7, RO, not used
// 6:4, R/W, DEVIATION_E, Deviation exponent, Default = 0x4
// 3, RO, not used
// 2:1, R/W, DEVIATION_M, Depends on modulation format. Default mantissa for 2-FSK = 0x7
// For MSK specifies fraction of sample period when phase change occurs.
CC1100_CONFIG_MCSM2 = 0x07, // 0x16, Main Radio Control State Machine Config
// 7:5, RO, not used
// 4, R/W, RX_TIME_RSSI, RX termination based on RSSI (carrier sense). Default off = 0x0
// 3, R/W, RX_TIME_QUAL, When RX_TIME expires: Default checks if sync word found = 0x0. if = 0x1 checks sync word or PQI.
// 2:0, R/W, RX_TIME, Timeout for sync word search in RX for both WOR mode and normal RX operation. Default = 0x7
CC1100_CONFIG_MCSM1 = 0x3F, // 0x17, Main Radio Control State Machine Config
// 7:6, RO, not used
// 5:4, R/W, CCA_MODE, Selects CCA mode. Default channel indication if RSSI below threshold = 0x3.
// 3:2, R/W, RXOFF_MODE, When packet RX'ed Default IDLE = 0x0.
// 0x3 = stay in RX.
// 1:0, R/W, TXOFF_MODE, When packet TX'd Default IDLE = 0x0.
// 0x3 = RX
CC1100_CONFIG_MCSM0 = 0x18, // 0x18, Main Radio Control State Machine Config
// 7:6, RO, not used
// 5:4, R/W, FS_AUTOCAL, Auto calibrate. Default never = 0x0.
// 0x1 = when going from IDLE to RX or TX.
// 3:2, R/W, PO_TIMEOUT, Number of times 6bit ripple counter expires after stable XOSC, before CHP_RDYn goes low. Default 16 = 0x1
// 1, R/W, PIN_CTRL_EN, Enables pin radio control option. Default disable = 0x0
// 0, R/W, XOSC_FPRCE_ON, Force the XOSC to stay on in SLEEP state. Default off = 0x0
CC1100_CONFIG_FOCCFG = 0x1D, // 0x19, Frequency Offset Compensation Config
// 7:6, RO, not used
// 5, R/W, FOC_BS_CS_GATE, Default set = 0x1, demodulator freezes FOC and clock feedback until CS goes high.
// 4:3, R/W, FOC_PRE_K, Freq comp loog gain used before sync word detected. Default 0x2 = 3K
// 0x3 = 4K.
// 2, R/W, FOC_POST_K, Freq comp loop gain used after sync word detected. Default 0x1 = K/2
// 1:0, R/W, FOC_LIMIT, Saturation point for FOC algorithm. Default 0x2 = BW_CHAN/4
// 0x1 = BW_CHAN/8
CC1100_CONFIG_BSCFG = 0x1C, // 0x1A, Bit Sync Config
// 7:6, R/W, BS_PRE_KI, Clock recovery feedback loop integral gain before sync word. Default 2Ki = 0x1.
// 0x0 = Ki
// 5:4, R/W, BS_PRE_KP, Clock recovery feedback loop proportional gain before syn word. Default 3Kp = 0x2.
// 3, R/W, BS_POST_KI, Clock recovery feedback loop integral gain after sync word. Default Ki/2 = 0x1
// 2, R/W, BS_POST_KP, Clock recovery feedback loop proportional gain after sync word. Default Kp = 0x1
// 1:0, R/W, BS_LIMIT, Saturation point for the data rate offset compensation algorithm. Default none = 0x0
CC1100_CONFIG_AGCTRL2 = 0xC7, // 0x1B, AGC Control
// 7:6, R/W, MAX_DVGA_GAIN, Reduces max allowable DVGA gain. Default all gain can be used = 0x0
// 0x3 = 3 highest gain settings can not be used
// 5:3, R/W, MAX_LNA_GAIN, Set max allowable LNA+LNA2 gain. Default max = 0x0
// 2:0, R/W, MAGN_TARGET, Set digital channel filter average amplitude target. Default 33 dB = 0x3
// 0x7 = 42 dB
CC1100_CONFIG_AGCTRL1 = 0x00, // 0x1C, AGC Control
// 7, RO, not used
// 6, R/W, AGC_LNA_PRIORITY, LNA gain adjustment. Default 0x1 = decrease LNA first.
// 0x0 = LNA 2 decreased to min then LNA decreased.
// 5:4, R/W, CARRIER_SENSE_REL_THR, Set relative change threshold for asserting carrier sense. Default disabled = 0x0.
// 3:0, R/W, CARRIER_SENSE_ABS_THR, Set absolute RSSI threshold for asserting carrier sense. Default disabled = 0x0.
CC1100_CONFIG_AGCTRL0 = 0xB0, // 0x1D, AGC Control
// 7:6, R/W, HYST_LEVEL, Set magnitude deviation hysteresis level. Default medium = 0x2
// 5:4, R/W, WAIT_TIME, Set number of channel filter samples before AGC starts new samples. Default 16 = 0x1
// 0x3 = 32
// 3:2, R/W, AGC_FREEZE, Set when to freeze AGC gain. Default normal = 0x0.
// 1:0, R/W, FILTER_LENGTH, Set channel filter amplitude average length.
// Default 0x1 set length = 16, boundary = 8 dB.
// 0x0 set length = 8, boundary = 4 dB
CC1100_CONFIG_WOREVT1 = 0x87, // 0x1E, High Byte Event0 Timeout
// 7:0, R/W, EVENT0, High byte of EVENT0 timeout register. Default = 0x87
CC1100_CONFIG_WOREVT0 = 0x6B, // 0x1F, Low Byte Event0 Timeout
// 7:0, R/W, EVENT0, Low byte of EVENT0 timeout register. Default = 0x6B
CC1100_CONFIG_WORCTRL = 0xF8, // 0x20, Wake On Radio Control
// 7, R/W, RC_PD, Power down signal to RC osc. When 0x0 auto cal will be performed. Default = 0x1
// 6:4, R/W, EVENT1, Timeout setting from register block. Decoded to EVENT1 timeout. Default 48 = 0x7.
// 3, R/W, RC_CAL, Default enables = 0x1 or disables RC osc calibration.
// 2, RO, not used.
// 1:0, R/W, WOR_RES, Controls EVENT0 resolution, WOR max timeout and RX normal operation max timeout.
// Default 0x0 set resolution = 1 period, timeout = 1.8 - 1.9 sec.
CC1100_CONFIG_FREND1 = 0xB6, // 0x21, Front End RX Config
// 7:6, R/W, LNA_CURRENT, Adjust front-end LNA PTAT current output. Default = 0x1
// 5:4, R/W, LNA2MIX_CURRENT, Adjust front-end PTAT outputs. Default = 0x1
// 3:2, R/W, LODIC_BUF_CURRENT_RX, Adjust current in RX LO buffer. Default = 0x1
// 1:0, R/W, MIX_CURRENT, Adjusts current in mixer. Default = 0x2
CC1100_CONFIG_FREND0 = 0x10, // 0x22, Front End TX Config
// 7:6, RO, not used
// 5:4, R/W, LODIV_BUF_CURRENT_TX, Adjsut current in TX LO buffer. Default = 0x1
// 3:2, RO, not used.
// 1:0, R/W, Selects PA power setting. Default = 0x0
CC1100_CONFIG_FSCAL3 = 0xEA, // 0x23, Frequency Synthesizer Calibration
// 7:6, R/W, FSCAL3, Frequency synthesizer calibration config. Default = 0x2
// 5:4, R/W, CHP_CURR_CAL_EN, when 0x0 disable charge pump calibration stage. Default = 0x2
// 3:0, R/W, FSCAL3, Frequency synthesizer calibration result register. Default = 0x9
CC1100_CONFIG_FSCAL2 = 0x2A, // 0x24, Frequency Synthesizer Calibration
// 7:6, RO, not used
// 5, R/W, VCO_CORE_H_EN, Choose high/low VCO. Default low = 0x0
// 4:0, R/W, FSCAL2, Frequency synthesizer calibration result register. Default = 0x0A
CC1100_CONFIG_FSCAL1 = 0x00, // 0x25, Frequency Synthesizer Calibration
// 7, RO, not used
// 6:0, R/W, FSCAL1, Frequency synthesizer calibration result register. Default = 0x20
CC1100_CONFIG_FSCAL0 = 0x1F, // 0x26, Frequency Synthesizer Calibration
// 7, RO, not used
// 6:0, R/W, FSCAL0, Frequency synthesizer calibration control. Default = 0x13
CC1100_CONFIG_RCCTRL1 = 0x41, // 0x27, RC Oscillator Config
// 7, RO, not used
// 6:0, R/W, RCCTRL1, RC osc config. Default = 0x41
CC1100_CONFIG_RCCTRL0 = 0x00, // 0x28, RC Oscillator Config
// 7, RO, not used
// 6:0, R/W, RCCTRL0, RC osc config. Default = 0x00
/* Registers loose programming values in SLEEP */
CC1100_CONFIG_FSTEST = 0x59, // 0x29, Frequency Synthesizer Calibration Control
// 7:0, R/W, FSTEST, For test only. DO NOT WRITE TO THIS REGISTER. Default 0x59
CC1100_CONFIG_PTEST = 0x7F, // 0x2A, Production Test
// 7:0, R/W, PTEST, For test mostly. Write 0xBF to make temperature sensor available in IDLE.
// Write 0x7F back before leaving IDLE. Default 0x7F
CC1100_CONFIG_AGCTST = 0x3F, // 0x2B, AGC Test
// 7:0, R/W, AGCTEST, For test only. DO NOT WRITE TO THIS REGISTER. Default 0x3F
CC1100_CONFIG_TEST2 = 0x88, // 0x2D, Varoius Test Setting
// 7:0, R/W, TEST2, Value to write in register determined by SmartRF. Default 0x88
CC1100_CONFIG_TEST1 = 0x31, // 0x2E, Varoius Test Setting
// 7:0, R/W, TEST1, Value to write in register determined by SmartRF. Default 0x31
CC1100_CONFIG_TEST0 = 0x0B // 0x2F, Varoius Test Setting
// 7:2, R/W, TEST0, Value to write in register determined by SmartRF. Default 0x02
// 1, R/W, VCO_SEL_CAL_EN, Enable VCO selection calibration stage. Default enable = 0x1
// 0, R/W, TEST0, Value to write in register determined by SmartRF. Default 0x1
};
/**
* Power Amp Values: calculated using TI smart RF studio
*/
enum{
CC1100_PA_PLUS_10 = 0xC0,
CC1100_PA_PLUS_5 = 0x85,
CC1100_PA_PLUS_0 = 0x60,
CC1100_PA_MINUS_5 = 0x57,
CC1100_PA_MINUS_10 = 0x26,
};
#ifndef CC1100_PA
#define CC1100_PA CC1100_PA_PLUS_10
#endif
#ifndef CCXX00_RADIO_DEFINED
#define CCXX00_RADIO_DEFINED
#endif
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/apps/AIIT_tutorials/7_RequestSample/RequestReading.h | <gh_stars>1-10
#ifndef PRINT_SERIAL_H
#define PRINT_SERIAL_H
#include "message.h"
enum {
AM_REQUEST_READING_MSG = 0x0F,
FLAG_COUNTER = 0x01,
FLAG_VOLTAGE_READING = 0x02,
FLAG_TEMPERATURE_READING = 0x04,
FLAG_TEXT = 0x08,
MAX_TEXT_LENGTH = 18,
};
typedef nx_struct request_reading_msg {
nx_uint8_t flag;
nx_uint16_t nodeid;
nx_uint16_t counter;
nx_uint16_t voltage_reading;
nx_uint16_t temperature_reading;
nx_uint8_t buffer[MAX_TEXT_LENGTH];
} request_reading_msg_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | intelmote2/support/sdk/c/compress/decodeZeros.h | /*
* Copyright (c) 2006 Stanford University.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of the Stanford University 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 COPYRIGHT HOLDERS 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 STANFORD
* UNIVERSITY OR ITS 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.
*/
/**
* @author <NAME> (<EMAIL>)
*/
uint32_t decodeZeros(uint8_t *dataIn, unsigned char *dataOut,
uint32_t size, uint32_t maxSize)
{
uint32_t i,j, idx=0;
for (i=0; i<size; i++)
{
if ((dataIn[i]&0x80) == 0)
{
if (dataIn[i]==0)
{//zeroes until the end of the file
while (idx<maxSize)
dataOut[idx++]=0;
return idx;
}
for (j=0; j<dataIn[i]; j++)
dataOut[idx++]=0;
}
else
{
int8_t value = dataIn[i];
value = (value>-65)?(value&0x7F)-128:value&0x7F;
dataOut[idx++]=value;
}
}
return idx;
}
static inline void decodeDC(uint8_t *dataIn, uint8_t *dataOut, uint16_t dataSize)
{
uint16_t i;
dataOut[0]=dataIn[0];
for (i=1; i<dataSize; i++)
dataOut[i]=dataOut[i-1]-dataIn[i];
}
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/lib/quanto/PowerState/PowerState.h | <filename>berkeley/quanto/tos/lib/quanto/PowerState/PowerState.h
#ifndef _POWER_STATE_H
#define _POWER_STATE_H
#define POWER_STATE_UNIQUE "Power.State.Unique"
typedef uint16_t powerstate_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | diku/common/lib/compression/passthru.h | <gh_stars>1-10
#include "../../tools/compression/passthru/passthru_comp.c"
|
tinyos-io/tinyos-3.x-contrib | diku/mcs51/tos/chips/cip51/usb/cip51-usb.h | <gh_stars>1-10
/*
* Copyright (c) 2008 Polaric
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - 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.
* - Neither the name of Polaric 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 COPYRIGHT HOLDERS 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 POLARIC OR ITS 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.
*/
/**
*
* @author <NAME> <<EMAIL>>
*/
#ifndef _H_cip51usb_H
#define _H_cip51usb_H
/* Constants for USB registers */
enum {
CIP51_USBADR_FADDR = 0,
CIP51_USBADR_POWER = 0x01,
CIP51_USBADR_IN1INT = 0x02,
CIP51_USBADR_OUT1INT = 0x04,
CIP51_USBADR_CMINT = 0x06,
CIP51_USBADR_IN1IE = 0x07,
CIP51_USBADR_OUT1IE = 0x09,
CIP51_USBADR_CMIE = 0x0B,
CIP51_USBADR_FRAMEL = 0x0C,
CIP51_USBADR_FRAMEH = 0x0D,
CIP51_USBADR_INDEX = 0x0E,
CIP51_USBADR_CLKREC = 0x0F,
CIP51_USBADR_INMAX = 0x10, // Undocumented, may or may not be valid
CIP51_USBADR_E0CSR = 0x11,
CIP51_USBADR_EINCSRL = 0x11,
CIP51_USBADR_EINCSRH = 0x12,
CIP51_USBADR_OUTMAX = 0x13, // Undocumented, may or may not be valid
CIP51_USBADR_EOUTCSRL = 0x14,
CIP51_USBADR_EOUTCSRH = 0x15,
CIP51_USBADR_E0CNT = 0x16,
CIP51_USBADR_EOUTCNTL = 0x16,
CIP51_USBADR_EOUTCNTH = 0x17,
CIP51_USBADR_FIFO_EP0 = 0x20,
CIP51_USBADR_FIFO_EP1 = 0x21,
CIP51_USBADR_FIFO_EP2 = 0x22,
CIP51_USBADR_FIFO_EP3 = 0x23
};
/* Interrupt sources */
enum {
CIP51_CMINT_SOF = 0x3,
CIP51_CMINT_RSTINT = 0x2,
CIP51_CMINT_RSUINT = 0x1,
CIP51_CMINT_SUSINT = 0x0
};
enum {
CIP51_IN1INT_IN3 = 0x3,
CIP51_IN1INT_IN2 = 0x2,
CIP51_IN1INT_IN1 = 0x1,
CIP51_IN1INT_EP0 = 0x0
};
enum {
CIP51_OUT1INT_MASK = 0xE,
CIP51_OUT1INT_OUT3 = 0x3,
CIP51_OUT1INT_OUT2 = 0x2,
CIP51_OUT1INT_OUT1 = 0x1
};
/* Other register constants */
enum {
CIP51_E0CSR_SSUEND = 7,
CIP51_E0CSR_SOPRDY = 6,
CIP51_E0CSR_SDSTL = 5,
CIP51_E0CSR_SUEND = 4,
CIP51_E0CSR_DATAEND = 3,
CIP51_E0CSR_STSTL = 2,
CIP51_E0CSR_INPRDY = 1,
CIP51_E0CSR_OPRDY = 0
};
enum {
CIP51_EINCSRL_CLRDT = 6,
CIP51_EINCSRL_STSTL = 5,
CIP51_EINCSRL_SDSTL = 4,
CIP51_EINCSRL_FLUSH = 3,
CIP51_EINCSRL_UNDRUN = 2,
CIP51_EINCSRL_FIFONE = 1,
CIP51_EINCSRL_INPRDY = 0,
};
enum {
CIP51_EINCSRH_DBIEN = 7,
CIP51_EINCSRH_ISO = 6,
CIP51_EINCSRH_DIRSEL = 5,
CIP51_EINCSRH_FCDT = 3,
CIP51_EINCSRH_SPLIT = 2
};
enum {
CIP51_EOUTCSRL_CLRDT = 7,
CIP51_EOUTCSRL_STSTL = 6,
CIP51_EOUTCSRL_SDSTL = 5,
CIP51_EOUTCSRL_FLUSH = 4,
CIP51_EOUTCSRL_DATERR = 3,
CIP51_EOUTCSRL_OVRUN = 2,
CIP51_EOUTCSRL_FIFOFUL= 1,
CIP51_EOUTCSRL_OPRDY = 0
};
enum{
CIP51_EOUTCSRH_DBOEN = 0x7,
CIP51_EOUTCSRH_ISO = 0x6
};
//------------------,-----------------------------------------------------------
// Register Read/Write Macros (borrowed from SiLabs)
//-----------------------------------------------------------------------------
// These first two macros do not poll for busy, and can be used to increase
// program speed where necessary, but should never be used for successive
// reads or writes.
#define CIP51_USBREAD_BYTE(addr, target) { \
USB0ADR = (0x80 | addr); \
while(USB0ADR & 0x80); \
target = USB0DAT; }
#define CIP51_USBWRITE_BYTE(addr, data) { \
USB0ADR = (addr); \
USB0DAT = data; }
// These two macros are polling versions of the above macros, and can be
// used for successive reads writes without taking the chance that the
// Interface Engine is busy from the last register access.
#define CIP51_USBPOLL_READ_BYTE(addr, target) { \
while(USB0ADR & 0x80); \
CIP51_USBREAD_BYTE(addr, target); }
#define CIP51_USBPOLL_WRITE_BYTE(addr, dt) { \
while(USB0ADR & 0x80); \
CIP51_USBWRITE_BYTE(addr, dt); }
typedef struct {
uint8_t endpoint;
uint8_t *start;
uint16_t len;
} in_queue_item_t;
typedef struct {
uint8_t *start;
uint8_t *p;
uint16_t len;
bool more;
bool wait_done;
bool done;
} in_item_t;
#endif //_H_cip51usb_H
|
tinyos-io/tinyos-3.x-contrib | jhu/lpp/Lpp.h | #ifndef SLOWLPL_H
#define SLOWLPL_H
enum {
SLOW_LPL_AM = 10,
};
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/error.h | <reponame>tinyos-io/tinyos-3.x-contrib
/**
* NXT bootstrap interface; error handling code.
*
* Copyright 2006 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#ifndef __ERROR_H__
#define __ERROR_H__
typedef enum
{
NXT_OK = 0,
NXT_NOT_PRESENT = 1,
NXT_CONFIGURATION_ERROR = 2,
NXT_IN_USE = 3,
NXT_USB_WRITE_ERROR = 4,
NXT_USB_READ_ERROR = 5,
NXT_SAMBA_PROTOCOL_ERROR = 6,
NXT_HANDSHAKE_FAILED = 7,
NXT_FILE_ERROR = 8,
NXT_INVALID_FIRMWARE = 9,
} nxt_error_t;
const char const *nxt_str_error(nxt_error_t err);
#define NXT_ERR(expr) \
do { \
nxt_error_t nxt__err_temp = (expr); \
if (nxt__err_temp) \
return nxt__err_temp; \
} while(0)
#endif /* __ERROR_H__ */
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/sensors/baseStation/bsComm/commConfig.h | /*
* Author: <NAME>
* contact: <EMAIL>
*/
// NOTE: please "includes AM;" before including this file
#ifndef _RADIOBIGMSG_H_
#define _RADIOBIGMSG_H_
#define BIGMSG_HEADER_LENGTH 2
#define BIGMSG_DATA_SHIFT 6
#define BIGMSG_DATA_LENGTH (1<<BIGMSG_DATA_SHIFT)
#define VIDEO_DATA_LENGTH 100
#define TOSH_DATA_LENGTH (BIGMSG_HEADER_LENGTH+VIDEO_DATA_LENGTH)
enum
{
AM_RADIO_RADIOBIGMSG=7,
AM_BIGMSG_FRAME_PART=0x6E,
AM_BIGMSG_FRAME_REQUEST=0x6F,
AM_VIDEO_FRAME_PART=0x70,
};
typedef nx_struct video_frame_part{
nx_uint8_t frame_id;
nx_uint8_t part_id;
nx_uint8_t buf[VIDEO_DATA_LENGTH];
} video_frame_part_t;
typedef nx_struct bigmsg_frame_part{
nx_uint16_t part_id;
nx_uint8_t buf[BIGMSG_DATA_LENGTH];
} bigmsg_frame_part_t;
typedef nx_struct bigmsg_frame_request{
nx_uint16_t part_id;
nx_uint16_t send_next_n_parts;
} bigmsg_frame_request_t;
typedef nx_struct video_frame_request{
nx_uint8_t frame_id;
nx_uint8_t part_id;
nx_uint8_t send_next_n_parts;
} video_frame_request_t;
#endif //_RADIOBIGMSG_H_
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/chips/at45db/Storage_chip.h | // $Id: Storage_chip.h,v 1.1 2014/11/26 19:31:32 carbajor Exp $
#ifndef STORAGE_CHIP_H
#define STORAGE_CHIP_H
#include "At45db.h"
#define UQ_BLOCK_STORAGE "BlockStorageP.BlockRead"
#define UQ_LOG_STORAGE "LogStorageP.LogRead"
#define UQ_CONFIG_STORAGE "ConfigStorageP.ConfigRead"
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/apps/turtle_snapper/impl/mica2dot/SingleStream.h |
#ifndef SINGLE_STREAM_H
#define SINGLE_STREAM_H
#include "common_header.h"
#include "sizes.h"
//includes common_header;
// stream_t
typedef struct _stream
{
flashptr_t tail;
bool doEcc;
flashptr_t traverse;
} stream_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/samba.h | /**
* NXT bootstrap interface; NXT bootstrap control functions.
*
* Copyright 2006 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#ifndef __SAMBA_H__
#define __SAMBA_H__
#include <stdint.h>
#include "error.h"
#include "lowlevel.h"
typedef uint32_t nxt_addr_t;
typedef uint32_t nxt_word_t;
typedef uint16_t nxt_hword_t;
typedef unsigned char nxt_byte_t;
nxt_error_t nxt_write_byte(nxt_t *nxt, nxt_addr_t addr, nxt_byte_t b);
nxt_error_t nxt_write_hword(nxt_t *nxt, nxt_addr_t addr, nxt_hword_t hw);
nxt_error_t nxt_write_word(nxt_t *nxt, nxt_addr_t addr, nxt_word_t w);
nxt_error_t nxt_read_byte(nxt_t *nxt, nxt_addr_t addr, nxt_byte_t *b);
nxt_error_t nxt_read_hword(nxt_t *nxt, nxt_addr_t addr, nxt_hword_t *hw);
nxt_error_t nxt_read_word(nxt_t *nxt, nxt_addr_t addr, nxt_word_t *w);
nxt_error_t nxt_send_file(nxt_t *nxt, nxt_addr_t addr,
char *file, unsigned short len);
nxt_error_t nxt_recv_file(nxt_t *nxt, nxt_addr_t addr,
char *file, unsigned short len);
nxt_error_t nxt_jump(nxt_t *nxt, nxt_addr_t addr);
nxt_error_t nxt_samba_version(nxt_t *nxt, char *version);
#endif /* __SAMBA_H__ */
|
tinyos-io/tinyos-3.x-contrib | berkeley/tos/lib/print/print.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>berkeley/tos/lib/print/print.h
/*
* "Copyright (c) 2007 The Regents of the University of California.
* All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY
* PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
* DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
* CALIFORNIA HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT,
* UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
/**
* A simple printf-like utility that writes to the raw serial port
* using the standard TinyOS 2.0 UART libraries, so it should be
* portable to any T2-compliant platform.
*
* @author <NAME> <<EMAIL>>
*/
#ifndef PRINT_H
#define PRINT_H
#include <stdio.h>
#include <stdarg.h>
enum {
PRINT_BUF_SIZE = 80
};
// nesC entry point for C calls.
error_t print_rsvp();
error_t print_spool(uint8_t *buf, uint16_t len);
/**
* The nesC entry point for <code>printf</code>. Calling this from
* nesC will output the expanded <code>fmt</code> string to the mote's
* default UART with default UART parameters.
*
* @param fmt A printf-style format string: %c, %d, %s, %x supported.
* @param ... Comma-separated parameter list matching fmt parameters.
* @return SUCCESS if the call was queued for transmission.
* EBUSY if the call failed because the transport is busy.
* FAIL if the call failed for an indeterminate reason.
*/
error_t print(const char *fmt, ...) {
error_t rval;
char buf[PRINT_BUF_SIZE];
int len = 0;
va_list ap;
if (print_rsvp() == SUCCESS) {
va_start(ap, fmt);
len = vsnprintf(buf, PRINT_BUF_SIZE, fmt, ap);
va_end(ap);
if (len > -1 && len < PRINT_BUF_SIZE) {
// Fits in the buffer
}
else {
// Will get truncated
}
rval = print_spool((uint8_t*)buf, len);
}
else {
rval = EBUSY;
}
return rval;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/tos/lib/net/blip/IPDispatch.h | /*
* "Copyright (c) 2008 The Regents of the University of California.
* All rights reserved."
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
* OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
* CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
* PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
*
*/
#ifndef _IPDISPATCH_H_
#define _IPDISPATCH_H_
#include <message.h>
#include <lib6lowpan.h>
#include <Statistics.h>
enum {
N_NEXT_HOPS = 2,
N_RECONSTRUCTIONS = 3, /* number of concurrent reconstructions */
N_CONCURRENT_SENDS = 3, /* number of concurrent sends */
N_FRAGMENTS = 12, /* number of link-layer fragments to buffer */
};
typedef struct {
// The extra 2 is because one dest could be from source route, other
// from the dest being a direct neighbor
ieee154_addr_t dest[N_NEXT_HOPS];
uint8_t current:4;
uint8_t nchoices:4;
uint8_t retries;
uint8_t actRetries;
uint16_t delay;
} send_policy_t;
typedef struct {
uint8_t link_fragments;
uint8_t link_transmissions;
uint8_t refcount;
bool failed;
} send_info_t;
typedef struct {
send_info_t *info;
message_t *msg;
} send_entry_t;
typedef struct {
uint8_t timeout;
ieee154_saddr_t l2_src;
uint16_t old_tag;
uint16_t new_tag;
send_info_t *s_info;
} forward_entry_t;
typedef enum {
S_FORWARD,
S_REQ,
} send_type_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | tinybt/tos/lib/bluetooth/hci.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>tinybt/tos/lib/bluetooth/hci.h
/*
BlueZ - Bluetooth protocol stack for Linux
Copyright (C) 2000-2001 Qualcomm Incorporated
Written 2000,2001 by <NAME> <<EMAIL>>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation;
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF THIRD PARTY RIGHTS.
IN NO EVENT SHALL THE COPYRIGHT HOLDER(S) AND AUTHOR(S) BE LIABLE FOR ANY
CLAIM, OR ANY SPECIAL INDIRECT OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
ALL LIABILITY, INCLUDING LIABILITY FOR INFRINGEMENT OF ANY PATENTS,
COPYRIGHTS, TRADEMARKS OR OTHER RIGHTS, RELATING TO USE OF THIS
SOFTWARE IS DISCLAIMED.
*/
/*
* $Id: hci.h,v 1.1 2011/12/09 19:48:58 sengg Exp $
*/
#ifndef __HCI_H
#define __HCI_H
#ifdef __cplusplus
extern "C" {
#endif
#include "bluetooth.h"
#define HCI_MAX_ACL_SIZE 1024
#define HCI_MAX_SCO_SIZE 255
#define HCI_MAX_EVENT_SIZE 260
#define HCI_MAX_FRAME_SIZE (HCI_MAX_ACL_SIZE + 4)
/* HCI dev events */
#define HCI_DEV_REG 1
#define HCI_DEV_UNREG 2
#define HCI_DEV_UP 3
#define HCI_DEV_DOWN 4
#define HCI_DEV_SUSPEND 5
#define HCI_DEV_RESUME 6
/* HCI device types */
#define HCI_VHCI 0
#define HCI_USB 1
#define HCI_PCCARD 2
#define HCI_UART 3
#define HCI_RS232 4
#define HCI_PCI 5
/* HCI device flags */
enum {
HCI_UP,
HCI_INIT,
HCI_RUNNING,
HCI_PSCAN,
HCI_ISCAN,
HCI_AUTH,
HCI_ENCRYPT,
HCI_INQUIRY,
HCI_RAW
};
/* HCI ioctl defines */
#define HCIDEVUP _IOW('H', 201, int)
#define HCIDEVDOWN _IOW('H', 202, int)
#define HCIDEVRESET _IOW('H', 203, int)
#define HCIDEVRESTAT _IOW('H', 204, int)
#define HCIGETDEVLIST _IOR('H', 210, int)
#define HCIGETDEVINFO _IOR('H', 211, int)
#define HCIGETCONNLIST _IOR('H', 212, int)
#define HCIGETCONNINFO _IOR('H', 213, int)
#define HCISETRAW _IOW('H', 220, int)
#define HCISETSCAN _IOW('H', 221, int)
#define HCISETAUTH _IOW('H', 222, int)
#define HCISETENCRYPT _IOW('H', 223, int)
#define HCISETPTYPE _IOW('H', 224, int)
#define HCISETLINKPOL _IOW('H', 225, int)
#define HCISETLINKMODE _IOW('H', 226, int)
#define HCISETACLMTU _IOW('H', 227, int)
#define HCISETSCOMTU _IOW('H', 228, int)
#define HCIINQUIRY _IOR('H', 240, int)
/* HCI timeouts */
#define HCI_CONN_TIMEOUT (HZ * 40)
#define HCI_DISCONN_TIMEOUT (HZ * 2)
#define HCI_CONN_IDLE_TIMEOUT (HZ * 60)
#ifndef __NO_HCI_DEFS
/* HCI Packet types */
#define HCI_COMMAND_PKT 0x01
#define HCI_ACLDATA_PKT 0x02
#define HCI_SCODATA_PKT 0x03
#define HCI_EVENT_PKT 0x04
#define HCI_UNKNOWN_PKT 0xff
/* HCI Packet types */
#define HCI_DM1 0x0008
#define HCI_DM3 0x0400
#define HCI_DM5 0x4000
#define HCI_DH1 0x0010
#define HCI_DH3 0x0800
#define HCI_DH5 0x8000
#define HCI_HV1 0x0020
#define HCI_HV2 0x0040
#define HCI_HV3 0x0080
#define SCO_PTYPE_MASK (HCI_HV1 | HCI_HV2 | HCI_HV3)
#define ACL_PTYPE_MASK (~SCO_PTYPE_MASK)
/* ACL flags */
#define ACL_CONT 0x01
#define ACL_START 0x02
#define ACL_ACTIVE_BCAST 0x04
#define ACL_PICO_BCAST 0x08
/* Baseband links */
#define SCO_LINK 0x00
#define ACL_LINK 0x01
/* LMP features */
#define LMP_3SLOT 0x01
#define LMP_5SLOT 0x02
#define LMP_ENCRYPT 0x04
#define LMP_SOFFSET 0x08
#define LMP_TACCURACY 0x10
#define LMP_RSWITCH 0x20
#define LMP_HOLD 0x40
#define LMP_SNIFF 0x80
#define LMP_PARK 0x01
#define LMP_RSSI 0x02
#define LMP_QUALITY 0x04
#define LMP_SCO 0x08
#define LMP_HV2 0x10
#define LMP_HV3 0x20
#define LMP_ULAW 0x40
#define LMP_ALAW 0x80
#define LMP_CVSD 0x01
#define LMP_PSCHEME 0x02
#define LMP_PCONTROL 0x04
#define LMP_TRSP_SCO 0x08
/* Link policies */
#define HCI_LP_RSWITCH 0x0001
#define HCI_LP_HOLD 0x0002
#define HCI_LP_SNIFF 0x0004
#define HCI_LP_PARK 0x0008
/* Link mode */
#define HCI_LM_ACCEPT 0x8000
#define HCI_LM_MASTER 0x0001
#define HCI_LM_AUTH 0x0002
#define HCI_LM_ENCRYPT 0x0004
#define HCI_LM_TRUSTED 0x0008
/* ----- HCI Commands ----- */
/* OGF & OCF values */
/* Informational Parameters */
#define OGF_INFO_PARAM 0x04
#define OCF_READ_LOCAL_VERSION 0x0001
typedef struct {
uint8_t status;
uint8_t hci_ver;
uint16_t hci_rev;
uint8_t lmp_ver;
uint16_t manufacturer;
uint16_t lmp_subver;
} __attribute__ ((packed)) read_local_version_rp;
#define READ_LOCAL_VERSION_RP_SIZE 9
#define OCF_READ_LOCAL_FEATURES 0x0003
typedef struct {
uint8_t status;
uint8_t features[8];
} __attribute__ ((packed)) read_local_features_rp;
#define OCF_READ_BUFFER_SIZE 0x0005
typedef struct {
uint8_t status;
uint16_t acl_mtu;
uint8_t sco_mtu;
uint16_t acl_max_pkt;
uint16_t sco_max_pkt;
} __attribute__ ((packed)) read_buffer_size_rp;
#define OCF_READ_BD_ADDR 0x0009
typedef struct {
uint8_t status;
bdaddr_t bdaddr;
} __attribute__ ((packed)) read_bd_addr_rp;
/* Host Controller and Baseband */
#define OGF_HOST_CTL 0x03
#define OCF_RESET 0x0003
#define OCF_READ_PAGE_TIMEOUT 0x0017
typedef struct {
uint8_t status;
uint16_t timeout;
} __attribute__ ((packed)) read_page_timeout_rp;
#define READ_PAGE_TIMEOUT_RP_SIZE 3
#define OCF_WRITE_PAGE_TIMEOUT 0x0018
typedef struct {
uint16_t timeout;
} __attribute__ ((packed)) write_page_timeout_cp;
#define WRITE_PAGE_TIMEOUT_CP_SIZE 2
#define OCF_READ_PAGE_ACTIVITY 0x001B
typedef struct {
uint8_t status;
uint16_t interval;
uint16_t window;
} __attribute__ ((packed)) read_page_activity_rp;
#define READ_PAGE_ACTIVITY_RP_SIZE 5
#define OCF_WRITE_PAGE_ACTIVITY 0x001C
typedef struct {
uint16_t interval;
uint16_t window;
} __attribute__ ((packed)) write_page_activity_cp;
#define WRITE_PAGE_ACTIVITY_CP_SIZE 4
#define OCF_READ_INQ_ACTIVITY 0x001D
typedef struct {
uint8_t status;
uint16_t interval;
uint16_t window;
} __attribute__ ((packed)) read_inq_activity_rp;
#define READ_INQ_ACTIVITY_RP_SIZE 5
#define OCF_WRITE_INQ_ACTIVITY 0x001E
typedef struct {
uint16_t interval;
uint16_t window;
} __attribute__ ((packed)) write_inq_activity_cp;
#define WRITE_INQ_ACTIVITY_CP_SIZE 4
#define OCF_READ_LINK_SUPERVISION_TIMEOUT 0x0036
typedef struct {
uint8_t status;
uint16_t handle;
uint16_t link_sup_to;
} __attribute__ ((packed)) read_link_supervision_timeout_rp;
#define READ_LINK_SUPERVISION_TIMEOUT_RP_SIZE 5
#define OCF_WRITE_LINK_SUPERVISION_TIMEOUT 0x0037
typedef struct {
uint16_t handle;
uint16_t link_sup_to;
} __attribute__ ((packed)) write_link_supervision_timeout_cp;
#define WRITE_LINK_SUPERVISION_TIMEOUT_CP_SIZE 4
#define OCF_READ_AUTH_ENABLE 0x001F
#define OCF_WRITE_AUTH_ENABLE 0x0020
#define AUTH_DISABLED 0x00
#define AUTH_ENABLED 0x01
#define OCF_READ_ENCRYPT_MODE 0x0021
#define OCF_WRITE_ENCRYPT_MODE 0x0022
#define ENCRYPT_DISABLED 0x00
#define ENCRYPT_P2P 0x01
#define ENCRYPT_BOTH 0x02
#define OCF_WRITE_CA_TIMEOUT 0x0016
#define OCF_WRITE_PG_TIMEOUT 0x0018
#define OCF_WRITE_SCAN_ENABLE 0x001A
#define SCAN_DISABLED 0x00
#define SCAN_INQUIRY 0x01
#define SCAN_PAGE 0x02
#define OCF_SET_EVENT_FLT 0x0005
typedef struct {
uint8_t flt_type;
uint8_t cond_type;
uint8_t condition[0];
} __attribute__ ((packed)) set_event_flt_cp;
#define SET_EVENT_FLT_CP_SIZE 2
/* Filter types */
#define FLT_CLEAR_ALL 0x00
#define FLT_INQ_RESULT 0x01
#define FLT_CONN_SETUP 0x02
/* CONN_SETUP Condition types */
#define CONN_SETUP_ALLOW_ALL 0x00
#define CONN_SETUP_ALLOW_CLASS 0x01
#define CONN_SETUP_ALLOW_BDADDR 0x02
/* CONN_SETUP Conditions */
#define CONN_SETUP_AUTO_OFF 0x01
#define CONN_SETUP_AUTO_ON 0x02
#define OCF_CHANGE_LOCAL_NAME 0x0013
typedef struct {
uint8_t name[248];
} __attribute__ ((packed)) change_local_name_cp;
#define CHANGE_LOCAL_NAME_CP_SIZE 248
#define OCF_READ_LOCAL_NAME 0x0014
typedef struct {
uint8_t status;
uint8_t name[248];
} __attribute__ ((packed)) read_local_name_rp;
#define READ_LOCAL_NAME_RP_SIZE 249
#define OCF_READ_CLASS_OF_DEV 0x0023
typedef struct {
uint8_t status;
uint8_t dev_class[3];
} __attribute__ ((packed)) read_class_of_dev_rp;
#define READ_CLASS_OF_DEV_RP_SIZE 4
#define OCF_WRITE_CLASS_OF_DEV 0x0024
typedef struct {
uint8_t dev_class[3];
} __attribute__ ((packed)) write_class_of_dev_cp;
#define WRITE_CLASS_OF_DEV_CP_SIZE 3
#define OCF_HOST_BUFFER_SIZE 0x0033
typedef struct {
uint16_t acl_mtu;
uint8_t sco_mtu;
uint16_t acl_max_pkt;
uint16_t sco_max_pkt;
} __attribute__ ((packed)) host_buffer_size_cp;
#define HOST_BUFFER_SIZE_CP_SIZE 7
#define MAX_IAC_LAP 0x40
#define OCF_READ_CURRENT_IAC_LAP 0x0039
typedef struct {
uint8_t status;
uint8_t num_current_iac;
uint8_t lap[3][MAX_IAC_LAP];
} __attribute__ ((packed)) read_current_iac_lap_rp;
#define READ_CURRENT_IAC_LAP_RP_SIZE 2+3*MAX_IAC_LAP
#define OCF_WRITE_CURRENT_IAC_LAP 0x003A
typedef struct {
uint8_t num_current_iac;
uint8_t lap[3][MAX_IAC_LAP];
} __attribute__ ((packed)) write_current_iac_lap_cp;
#define WRITE_CURRENT_IAC_LAP_CP_SIZE 1+3*MAX_IAC_LAP
#define OCF_WRITE_INQUIRY_MODE 0x0045
#define INQUIRY_MODE_STD 0x00
#define INQUIRY_MODE_RSSI 0x01
/* Link Control */
#define OGF_LINK_CTL 0x01
#define OCF_INQUIRY_CANCEL 0x0002
#define OCF_INQUIRY 0x0001
typedef struct {
uint8_t lap[3];
uint8_t length;
uint8_t num_rsp;
} __attribute__ ((packed)) inquiry_cp;
#define INQUIRY_CP_SIZE 5
#define OCF_CREATE_CONN 0x0005
typedef struct {
bdaddr_t bdaddr;
uint16_t pkt_type;
uint8_t pscan_rep_mode;
uint8_t pscan_mode;
uint16_t clock_offset;
uint8_t role_switch;
} __attribute__ ((packed)) create_conn_cp;
#define CREATE_CONN_CP_SIZE 13
#define OCF_DISCONNECT 0x0006
typedef struct {
uint16_t handle;
uint8_t reason;
} __attribute__ ((packed)) disconnect_cp;
#define DISCONNECT_CP_SIZE 3
#define OCF_ACCEPT_CONN_REQ 0x0009
typedef struct {
bdaddr_t bdaddr;
uint8_t role;
} __attribute__ ((packed)) accept_conn_req_cp;
#define ACCEPT_CONN_REQ_CP_SIZE 7
#define OCF_REJECT_CONN_REQ 0x000a
typedef struct {
bdaddr_t bdaddr;
uint8_t reason;
} __attribute__ ((packed)) reject_conn_req_cp;
#define REJECT_CONN_REQ_CP_SIZE 7
#define OCF_ADD_SCO 0x0007
typedef struct {
uint16_t handle;
uint16_t pkt_type;
} __attribute__ ((packed)) add_sco_cp;
#define ADD_SCO_CP_SIZE 4
#define OCF_LINK_KEY_REPLY 0x000B
#define OCF_LINK_KEY_NEG_REPLY 0x000C
typedef struct {
bdaddr_t bdaddr;
uint8_t link_key[16];
} __attribute__ ((packed)) link_key_reply_cp;
#define LINK_KEY_REPLY_CP_SIZE 22
#define OCF_PIN_CODE_REPLY 0x000D
#define OCF_PIN_CODE_NEG_REPLY 0x000E
typedef struct {
bdaddr_t bdaddr;
uint8_t pin_len;
uint8_t pin_code[16];
} __attribute__ ((packed)) pin_code_reply_cp;
#define PIN_CODE_REPLY_CP_SIZE 23
#define OCF_SET_CONN_PTYPE 0x000F
typedef struct {
uint16_t handle;
uint16_t pkt_type;
} __attribute__ ((packed)) set_conn_ptype_cp;
#define SET_CONN_PTYPE_CP_SIZE 4
#define OCF_AUTH_REQUESTED 0x0011
typedef struct {
uint16_t handle;
} __attribute__ ((packed)) auth_requested_cp;
#define AUTH_REQUESTED_CP_SIZE 2
#define OCF_SET_CONN_ENCRYPT 0x0013
typedef struct {
uint16_t handle;
uint8_t encrypt;
} __attribute__ ((packed)) set_conn_encrypt_cp;
#define SET_CONN_ENCRYPT_CP_SIZE 3
#define OCF_REMOTE_NAME_REQ 0x0019
typedef struct {
bdaddr_t bdaddr;
uint8_t pscan_rep_mode;
uint8_t pscan_mode;
uint16_t clock_offset;
} __attribute__ ((packed)) remote_name_req_cp;
#define REMOTE_NAME_REQ_CP_SIZE 10
#define OCF_READ_REMOTE_FEATURES 0x001B
typedef struct {
uint16_t handle;
} __attribute__ ((packed)) read_remote_features_cp;
#define READ_REMOTE_FEATURES_CP_SIZE 2
#define OCF_READ_REMOTE_VERSION 0x001D
typedef struct {
uint16_t handle;
} __attribute__ ((packed)) read_remote_version_cp;
#define READ_REMOTE_VERSION_CP_SIZE 2
/* Link Policy */
#define OGF_LINK_POLICY 0x02
#define OCF_SNIFF_MODE 0x0003
typedef struct {
uint16_t handle;
uint16_t max_interval;
uint16_t min_interval;
uint16_t attempt;
uint16_t timeout;
} __attribute__ ((packed)) sniff_mode_cp;
#define SNIFF_MODE_CP_SIZE 10
#define OCF_ROLE_DISCOVERY 0x0009
typedef struct {
uint16_t handle;
} __attribute__ ((packed)) role_discovery_cp;
#define ROLE_DISCOVERY_CP_SIZE 2
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t role;
} __attribute__ ((packed)) role_discovery_rp;
#define ROLE_DISCOVERY_RP_SIZE 4
#define OCF_READ_LINK_POLICY 0x000C
typedef struct {
uint16_t handle;
} __attribute__ ((packed)) read_link_policy_cp;
#define READ_LINK_POLICY_CP_SIZE 2
typedef struct {
uint8_t status;
uint16_t handle;
uint16_t policy;
} __attribute__ ((packed)) read_link_policy_rp;
#define READ_LINK_POLICY_RP_SIZE 5
#define OCF_SWITCH_ROLE 0x000B
typedef struct {
bdaddr_t bdaddr;
uint8_t role;
} __attribute__ ((packed)) switch_role_cp;
#define SWITCH_ROLE_CP_SIZE 7
#define OCF_WRITE_LINK_POLICY 0x000D
typedef struct {
uint16_t handle;
uint16_t policy;
} __attribute__ ((packed)) write_link_policy_cp;
#define WRITE_LINK_POLICY_CP_SIZE 4
typedef struct {
uint8_t status;
uint16_t handle;
} __attribute__ ((packed)) write_link_policy_rp;
#define WRITE_LINK_POLICY_RP_SIZE 3
/* Status params */
#define OGF_STATUS_PARAM 0x05
#define OCF_READ_FAILED_CONTACT_COUNTER 0x0001
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t counter;
} __attribute__ ((packed)) read_failed_contact_counter_rp;
#define READ_FAILED_CONTACT_COUNTER_RP_SIZE 4
#define OCF_RESET_FAILED_CONTACT_COUNTER 0x0002
typedef struct {
uint8_t status;
uint16_t handle;
} __attribute__ ((packed)) reset_failed_contact_counter_rp;
#define OCF_RESET_FAILED_CONTACT_COUNTER_RP_SIZE 4
#define OCF_GET_LINK_QUALITY 0x0003
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t link_quality;
} __attribute__ ((packed)) get_link_quality_rp;
#define GET_LINK_QUALITY_RP_SIZE 4
#define OCF_READ_RSSI 0x0005
typedef struct {
uint8_t status;
uint16_t handle;
int8_t rssi;
} __attribute__ ((packed)) read_rssi_rp;
#define READ_RSSI_RP_SIZE 4
#define OCF_SET_FLOW_CONTROL 0x0031
#define OGF_VENDOR_SPECIFIC 0x3f
/* ---- HCI Events ---- */
#define EVT_INQUIRY_COMPLETE 0x01
#define EVT_INQUIRY_RESULT 0x02
typedef struct {
bdaddr_t bdaddr;
uint8_t pscan_rep_mode;
uint8_t reserved1;
uint8_t reserved2;
uint8_t dev_class[3];
uint16_t clock_offset;
} __attribute__ ((packed)) inquiry_info;
#define INQUIRY_INFO_SIZE 14
#define EVT_CONN_COMPLETE 0x03
typedef struct {
uint8_t status;
uint16_t handle;
bdaddr_t bdaddr;
uint8_t link_type;
uint8_t encr_mode;
} __attribute__ ((packed)) evt_conn_complete;
#define EVT_CONN_COMPLETE_SIZE 13
#define EVT_CONN_REQUEST 0x04
typedef struct {
bdaddr_t bdaddr;
uint8_t dev_class[3];
uint8_t link_type;
} __attribute__ ((packed)) evt_conn_request;
#define EVT_CONN_REQUEST_SIZE 10
#define EVT_DISCONN_COMPLETE 0x05
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t reason;
} __attribute__ ((packed)) evt_disconn_complete;
#define EVT_DISCONN_COMPLETE_SIZE 4
#define EVT_AUTH_COMPLETE 0x06
typedef struct {
uint8_t status;
uint16_t handle;
} __attribute__ ((packed)) evt_auth_complete;
#define EVT_AUTH_COMPLETE_SIZE 3
#define EVT_REMOTE_NAME_REQ_COMPLETE 0x07
typedef struct {
uint8_t status;
bdaddr_t bdaddr;
uint8_t name[248];
} __attribute__ ((packed)) evt_remote_name_req_complete;
#define EVT_REMOTE_NAME_REQ_COMPLETE_SIZE 255
#define EVT_ENCRYPT_CHANGE 0x08
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t encrypt;
} __attribute__ ((packed)) evt_encrypt_change;
#define EVT_ENCRYPT_CHANGE_SIZE 5
#define EVT_QOS_SETUP_COMPLETE 0x0D
typedef struct {
uint8_t service_type;
uint32_t token_rate;
uint32_t peak_bandwidth;
uint32_t latency;
uint32_t delay_variation;
} __attribute__ ((packed)) hci_qos;
typedef struct {
uint8_t status;
uint16_t handle;
hci_qos qos;
} __attribute__ ((packed)) evt_qos_setup_complete;
#define EVT_QOS_SETUP_COMPLETE_SIZE 20
#define EVT_CMD_COMPLETE 0x0e
typedef struct {
uint8_t ncmd;
uint16_t opcode;
} __attribute__ ((packed)) evt_cmd_complete;
#define EVT_CMD_COMPLETE_SIZE 3
#define EVT_CMD_STATUS 0x0f
typedef struct {
uint8_t status;
uint8_t ncmd;
uint16_t opcode;
} __attribute__ ((packed)) evt_cmd_status;
#define EVT_CMD_STATUS_SIZE 4
#define EVT_HW_ERROR 0x10
typedef struct {
uint8_t code;
} __attribute__ ((packed)) evt_hw_error;
#define EVT_HW_ERROR_SIZE 1
#define EVT_ROLE_CHANGE 0x12
typedef struct {
uint8_t status;
bdaddr_t bdaddr;
uint8_t role;
} __attribute__ ((packed)) evt_role_change;
#define EVT_ROLE_CHANGE_SIZE 8
#define EVT_NUM_COMP_PKTS 0x13
typedef struct {
uint8_t num_hndl;
/* Two arrays of num_hndl length
uint16_t connection_handle[num_nndl]
uint16_t num_completed_pkts[num_hndl]
*/
} __attribute__ ((packed)) evt_num_comp_pkts;
#define EVT_NUM_COMP_PKTS_SIZE 1
#define EVT_MODE_CHANGE 0x14
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t cur_mode;
uint16_t interval;
} __attribute__ ((packed)) evt_mode_change;
#define EVT_MODE_CHANGE_SIZE 6
#define EVT_PIN_CODE_REQ 0x16
typedef struct {
bdaddr_t bdaddr;
} __attribute__ ((packed)) evt_pin_code_req;
#define EVT_PIN_CODE_REQ_SIZE 6
#define EVT_LINK_KEY_REQ 0x17
typedef struct {
bdaddr_t bdaddr;
} __attribute__ ((packed)) evt_link_key_req;
#define EVT_LINK_KEY_REQ_SIZE 6
#define EVT_LINK_KEY_NOTIFY 0x18
typedef struct {
bdaddr_t bdaddr;
uint8_t link_key[16];
uint8_t key_type;
} __attribute__ ((packed)) evt_link_key_notify;
#define EVT_LINK_KEY_NOTIFY_SIZE 23
#define EVT_MAX_SLOTS_CHANGE 0x1B
typedef struct {
uint16_t handle;
uint8_t lmp_max_slots;
} __attribute__ ((packed)) evt_max_slots_change;
#define EVT_MAX_SLOTS_CHANGE_SIZE 3
#define EVT_CONN_PTYPE_CHANGED 0x1D
typedef struct {
uint8_t status;
uint16_t handle;
uint16_t ptype;
} __attribute__ ((packed)) evt_conn_ptype_changed;
#define EVT_CONN_PTYPE_CHANGED_SIZE 5
#define EVT_READ_REMOTE_FEATURES_COMPLETE 0x0B
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t features[8];
} __attribute__ ((packed)) evt_read_remote_features_complete;
#define EVT_READ_REMOTE_FEATURES_COMPLETE_SIZE 11
#define EVT_READ_REMOTE_VERSION_COMPLETE 0x0C
typedef struct {
uint8_t status;
uint16_t handle;
uint8_t lmp_ver;
uint16_t manufacturer;
uint16_t lmp_subver;
} __attribute__ ((packed)) evt_read_remote_version_complete;
#define EVT_READ_REMOTE_VERSION_COMPLETE_SIZE 8
#define EVT_INQUIRY_RSSI_RESULT 0x22
typedef struct {
bdaddr_t bdaddr;
uint8_t pscan_rep_mode;
uint8_t reserved;
uint8_t dev_class[3];
uint16_t clock_offset;
uint8_t rssi;
} __attribute__ ((packed)) inquiry_rssi_info;
#define INQUIRY_RSSI_INFO_SIZE 14
/* Internal events generated by BlueZ stack */
#define EVT_STACK_INTERNAL 0xfd
typedef struct {
uint16_t type;
uint8_t data[0];
} __attribute__ ((packed)) evt_stack_internal;
#define EVT_STACK_INTERNAL_SIZE 2
#define EVT_SI_DEVICE 0x01
typedef struct {
uint16_t evt;
uint16_t dev_id;
} __attribute__ ((packed)) evt_si_device;
#define EVT_SI_DEVICE_SIZE 4
#define EVT_SI_SECURITY 0x02
typedef struct {
uint16_t evt;
uint16_t proto;
uint16_t subproto;
uint8_t incomming;
} __attribute__ ((packed)) evt_si_security;
#define EVT_VENDOR_SPECIFIC 0x0C
/* -------- HCI Packet structures -------- */
#define HCI_TYPE_LEN 1
typedef struct {
uint16_t opcode; /* OCF & OGF */
uint8_t plen;
} __attribute__ ((packed)) hci_command_hdr;
#define HCI_COMMAND_HDR_SIZE 3
typedef struct {
uint8_t evt;
uint8_t plen;
} __attribute__ ((packed)) hci_event_hdr;
#define HCI_EVENT_HDR_SIZE 2
typedef struct {
int handle:12;
int pb:2;
int bc:2; // High order bits
uint16_t dlen;
} __attribute__ ((packed)) hci_acl_hdr;
#define HCI_ACL_HDR_SIZE 4
typedef struct {
uint16_t handle;
uint8_t dlen;
} __attribute__ ((packed)) hci_sco_hdr;
#define HCI_SCO_HDR_SIZE 3
/* Command opcode pack/unpack */
// Nicked from glibc
#ifndef __bswap_16
#define __bswap_16(x) ((((x) >> 8) & 0xff) | (((x) & 0xff) << 8))
#endif
#define cmd_opcode_pack(ogf, ocf) (uint16_t)((ocf & 0x03ff)|(ogf << 10))
#define cmd_opcode_ogf(op) (op >> 10)
#define cmd_opcode_ocf(op) (op & 0x03ff)
/* ACL handle and flags pack/unpack */
#define acl_handle_pack(h, f) (uint16_t)((h & 0x0fff)|(f << 12))
#define acl_handle(h) (h & 0x0fff)
#define acl_flags(h) (h >> 12)
#endif /* _NO_HCI_DEFS */
/* HCI Socket options */
#define HCI_DATA_DIR 1
#define HCI_FILTER 2
#define HCI_TIME_STAMP 3
/* HCI CMSG flags */
#define HCI_CMSG_DIR 0x0001
#define HCI_CMSG_TSTAMP 0x0002
/*
struct sockaddr_hci {
sa_family_t hci_family;
unsigned short hci_dev;
};
#define HCI_DEV_NONE 0xffff
*/
struct hci_filter {
uint32_t type_mask;
uint32_t event_mask[2];
uint16_t opcode;
};
#define HCI_FLT_TYPE_BITS 31
#define HCI_FLT_EVENT_BITS 63
#define HCI_FLT_OGF_BITS 63
#define HCI_FLT_OCF_BITS 127
/* Ioctl requests structures */
struct hci_dev_stats {
uint32_t err_rx;
uint32_t err_tx;
uint32_t cmd_tx;
uint32_t evt_rx;
uint32_t acl_tx;
uint32_t acl_rx;
uint32_t sco_tx;
uint32_t sco_rx;
uint32_t byte_rx;
uint32_t byte_tx;
};
struct hci_dev_info {
uint16_t dev_id;
char name[8];
bdaddr_t bdaddr;
uint32_t flags;
uint8_t type;
uint8_t features[8];
uint32_t pkt_type;
uint32_t link_policy;
uint32_t link_mode;
uint16_t acl_mtu;
uint16_t acl_pkts;
uint16_t sco_mtu;
uint16_t sco_pkts;
struct hci_dev_stats stat;
};
struct hci_conn_info {
uint16_t handle;
bdaddr_t bdaddr;
uint8_t type;
uint8_t out;
uint16_t state;
uint32_t link_mode;
};
struct hci_dev_req {
uint16_t dev_id;
uint32_t dev_opt;
};
struct hci_dev_list_req {
uint16_t dev_num;
struct hci_dev_req dev_req[0]; /* hci_dev_req structures */
};
struct hci_conn_list_req {
uint16_t dev_id;
uint16_t conn_num;
struct hci_conn_info conn_info[0];
};
struct hci_conn_info_req {
bdaddr_t bdaddr;
uint8_t type;
struct hci_conn_info conn_info[0];
};
struct hci_inquiry_req {
uint16_t dev_id;
uint16_t flags;
uint8_t lap[3];
uint8_t length;
uint8_t num_rsp;
};
#define IREQ_CACHE_FLUSH 0x0001
struct hci_remotename_req {
uint16_t dev_id;
uint16_t flags;
bdaddr_t bdaddr;
uint8_t name[248];
};
#ifdef __cplusplus
}
#endif
#endif /* __HCI_H */
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/reset_endpoint.c | /* LIBUSB-WIN32, Generic Windows USB Library
* Copyright (c) 2002-2005 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "libusb_driver.h"
NTSTATUS reset_endpoint(libusb_device_t *dev, int endpoint, int timeout)
{
NTSTATUS status = STATUS_SUCCESS;
URB urb;
DEBUG_PRINT_NL();
DEBUG_MESSAGE("reset_endpoint(): endpoint 0x%02x", endpoint);
DEBUG_MESSAGE("reset_endpoint(): timeout %d", timeout);
if(!dev->config.value)
{
DEBUG_ERROR("reset_endpoint(): invalid configuration 0");
return STATUS_INVALID_DEVICE_STATE;
}
memset(&urb, 0, sizeof(struct _URB_PIPE_REQUEST));
urb.UrbHeader.Length = (USHORT) sizeof(struct _URB_PIPE_REQUEST);
urb.UrbHeader.Function = URB_FUNCTION_RESET_PIPE;
if(!get_pipe_handle(dev, endpoint, &urb.UrbPipeRequest.PipeHandle))
{
DEBUG_ERROR("reset_endpoint(): getting endpoint pipe failed");
return STATUS_INVALID_PARAMETER;
}
status = call_usbd(dev, &urb, IOCTL_INTERNAL_USB_SUBMIT_URB, timeout);
if(!NT_SUCCESS(status) || !USBD_SUCCESS(urb.UrbHeader.Status))
{
DEBUG_ERROR("reset_endpoint(): request failed: status: 0x%x, "
"urb-status: 0x%x", status, urb.UrbHeader.Status);
}
return status;
}
|
tinyos-io/tinyos-3.x-contrib | ethz/meshbean900/tos/platforms/meshbean/chips/atm1281/usart/Atm1281Usart.h | /*
* Copyright (c) 2004-2005 Crossbow Technology, Inc. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose, without fee, and without written agreement is
* hereby granted, provided that the above copyright notice, the following
* two paragraphs and the author appear in all copies of this software.
*
* IN NO EVENT SHALL CROSSBOW TECHNOLOGY OR ANY OF ITS LICENSORS BE LIABLE TO
* ANY PARTY FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
* DAMAGES ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF CROSSBOW OR ITS LICENSOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* CROSSBOW TECHNOLOGY AND ITS LICENSORS SPECIFICALLY DISCLAIM ALL WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
* AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
* ON AN "AS IS" BASIS, AND NEITHER CROSSBOW NOR ANY LICENSOR HAS ANY
* OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
* MODIFICATIONS.
*/
// @author <NAME> <<EMAIL>>
// @author <NAME> <<EMAIL>> (Atmega1281 port)
#ifndef _H_Atm1281Usart_h
#define _H_Atm1281Usart_h
#define ATM1281_HPLUSART0_RESOURCE "Atm1281Usart0.Resource"
#define ATM1281_SPIO_BUS "Atm1281Spi0.Resource"
#define ATM1281_UARTO_BUS "Atm1281Uart0.Resource"
#define ATM1281_HPLUSART1_RESOURCE "Atm1281Usart1.Resource"
#define ATM1281_SPI1_BUS "Atm1281Spi1.Resource"
#define ATM1281_UART1_BUS "Atm1281Uart1.Resource"
//====================== USART Bus ==================================
/* USART Status Register */
typedef union {
struct Atm1281_UCSRA_t {
uint8_t mpcm : 1; //!< USART Multiprocessor Communication Mode
uint8_t u2x : 1; //!< USART Double Transmission Speed
uint8_t upe : 1; //!< USART Parity Error
uint8_t dor : 1; //!< USART Data Overrun
uint8_t fe : 1; //!< USART Frame Error
uint8_t udre : 1; //!< USART Data Register Empty
uint8_t txc : 1; //!< USART Transfer Complete
uint8_t rxc : 1; //!< USART Receive Complete
} bits;
uint8_t flat;
} Atm1281UsartStatus_t;
/* USART Control Register */
typedef union {
struct Atm1281_UCSRB_t {
uint8_t txb8 : 1; //!< USART Transmit Data Bit 8
uint8_t rxb8 : 1; //!< USART Receive Data Bit 8
uint8_t ucsz2 : 1; //!< USART Character Size (Bit 2)
uint8_t txen : 1; //!< USART Transmitter Enable
uint8_t rxen : 1; //!< USART Receiver Enable
uint8_t udrie : 1; //!< USART Data Register Enable
uint8_t txcie : 1; //!< USART TX Complete Interrupt Enable
uint8_t rxcie : 1; //!< USART RX Complete Interrupt Enable
} bits;
uint8_t flat;
} Atm1281UsartControl_t;
enum {
ATM1281_UART_DATA_SIZE_5_BITS = 0,
ATM1281_UART_DATA_SIZE_6_BITS = 1,
ATM1281_UART_DATA_SIZE_7_BITS = 2,
ATM1281_UART_DATA_SIZE_8_BITS = 3,
};
/* USART Control Register */
typedef union {
uint8_t flat;
struct Atm1281_UCSRC_t {
uint8_t ucpol : 1; //!< USART Clock Polarity
uint8_t ucsz : 2; //!< USART Character Size (Bits 0 and 1)
uint8_t usbs : 1; //!< USART Stop Bit Select
uint8_t upm : 2; //!< USART Parity Mode
uint8_t umsel : 2; //!< USART Mode Select
} bits;
} Atm1281UsartMode_t;
/*
* ATmega1281 USART baud register settings:
* ATM1281_<baudRate>_BAUD_<cpuSpeed>
*/
enum {
ATM1281_4800_BAUD_1MHZ = 12,
ATM1281_9600_BAUD_1MHZ = 6,
ATM1281_19200_BAUD_1MHZ = 2,
ATM1281_38400_BAUD_1MHZ = 1,
ATM1281_57600_BAUD_1MHZ = 0,
ATM1281_4800_BAUD_1MHZ_2X = 25,
ATM1281_9600_BAUD_1MHZ_2X = 12,
ATM1281_19200_BAUD_1MHZ_2X = 25,
ATM1281_38400_BAUD_1MHZ_2X = 2,
ATM1281_57600_BAUD_1MHZ_2X = 1,
ATM1281_4800_BAUD_4MHZ = 51,
ATM1281_9600_BAUD_4MHZ = 25,
ATM1281_19200_BAUD_4MHZ = 12,
ATM1281_38400_BAUD_4MHZ = 6,
ATM1281_57600_BAUD_4MHZ = 3,
ATM1281_115200_BAUD_4MHZ = 1,
ATM1281_4800_BAUD_4MHZ_2X = 103,
ATM1281_9600_BAUD_4MHZ_2X = 51,
ATM1281_19200_BAUD_4MHZ_2X = 25,
ATM1281_38400_BAUD_4MHZ_2X = 12,
ATM1281_57600_BAUD_4MHZ_2X = 8,
ATM1281_115200_BAUD_4MHZ_2X = 3,
ATM1281_4800_BAUD_7MHZ = 95,
ATM1281_9600_BAUD_7MHZ = 47,
ATM1281_19200_BAUD_7MHZ = 23,
ATM1281_38400_BAUD_7MHZ = 11,
ATM1281_57600_BAUD_7MHZ = 7,
ATM1281_115200_BAUD_7MHZ = 3,
ATM1281_4800_BAUD_7MHZ_2X = 191,
ATM1281_9600_BAUD_7MHZ_2X = 95,
ATM1281_19200_BAUD_7MHZ_2X = 47,
ATM1281_38400_BAUD_7MHZ_2X = 23,
ATM1281_57600_BAUD_7MHZ_2X = 15,
ATM1281_115200_BAUD_7MHZ_2X = 7,
ATM1281_4800_BAUD_8MHZ = 103,
ATM1281_9600_BAUD_8MHZ = 51,
ATM1281_19200_BAUD_8MHZ = 25,
ATM1281_38400_BAUD_8MHZ = 12,
ATM1281_57600_BAUD_8MHZ = 8,
ATM1281_115200_BAUD_8MHZ = 3,
ATM1281_4800_BAUD_8MHZ_2X = 207,
ATM1281_9600_BAUD_8MHZ_2X = 103,
ATM1281_19200_BAUD_8MHZ_2X = 51,
ATM1281_38400_BAUD_8MHZ_2X = 25,
ATM1281_57600_BAUD_8MHZ_2X = 16,
ATM1281_115200_BAUD_8MHZ_2X = 8,
};
typedef struct {
uint16_t ubr : 16; // USART baud rate
uint8_t mpcm : 1; // USART Multiprocessor Communication Mode
uint8_t u2x : 1; // USART Double Transmission Speed
uint8_t : 1;
uint8_t : 1;
uint8_t : 1;
uint8_t : 1;
uint8_t : 1;
uint8_t : 1;
uint8_t txb8 : 1; // USART Transmit Data Bit 8
uint8_t rxb8 : 1; // USART Receive Data Bit 8
uint8_t ucsz2 : 1; // USART Character Size (Bit 2)
uint8_t txen : 1; // USART Transmitter Enable
uint8_t rxen : 1; // USART Receiver Enable
uint8_t udrie : 1; // USART Data Register Enable
uint8_t txcie : 1; // USART TX Complete Interrupt Enable
uint8_t rxcie : 1; // USART RX Complete Interrupt Enable
uint8_t ucpol : 1; // USART Clock Polarity
uint8_t ucsz : 2; // USART Character Size (Bits 0 and 1)
uint8_t usbs : 1; // USART Stop Bit Select
uint8_t upm : 2; // USART Parity Mode
uint8_t umsel : 2; // USART Mode Select
} Atm1281UartConfig_t;
typedef struct {
uint8_t UBBRL;
uint8_t UBBRH;
uint8_t UCSRA;
uint8_t UCSRB;
uint8_t UCSRC;
} Atm1281UartRegisters_t;
typedef union {
Atm1281UartConfig_t uartConfig;
Atm1281UartRegisters_t uartRegisters;
} Atm1281UartUnionConfig_t;
Atm1281UartUnionConfig_t atm1281_uart_default_config = {{
#if MHZ == 8
#if PLATFORM_BAUDRATE == 115200L
ubr : ATM1281_115200_BAUD_8MHZ_2X,
#elif PLATFORM_BAUDRATE == 57600L
ubr : ATM1281_57600_BAUD_8MHZ_2X,
#elif PLATFORM_BAUDRATE == 38400L
ubr : ATM1281_38400_BAUD_8MHZ_2X,
#elif PLATFORM_BAUDRATE == 19200L
ubr : ATM1281_19200_BAUD_8MHZ_2X,
#endif
#elif MHZ == 4
#if PLATFORM_BAUDRATE == 115200L
ubr : ATM1281_115200_BAUD_4MHZ_2X,
#elif PLATFORM_BAUDRATE == 57600L
ubr : ATM1281_57600_BAUD_4MHZ_2X,
#elif PLATFORM_BAUDRATE == 38400L
ubr : ATM1281_38400_BAUD_4MHZ_2X,
#elif PLATFORM_BAUDRATE == 19200L
ubr : ATM1281_19200_BAUD_4MHZ_2X,
#endif
#elif MHZ == 1
#if PLATFORM_BAUDRATE == 57600L
ubr : ATM1281_57600_BAUD_1MHZ_2X,
#elif PLATFORM_BAUDRATE == 38400L
ubr : ATM1281_38400_BAUD_1MHZ_2X,
#elif PLATFORM_BAUDRATE == 19200L
ubr : ATM1281_19200_BAUD_1MHZ_2X,
#endif
#else
#error "Unsupported settings for MHZ/PLATFORM_BAUDRATE, see Atm1281Usart.h"
#endif
mpcm : 0, // ignored
u2x : 1, // USART Double Transmission Speed
txb8 : 0, // ignored
rxb8 : 0, // ignored
ucsz2 : 0, // 8-bit data
txen : 1, // USART Transmitter Enable
rxen : 1, // USART Receiver Enable
udrie : 0, // no data register empty interrupt
txcie : 0, // USART TX Complete Interrupt Enable
rxcie : 0, // USART RX Complete Interrupt Enable
ucpol : 0, // not used for asynchronous mode
ucsz : 3, // 8-bit data
usbs : 0, // 1 stop bit
upm : 0, // No parity
umsel : 0, // Asynchronous UART
}};
typedef struct {
uint16_t ubr : 16; // SPI baud rate
uint8_t : 8;
uint8_t : 3; // Reserved bits in SPI mode
uint8_t txen : 1; // USART Transmitter Enable
uint8_t rxen : 1; // USART Receiver Enable
uint8_t udrie : 1; // USART Data Register Enable
uint8_t txcie : 1; // USART TX Complete Interrupt Enable
uint8_t rxcie : 1; // USART RX Complete Interrupt Enable
uint8_t ucpol : 1; // SPI Clock Polarity
uint8_t ucpha : 1; // SPI Clock Phase
uint8_t udord : 1; // SPI Data Order
uint8_t : 3; // Reserved bits in SPI mode
uint8_t umsel : 2; // USART Mode Select
} Atm1281SpiConfig_t;
typedef struct {
uint8_t UBBRL;
uint8_t UBBRH;
uint8_t UCSRA;
uint8_t UCSRB;
uint8_t UCSRC;
} Atm1281SpiRegisters_t;
typedef union {
Atm1281SpiConfig_t uartConfig;
Atm1281SpiRegisters_t uartRegisters;
} Atm1281SpiUnionConfig_t;
Atm1281SpiUnionConfig_t atm1281_spi_default_config = {{
ubr : 8, // 1 MHz speed
txen : 1, // USART Transmitter Enable
rxen : 1, // USART Receiver Enable
udrie : 0, // no data register empty interrupt
txcie : 0, // USART TX Complete Interrupt Enable
rxcie : 0, // USART RX Complete Interrupt Enable
ucpol : 0, // clock polarity
ucpha : 0, // clock phase
udord : 0, // data order (0=MSB, 1=LSB)
umsel : 3, // Master SPI
}};
#endif // H_Atm1281Usart_h
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/debug/m_printf.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>tinymulle/tos/platforms/mulle/debug/m_printf.h
/*
Copyright 2001, 2002 <NAME> (www.menie.org)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
/**
* The file is a debug tool for the Mull-TinyOS platform. To use this tool,
* just need 2 steps.
* First, add #inclued "m_printf.h" to your component.
* Sencond, use _printf() function in the m_printf.h to print what you want
* to see.
* attention: don't forget to start your serialport, and just initialization.
* The serialport baudrate is at 57600, and you can choose a terminal to watch
* the output, for example, cutecom in linux.
* For more information see www.eistec.se.
*
* Modification to adopt printf for tinymulle is made by
* @author <NAME>
* @author <NAME>
*/
#ifndef _M_PRINTF_H
#define _M_PRINTF_H
#include <stdarg.h>
#include <string.h>
/*
* void m16c62p_putc(int c) is for the m16c62p. send a char through
* serial port 1.
*/
void m16c62p_putc(int c)
{
while(U1C1.BIT.TI == 0); // wait for transmit buffer empty flag
U1TB.BYTE.U1TBL = c;
}
#define putchar(c) m16c62p_putc(c)
static void printchar(char **str, int c)
{
//extern int putchar(int c);
if (str) {
**str = c;
++(*str);
}
else (void)putchar(c);
}
#define PAD_RIGHT 1
#define PAD_ZERO 2
static int prints(char **out, const char *string, int width, int pad)
{
register int pc = 0, padchar = ' ';
if (width > 0)
{
register int len = 0;
register const char *ptr;
for (ptr = string; *ptr; ++ptr) ++len;
if (len >= width) width = 0;
else width -= len;
if (pad & PAD_ZERO) padchar = '0';
}
if (!(pad & PAD_RIGHT)) {
for ( ; width > 0; --width) {
printchar (out, padchar);
++pc;
}
}
for ( ; *string ; ++string) {
printchar (out, *string);
++pc;
}
for ( ; width > 0; --width) {
printchar (out, padchar);
++pc;
}
return pc;
}
/*
* the following should be enough for 32 bit int
*/
#define PRINT_BUF_LEN 12
static int printi(char **out, long int i, int b, int sg, int width, int pad, int letbase)
{
char print_buf[PRINT_BUF_LEN];
register char *s;
register int t, neg = 0, pc = 0;
register unsigned long int u = i;
if (i == 0) {
print_buf[0] = '0';
print_buf[1] = '\0';
return prints (out, print_buf, width, pad);
}
if (sg && b == 10 && i < 0) {
neg = 1;
u = -i;
}
s = print_buf + PRINT_BUF_LEN-1;
*s = '\0';
while (u) {
t = u % b;
if( t >= 10 )
t += letbase - '0' - 10;
*--s = t + '0';
u /= b;
}
if (neg) {
if( width && (pad & PAD_ZERO) ) {
printchar (out, '-');
++pc;
--width;
}
else {
*--s = '-';
}
}
return pc + prints (out, s, width, pad);
}
static int print(char **out, const char *format, va_list args )
{
register int width, pad;
register int pc = 0;
char scr[2];
for (; *format != 0; ++format)
{
if (*format == '%')
{
++format;
width = pad = 0;
if (*format == '\0') break;
if (*format == '%') goto out;
if (*format == '-')
{
++format;
pad = PAD_RIGHT;
}
while (*format == '0')
{
++format;
pad |= PAD_ZERO;
}
for ( ; *format >= '0' && *format <= '9'; ++format)
{
width *= 10;
width += *format - '0';
}
if( *format == 's' )
{
register char *s = (char *)va_arg( args, int);
pc += prints (out, s?s:"(null)", width, pad);
continue;
}
if( *format == 'd' )
{
pc += printi (out, va_arg( args, int ), 10, 1, width, pad, 'a');
continue;
}
if( *format == 'x' )
{
pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'a');
continue;
}
if( *format == 'X' )
{
pc += printi (out, va_arg( args, int ), 16, 0, width, pad, 'A');
continue;
}
if( *format == 'u' )
{
pc += printi (out, va_arg( args, int ), 10, 0, width, pad, 'a');
continue;
}
if( *format == 'l' )
{
++format;
if( *format == 'u' )
{
pc += printi (out, va_arg( args, uint32_t ), 10, 0, width, pad, 'a');
continue;
}
}
if( *format == 'c' )
{
/* char are converted to int then pushed on the stack */
scr[0] = (char)va_arg( args, int );
scr[1] = '\0';
pc += prints (out, scr, width, pad);
continue;
}
}
else
{
out:
printchar (out, *format);
++pc;
}
}
if (out) **out = '\0';
va_end( args );
return pc;
}
/*
* A simple printf function. Support the following format:
* Code Format
* %c character
* %d signed decimal integers
* %i signed decimal integers, the same as %d
* %s a string of characters
* %o octal
* %x unsigned hexadecimal
* %X unsigned hexadecimal with uppercase
* %u unsigned decimal integers
* %lu 32 bits decimal unsigned long int=uint32_t
*/
int _printf(const char *format, ...)
{
va_list args;
va_start( args, format );
return print( 0, format, args );
}
int sprintf(char *out, const char *format, ...)
{
va_list args;
va_start( args, format );
return print( &out, format, args );
}
void _puts(const char *str)
{
while( *str != '\0' )
putchar(*str++);
putchar('\n');
}
void printmsg(void *msg, uint8_t printLen)
{
uint8_t i;
for(i=0; i < printLen; i++)
{
_printf("%x ", *( (uint8_t *)msg + i));
}
_printf("\n");
}
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/quanto/tos/lib/quanto/QuantoLog/RawUartMsg.h | #ifndef _UART_RAW_MSG_H
#define _UART_RAW_MSG_H
// The reason for this being more complicated than necessary is
// for efficiency
// We divide a single type byte to indicate the type of the record,
// i.e., the way to access the union, and also a subtype within each
// type.
enum {
MSG_TYPE_SINGLE_CHG = 0,
MSG_TYPE_MULTI_CHG = 1,
MSG_TYPE_COUNT_EV = 2,
MSG_TYPE_POWER_CHG = 3,
MSG_TYPE_FLUSH_REPORT = 4,
MSG_TYPE_OFFSET = 4,
SINGLE_CHG_NORMAL = 1,
SINGLE_CHG_ENTER_INT = 2,
SINGLE_CHG_EXIT_INT = 3,
SINGLE_CHG_BIND = 4,
MULTI_CHG_ADD = 1,
MULTI_CHG_REM = 2,
MULTI_CHG_IDL = 3,
//"Exported" constants
//Context changes for single-context resources
TYPE_SINGLE_CHG_NORMAL = (MSG_TYPE_SINGLE_CHG << MSG_TYPE_OFFSET) | SINGLE_CHG_NORMAL,
TYPE_SINGLE_CHG_ENTER_INT = (MSG_TYPE_SINGLE_CHG << MSG_TYPE_OFFSET) | SINGLE_CHG_ENTER_INT,
TYPE_SINGLE_CHG_EXIT_INT = (MSG_TYPE_SINGLE_CHG << MSG_TYPE_OFFSET) | SINGLE_CHG_EXIT_INT,
TYPE_SINGLE_CHG_BIND = (MSG_TYPE_SINGLE_CHG << MSG_TYPE_OFFSET) | SINGLE_CHG_BIND,
//Context changes for multi-context resources
TYPE_MULTI_CHG_ADD = (MSG_TYPE_MULTI_CHG << MSG_TYPE_OFFSET) | MULTI_CHG_ADD,
TYPE_MULTI_CHG_REM = (MSG_TYPE_MULTI_CHG << MSG_TYPE_OFFSET) | MULTI_CHG_ADD,
TYPE_MULTI_CHG_IDL = (MSG_TYPE_MULTI_CHG << MSG_TYPE_OFFSET) | MULTI_CHG_IDL,
//Power-state changes
TYPE_POWER_CHG = MSG_TYPE_POWER_CHG << MSG_TYPE_OFFSET,
//Count of events of a particular type.
TYPE_COUNT_EV = MSG_TYPE_COUNT_EV << MSG_TYPE_OFFSET,
TYPE_FLUSH_REPORT = MSG_TYPE_FLUSH_REPORT << MSG_TYPE_OFFSET,
QUANTO_LOG_AM_TYPE = 55,
AM_NX_ENTRY_T = QUANTO_LOG_AM_TYPE,
};
//12 bytes per entry.
typedef struct entry_t {
uint8_t type; //type of the entry, see enum above
uint8_t res_id; //resource id this entry refers to
uint32_t time; //local time of the node
uint32_t ic; //icount
union {
uint16_t act; //for single and multiple act changes
uint16_t powerstate; //for powerstate changes
uint16_t event_count; //for count entries
};
} entry_t;
#ifndef _QUANTO_C
typedef nx_struct nx_entry_t {
//nx_union {
nx_uint8_t type; //type of the entry, see enum above
//nx_union {
//nx_uint8_t entry_type:4;
//nx_uint8_t entry_subtype:4;
//};
//};
nx_uint8_t res_id; //resource id this entry refers to
nx_uint32_t time; //local time of the node
nx_uint32_t ic; //icount
nx_uint16_t arg;
// nx_union { // THIS UNION BREAKS MIG PYTHON
// nx_uint16_t arg;
// nx_uint16_t act; //for single and multiple act changes
// nx_uint16_t powerstate; //for powerstate changes
// nx_uint16_t event_count; //for count entries
// };
} nx_entry_t;
typedef nx_struct quanto_log_msg_t {
nx_entry_t entry;
} quanto_log_msg_t;
typedef nx_struct quanto_log_cnt_msg_t {
nx_uint8_t seq;
nx_entry_t entry;
} quanto_log_cnt_msg_t;
#endif //_QUANTO_C
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libnxt/error.c | /**
* NXT bootstrap interface; error handling code.
*
* Copyright 2006 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
* USA
*/
#include "error.h"
static const char const *err_str[] = {
"Success",
"NXT not found on USB bus",
"Error trying to configure the NXT USB link",
"NXT USB interface is already claimed by another program",
"USB write error",
"USB read error",
"SAM-BA protocol error",
"NXT handshake failed",
"File open/handling error",
"Invalid firmware image",
};
const char const *
nxt_str_error(nxt_error_t err)
{
return err_str[err];
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/driver/set_configuration.c | /* LIBUSB-WIN32, Generic Windows USB Library
* Copyright (c) 2002-2005 <NAME> <<EMAIL>>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include "libusb_driver.h"
NTSTATUS set_configuration(libusb_device_t *dev, int configuration,
int timeout)
{
NTSTATUS status = STATUS_SUCCESS;
URB urb, *urb_ptr = NULL;
USB_CONFIGURATION_DESCRIPTOR *configuration_descriptor = NULL;
USB_INTERFACE_DESCRIPTOR *interface_descriptor = NULL;
USBD_INTERFACE_LIST_ENTRY *interfaces = NULL;
int i, j, interface_number, desc_size;
DEBUG_PRINT_NL();
DEBUG_MESSAGE("set_configuration(): configuration %d", configuration);
DEBUG_MESSAGE("set_configuration(): timeout %d", timeout);
if(dev->config.value == configuration)
{
return STATUS_SUCCESS;
}
memset(&urb, 0, sizeof(URB));
if(!configuration)
{
urb.UrbHeader.Function = URB_FUNCTION_SELECT_CONFIGURATION;
urb.UrbHeader.Length = sizeof(struct _URB_SELECT_CONFIGURATION);
status = call_usbd(dev, &urb, IOCTL_INTERNAL_USB_SUBMIT_URB, timeout);
if(!NT_SUCCESS(status) || !USBD_SUCCESS(urb.UrbHeader.Status))
{
DEBUG_ERROR("set_configuration(): setting configuration %d failed: "
"status: 0x%x, urb-status: 0x%x",
configuration, status, urb.UrbHeader.Status);
return status;
}
dev->config.handle = urb.UrbSelectConfiguration.ConfigurationHandle;
dev->config.value = 0;
clear_pipe_info(dev);
return status;
}
configuration_descriptor = get_config_descriptor(dev, configuration,
&desc_size);
if(!configuration_descriptor)
{
DEBUG_ERROR("set_configuration(): getting configuration descriptor "
"failed");
return STATUS_INVALID_PARAMETER;
}
interfaces =
ExAllocatePool(NonPagedPool,(configuration_descriptor->bNumInterfaces + 1)
* sizeof(USBD_INTERFACE_LIST_ENTRY));
if(!interfaces)
{
DEBUG_ERROR("set_configuration(): memory allocation failed");
ExFreePool(configuration_descriptor);
return STATUS_NO_MEMORY;
}
memset(interfaces, 0, (configuration_descriptor->bNumInterfaces + 1)
* sizeof(USBD_INTERFACE_LIST_ENTRY));
interface_number = 0;
for(i = 0; i < configuration_descriptor->bNumInterfaces; i++)
{
for(j = interface_number; j < LIBUSB_MAX_NUMBER_OF_INTERFACES; j++)
{
interface_descriptor =
find_interface_desc(configuration_descriptor, desc_size, j, 0);
if(interface_descriptor)
{
interface_number = ++j;
break;
}
}
if(!interface_descriptor)
{
DEBUG_ERROR("set_configuration(): unable to find interface "
"descriptor at index %d", i);
ExFreePool(interfaces);
ExFreePool(configuration_descriptor);
return STATUS_INVALID_PARAMETER;
}
else
{
DEBUG_MESSAGE("set_configuration(): found interface %d",
interface_descriptor->bInterfaceNumber);
interfaces[i].InterfaceDescriptor = interface_descriptor;
}
}
urb_ptr = USBD_CreateConfigurationRequestEx(configuration_descriptor,
interfaces);
if(!urb_ptr)
{
DEBUG_ERROR("set_configuration(): memory allocation failed");
ExFreePool(interfaces);
ExFreePool(configuration_descriptor);
return STATUS_NO_MEMORY;
}
for(i = 0; i < configuration_descriptor->bNumInterfaces; i++)
{
for(j = 0; j < (int)interfaces[i].Interface->NumberOfPipes; j++)
{
interfaces[i].Interface->Pipes[j].MaximumTransferSize
= LIBUSB_MAX_READ_WRITE;
}
}
status = call_usbd(dev, urb_ptr, IOCTL_INTERNAL_USB_SUBMIT_URB, timeout);
if(!NT_SUCCESS(status) || !USBD_SUCCESS(urb_ptr->UrbHeader.Status))
{
DEBUG_ERROR("set_configuration(): setting configuration %d failed: "
"status: 0x%x, urb-status: 0x%x",
configuration, status, urb_ptr->UrbHeader.Status);
ExFreePool(interfaces);
ExFreePool(configuration_descriptor);
ExFreePool(urb_ptr);
return status;
}
dev->config.handle = urb_ptr->UrbSelectConfiguration.ConfigurationHandle;
dev->config.value = configuration;
clear_pipe_info(dev);
for(i = 0; i < configuration_descriptor->bNumInterfaces; i++)
{
update_pipe_info(dev, interfaces[i].Interface);
}
ExFreePool(interfaces);
ExFreePool(urb_ptr);
ExFreePool(configuration_descriptor);
return status;
}
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/platforms/nxtmote/platform_message.h | /*
* Copyright (c) 2005-2006 Intel Corporation
* All rights reserved.
*
* This file is distributed under the terms in the attached INTEL-LICENSE
* file. If you do not find these files, copies can be found by writing to
* Intel Research Berkeley, 2150 Shattuck Avenue, Suite 1300, Berkeley, CA,
* 94704. Attention: Intel License Inquiry.
*/
/**
* Dummy implementation to support the null platform.
*/
/**
* Adapted for nxtmote.
* @author <NAME>
*/
#ifndef PLATFORM_MESSAGE_H
#define PLATFORM_MESSAGE_H
//#include "Serial.h"
#include "Bc4.h"
typedef union message_header {
//serial_header_t serial;
bc4_header_t bc4;
} message_header_t;
typedef union message_footer {
bc4_footer_t bc4;
} message_footer_t;
typedef union message_metadata {
bc4_metadata_t bc4;
} message_metadata_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | berkeley/blip-2.0/support/sdk/c/blip/interface/queue.h | <filename>berkeley/blip-2.0/support/sdk/c/blip/interface/queue.h
#ifndef _QUEUE_H_
#define _QUEUE_H_
#include <pthread.h>
struct queue_entry;
struct queue_entry {
void *q_data;
struct queue_entry *q_next;
};
struct blocking_queue {
pthread_mutex_t mut;
pthread_cond_t cond;
struct queue_entry *head, *tail;
};
int queue_init(struct blocking_queue *q);
int queue_push(struct blocking_queue *q, void *data);
/* blocks until there's something to pop */
void *queue_pop(struct blocking_queue *q);
#endif
|
tinyos-io/tinyos-3.x-contrib | tinymulle/tos/platforms/mulle/softwarespi/MulleSpi.h | <gh_stars>1-10
/**
* @author <NAME>
*/
#ifndef __MULLESPI_H__
#define __MULLESPI_H__
#define UQ_MULLE_SOFTSPIMASTER "SoftSPIMasterC.SoftSPIPacket"
#endif // __MULLESPI_H__
|
tinyos-io/tinyos-3.x-contrib | antlab-polimi/sensors/baseStation/config.h | <filename>antlab-polimi/sensors/baseStation/config.h
/*
* Author: <NAME>
* contact: <EMAIL>
*/
#ifndef RADIOTEST_H
#define RADIOTEST_H
#define VIDEO_HEADER_LENGTH 3
#define PHOTO_HEADER_LENGTH 2
#define BIGMSG_DATA_SHIFT 6
#define PHOTO_DATA_LENGTH 40//(1<<BIGMSG_DATA_SHIFT)
#define VIDEO_DATA_LENGTH 40//64
//#define TOSH_DATA_LENGTH (BIGMSG_HEADER_LENGTH+VIDEO_DATA_LENGTH)
#define SRC 5
#define MAX_RTX 5
typedef nx_struct radio_count_msg {
nx_uint16_t counter;
} radio_count_msg_t;
enum {
AM_CMD_MSG = 4,
AM_IMG_STAT = 5,
AM_RADIO_CMD = 120,
AM_RADIO_IMGSTAT =127,
AM_RADIO_PHOTO = 128,
AM_RADIO_VIDEO = 129,
AM_RADIO_TIME_TEST = 130,
AM_RADIO_PKT_TEST = 131,
AM_RADIO_QUEUE_TEST = 132,
AM_VIDEO=112,
AM_PHOTO=110,
AM_RADIO_TIMER=121,
AM_TIME_TEST_MSG=113,
AM_PKT_TEST_MSG=114,
AM_QUEUE_TEST_MSG=115,
//AM_BIGMSG_FRAME_PART=0x6E,
};
typedef nx_struct video_radio_part{
nx_uint8_t frame_id;
nx_uint16_t part_id;
nx_uint8_t buf[VIDEO_DATA_LENGTH];
} video_radio_part_t;
typedef nx_struct photo_radio_part{
nx_uint16_t part_id;
nx_uint8_t buf[PHOTO_DATA_LENGTH];
} photo_radio_part_t;
typedef nx_struct cmd_msg{
nx_uint8_t cmd;
nx_uint16_t val1;
nx_uint16_t val2;
} cmd_msg_t;
typedef nx_struct pkt_test_msg{
nx_uint32_t rcv_inter_pkts;
nx_uint32_t rcv_bs_pkts;
nx_uint32_t rtx_camera_count;
nx_uint32_t rtx_inter_count;
nx_uint32_t frame_num;
} pkt_test_msg_t;
typedef nx_struct time_test_msg{
nx_uint32_t acquire;
nx_uint32_t process;
nx_uint32_t sending;
nx_uint32_t send_size;
nx_uint32_t id;
nx_uint32_t acq_period;
nx_uint32_t pause_time;
} time_test_msg_t;
typedef nx_struct queue_test_msg{
nx_uint16_t tx_pause;
nx_uint16_t queue_size;
nx_uint16_t queue_delta;
} queue_test_msg_t;
typedef nx_struct img_stat{
nx_uint8_t type;
nx_uint16_t width;
nx_uint16_t height;
nx_uint32_t data_size;
nx_uint32_t timeAcq;
nx_uint32_t timeProc;
nx_uint32_t tmp1;
nx_uint32_t tmp2;
nx_uint32_t tmp3;
nx_uint32_t tmp4;
} img_stat_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/tos/chips/motor/c_output.h | #ifndef C_OUTPUT_H
#define C_OUTPUT_H
//// c_output.h ////
typedef struct
{
UBYTE TimeCnt;
UBYTE Tmp;
}VARSOUTPUT;
#endif
|
tinyos-io/tinyos-3.x-contrib | dexma/tos/chips/adxl345/ADXL345.h | <reponame>tinyos-io/tinyos-3.x-contrib
#ifndef ADXL345_H
#define ADXL345_H
#define ADXL345_ADDRESS 0x53
//ADXL345 Registers Start
#define ADXL345_DEVID 0x00 // R // Device ID.
#define ADXL345_THRESH_TAP 0x1D // RW // Tap Threshold 62.5mg/LSB (0xFF = +16g)
#define ADXL345_OFSX 0x1E // RW // X-axis Offset 15.6mg/LSB
#define ADXL345_OFSY 0x1F // RW // Y-axis Offset 15.6mg/LSB
#define ADXL345_OFSZ 0x20 // RW // Z-axis Offset 15.6mg/LSB
#define ADXL345_DUR 0x21 // RW // Tap Duration 625us/LSB
#define ADXL345_LATENT 0x22 // RW // Tap Latency 1.25ms/LSB
#define ADXL345_WINDOW 0x23 // RW // Tap Window 1.25ms/LSB
#define ADXL345_THRESH_ACT 0x24 // RW // Activity threshold 62.5mg/LSB
#define ADXL345_THRESH_INACT 0x25 // RW // Inactivity Threshold 62.5mg/LSB
#define ADXL345_TIME_INACT 0x26 // RW // Inactivity Time. 1s/LSB
#define ADXL345_ACT_INACT_CTL 0x27 // RW // xis enable control for activity and inactivity detection.
#define ADXL345_THRESH_FF 0x28 // RW // Free-fall threshold. 62.5mg/LSB
#define ADXL345_TIME_FF 0x29 // RW // Free-fall Time 5ms/LSB (values 0x14 to 0x46 are recommended)
#define ADXL345_TAP_AXES 0x2A // RW // Axis control for tap/double tap
#define ADXL345_ACT_TAP_STATUS 0x2B // R // Source of tap/double tap
#define ADXL345_BW_RATE 0x2C // RW // Data rate and power control mode (default 0xA)
#define ADXL345_POWER_CTL 0x2D // RW // Power saving features control
#define ADXL345_INT_ENABLE 0x2E // RW // Interrupt enable control
#define ADXL345_INT_MAP 0x2F // RW // Interrupt mapping control
#define ADXL345_INT_SOURCE 0x30 // R // Source of interrupts
#define ADXL345_DATAFORMAT 0x31 // RW // Data format control
#define ADXL345_DATAX0 0x32 // R // X-Axis
#define ADXL345_DATAY0 0x34 // R // Y-Axis
#define ADXL345_DATAZ0 0x36 // R // Z-Axis
#define ADXL345_FIFO_CTL 0x38 // RW // FIFO control
#define ADXL345_FIFO_STATE 0x39 // R // FIFO status
//ADXL Registers End
#define ADXL345_MEASURE_MODE 0x08
#define ADXL345_STANDBY_MODE 0xF7
#define ADXL345_SLEEP_MODE 0x04
#define ADXL345_RANGE_2G 0
#define ADXL345_RANGE_4G 1
#define ADXL345_RANGE_8G 2
#define ADXL345_RANGE_16G 3
#define ADXL345_LOWRES 0
#define ADXL345_FULLRES 1
#define ADXL345_START_TIMEOUT 2000
//ADXL345 Driver States States
typedef enum {
ADXLCMD_START,
ADXLCMD_READ_REGISTER,
ADXLCMD_READ_DURATION,
ADXLCMD_READ_LATENT,
ADXLCMD_READ_WINDOW,
ADXLCMD_READ_THRESH_ACT, //TODO
ADXLCMD_READ_THRESH_INACT, //TODO
ADXLCMD_READ_TIME_INACT, //TODO
ADXLCMD_READ_ACT_INACT_CTL, //TODO
ADXLCMD_READ_THRESH_FF, //TODO
ADXLCMD_READ_TIME_FF, //TODO
ADXLCMD_READ_TAP_AXES, //TODO
ADXLCMD_READ_ACT_TAP_STATUS, //TODO
ADXLCMD_READ_BW_RATE, //TODO
ADXLCMD_READ_POWER_CTL, //TODO
ADXLCMD_READ_INT_ENABLE,
ADXLCMD_READ_INT_MAP,
ADXLCMD_READ_INT_SOURCE,
ADXLCMD_READ_X,
ADXLCMD_READ_Y,
ADXLCMD_READ_Z,
ADXLCMD_SET_RANGE,
ADXLCMD_STOP,
ADXLCMD_SLEEP,
ADXLCMD_INT,
ADXLCMD_SET_REGISTER,
ADXLCMD_SET_DURATION,
ADXLCMD_SET_LATENT,
ADXLCMD_SET_WINDOW,
ADXLCMD_SET_INT_MAP,
} adxl345_commands;
//ADXL345 Interruptions
typedef enum {
ADXLINT_NONE = 0x00,
ADXLINT_OVERRUN = 0x01,
ADXLINT_WATERMARK = 0x02,
ADXLINT_FREE_FALL = 0x04,
ADXLINT_INACTIVITY = 0x08,
ADXLINT_ACTIVITY = 0x10,
ADXLINT_DOUBLE_TAP = 0x20,
ADXLINT_SINGLE_TAP = 0x40,
ADXLINT_DATA_READY = 0x80,
} adxlint_state_t;
#endif
|
tinyos-io/tinyos-3.x-contrib | wsu/tools/simx/simx/lib/simx/pushback/pushback.h | #ifndef PUSHBACK_H
#define PUSHBACK_H
#include <stdarg.h>
#ifdef __cplusplus
extern "C" {
#endif
#if 0 /* To keep emacs indent nice */
}
#endif
/* PST-- SWIG 1.3.35 does not supported nested unions */
typedef union {
double d;
long l;
void *h;
} pushback_result_union_t;
/* possible error return values */
enum {
PUSHBACK_SUCCESS = 0,
PUSHBACK_ERROR = -1, /* general error */
PUSHBACK_DUPLICATE_NAME = -42,
PUSHBACK_INVOKE_ERROR,
PUSHBACK_EXPECTING_LONG,
PUSHBACK_UNKNOWN_PUSHBACK
};
/* possible values of pushback_result_t.type */
enum {
PUSHBACK_NONE = 1,
PUSHBACK_EXCEPTION,
PUSHBACK_LONG,
PUSHBACK_DOUBLE,
PUSHBACK_STRING
};
typedef struct {
/* Caller-responsible to free data.h if type is PUSHBACK_STRING */
unsigned char type;
pushback_result_union_t data;
} pushback_result_t;
typedef pushback_result_t (*pushback_fn_t)(void *pushback, /* pushback_t* */
va_list vargs);
typedef struct pushback {
char *name;
/* See http://docs.python.org/api/arg-parsing.html. May be NULL. */
char *format;
pushback_fn_t fn;
void *data;
/* Used to free pushback_t: name, format, data, etc... */
void (*dtor)(struct pushback *pb);
} pushback_t;
int simx_pushback_add(pushback_t pushback, int overwrite);
int simx_pushback_remove(char *name);
const char *simx_pushback_errstr(int err);
#ifdef __cplusplus
} /* extern "C" */
#endif
#ifdef __cplusplus
class Pushback {
public:
Pushback();
~Pushback();
int addPushback(pushback_t cb, bool overwrite);
int removePushback(char *name);
int invokePushback(char *name, pushback_result_t *result, ...);
};
#endif
#endif /* PUSHBACK_H */
|
tinyos-io/tinyos-3.x-contrib | tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/sim_mote.h | <reponame>tinyos-io/tinyos-3.x-contrib<filename>tcd/powertossim-z/tinyos_files/tinyos-2.0.2/tos/lib/tossim/sim_mote.h
/*
* "Copyright (c) 2005 Stanford University. All rights reserved.
*
* Permission to use, copy, modify, and distribute this software and
* its documentation for any purpose, without fee, and without written
* agreement is hereby granted, provided that the above copyright
* notice, the following two paragraphs and the author appear in all
* copies of this software.
*
* IN NO EVENT SHALL STANFORD UNIVERSITY BE LIABLE TO ANY PARTY FOR
* DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
* ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN
* IF STANFORD UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* STANFORD UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES,
* INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
* PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND STANFORD UNIVERSITY
* HAS NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES,
* ENHANCEMENTS, OR MODIFICATIONS."
*/
/**
* The C functions that allow TOSSIM-side code to access the SimMoteP
* component.
*
* @author <NAME>
* @date Nov 22 2005
*/
// $Id: sim_mote.h,v 1.1 2014/11/26 19:31:35 carbajor Exp $
#ifndef SIM_MOTE_H_INCLUDED
#define SIM_MOTE_H_INCLUDED
#ifdef __cplusplus
extern "C" {
#endif
long long int sim_mote_euid(int mote);
void sim_mote_set_euid(int mote, long long int euid);
long long int sim_mote_start_time(int mote);
void sim_mote_set_start_time(int mote, long long int t);
bool sim_mote_is_on(int mote);
void sim_mote_turn_on(int mote);
void sim_mote_turn_off(int mote);
int sim_mote_get_variable_info(int mote, char* name, void** addr, size_t* len);
void sim_mote_enqueue_boot_event(int mote);
#ifdef __cplusplus
}
#endif
#endif // SIM_MOTE_H_INCLUDED
|
tinyos-io/tinyos-3.x-contrib | iowa/T2.tsync/IAtsync/Tnbrhood.h | <filename>iowa/T2.tsync/IAtsync/Tnbrhood.h
#ifndef TS_TNBRHOOD
enum { NUM_NEIGHBORS = 12, // 12 because of payload in TinyOS msg
/*** Note: don't make NUM_NEIGHBORS too big or you'll
* have trouble with the health message -- see TnbrhoodM
* to see why this would be an error ***/
NUM_TYPES = 4, // how many AM_types for Neighbor iface
INIT_WAIT = 8*5, // five second wait between beacons
INIT_MAIN = 8*30, // one half minute to first main task
INIT_COUNT = 5, // number of initializing beacons
NORM_WAIT = 8*60, // normal time between beacons (1 min)
// NORM_WAIT = 8*60*2, // normal time between beacons (2 min)
// NORM_WAIT = 8*60*5, // normal time between beacons (5min)
// NORM_WAIT = 8*60*10, // normal time between beacons (10min)
// NORM_WAIT = 8*60*15, // normal time between beacons (15min)
EXCHANGE_INTERVAL = 2, // 2 slots (2/8 second)
EXCHANGE_LMARGIN = 1, // 1 slots "left" margin (1/8 second)
EXCHANGE_RMARGIN = 0, // 0 slots "right" margin (0/8 second)
HEALTH_CHECK_FREQ = 8*60, // check once per minute nbr health
OUTLIER_LIMIT = 16, // this is two seconds in eighth-sec units
// These modes are for both neighbor tables and control
MODE_NORMAL = 0x80,
MODE_RECOVERING = 0x40,
MODE_GOTSYNC = 0x20,
MODE_BIDIRECTIONAL = 0x04, // communication goes two-way
MODE_EVALUATE = 0x02, // protect from restart until evaluated
MODE_DISCARD = 0x01, // discard next message (a special case)
DEMO_SYNC = 3*8, // waiting period between beeps (3 sec)
MAX_MAC_DELAY = 16000, // max jiffies allowed for MAC delay
MAX_DRIFT = 65, // how many jiffies
// two motes can drift in one second
SANE_JIFFIES = 1500, // threshold for automatically sane
SKEW_PU = ONE_BYTE_TIME_UNIT*MAX_DRIFT,
// allowed # jiffies skew per 1-byte unit
SKEW_NOISE_WAIT = 8*60*12, // wait this long before calculating skew
SKEW_DIFFUSION_TIME = 8*60*3, // a few minutes to diffuse
// following are unused, but may be useful someday ...
// values of zero for radio power => do not adjust
CC2420_RADIO_POWER = 15, // 1 is lowest, 31 is highest
// 2 => max about 2 feet, 3 => up to 20 feet or so
MICA128_RADIO_POWER = 0,
// 99 => 0 inches,90 => 1-2 inches, 80 => 3 inches
// // 64 => 8 inches, 32 => 15 inches, 16 => 25 inches
// // 8, 4, 2, 0 => 3 feet or maybe a bit more
MICA2_RADIO_POWER = 0,
// Allowed (from datasheet, p.32) are
// 01,02,03,04,05,06,07,08,09,0A,0B,0C,0D,0E,0F,
// 40,50,60,70,80,90,C0,E0,FF which relate to range
// highly dependent on elevation, antenna, etc --
// typical could be (using antenna) 80 => 50meters,
// FF => 70meters, 09 => 15meters, 02 => 2meters
};
/**
* Neighborhood Structures (internal and for interface)
*/
typedef struct neighbor_t {
#ifdef TRACK
/*--- Local and RemoteVirtual are used in evaluation -----*/
/* " " also are used in containment */
timeSync_t Local; // our local clock
timeSync_t RemoteVirtual; // neighbor's virtual clock
/*--- oldRemoteLocal and oldLocal are used for slope -----*/
timeSync_t oldRemoteLocal; // an older value of RemoteLocal
timeSync_t oldLocal; // with accompanying Local clock
float slope; // current computed slope
uint8_t byteMem; // 8 bits:
// First four bits are for index into
// diffs array, below. Second four bits
// are history of recent beacons being
// "sane" or not; these bits are managed
// as a shift register (newest on front)
int8_t diffs[5]; // circular buffer: last 5 "diff" values for
// incoming beacons of this neighbor, but divided
// by 256 so as to fit into a single byte
#endif
/*--- state variables to track a neighbor ----------------*/
uint8_t connected; // indications of connectedness;
// implementation assumes NUM_TYPES <= 8
uint8_t rcvHist[NUM_TYPES]; // history of receive events
uint16_t Id; // identifier of the neighbor
#ifdef TRACK
uint8_t mode; // modality of the neighbor
int8_t eights; // number of 1/8 seconds this neighbor is
// ahead or behind the neighbor "base" time (range is +127
// to -127, but we floor and ceiling, so that +/-127 can
// signify anything out of range). The "base" time is
// approximately the median time of all in the neighborhood.
uint8_t DebugAge;
#endif
} neighbor_t;
typedef neighbor_t * neighborPtr;
#define TS_TNBRHOOD
#endif
|
tinyos-io/tinyos-3.x-contrib | eon/eon/src/simulator/omniloadpredictor.h | <filename>eon/eon/src/simulator/omniloadpredictor.h
#ifndef OMNILOADPREDICTOR_H
#define OMNILOADPREDICTOR_H
#include "simulator.h"
#include "nodes.h"
using namespace std;
extern int64_t current_time;
int get_tl_type(string &str);
int64_t get_tl_time(string& str);
#define LOAD_HISTORY 24
#define LOAD_DOUBT 8
#define EPOCH_HRS 1
int64_t last_time;
int64_t start_epoch;
int64_t event_count;
int64_t prediction;
int64_t history[LOAD_HISTORY];
uint8_t history_index;
void init_load_predictor()
{
start_epoch = 0;
event_count = 0;
prediction = 0;
memset(history, 0, sizeof(history));
}
void lp_path_done(int pathNum, int64_t timestamp)
{
return;
}
int64_t lp_predict_load(
vector<event_t*>* timeline,
int current_index,
int64_t hours)
{
int64_t result = 0;
int64_t index = current_index;
int64_t deadline;
int64_t ctime;
ctime = current_time;
deadline = current_time + (hours * 60 * 60 * 1000);
while (ctime < deadline && index < timeline->size())
{
event_t* evt = timeline->at(index);
int event_type = evt->type;
int64_t event_time = evt->time;
if (event_type == SERVICE_REQUEST)
{
result++;
}
ctime = event_time;
index++;
}
return result;
}
#endif
|
tinyos-io/tinyos-3.x-contrib | jhu/misc/KeepAlive.h | #ifndef KEEPALIVE_H
#define KEEPALIVE_H
nx_struct Beacon {
nx_uint32_t interval;
nx_uint32_t counter;
};
#endif
|
tinyos-io/tinyos-3.x-contrib | nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/install_filter.c | <reponame>tinyos-io/tinyos-3.x-contrib<filename>nxtmote/misc/src/libusb-win32/libusb-win32-src-0.1.12.1/src/install_filter.c
/* LIBUSB-WIN32, Generic Windows USB Library
* Copyright (c) 2002-2005 <NAME> <<EMAIL>>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <stdio.h>
#include "usb.h"
void usage(void);
void usage(void)
{
fprintf(stderr, "Usage: install-filter.exe [option]\n"
"Options:\n"
"-h prints this help message\n"
"-i installs the filter driver\n"
"-u uninstalls the filter driver\n");
}
int main(int argc, char **argv)
{
if(argc == 2)
{
if(!strcmp(argv[1], "-i"))
{
usb_install_service_np();
return 0;
}
if(!strcmp(argv[1], "-u"))
{
usb_uninstall_service_np();
return 0;
}
}
usage();
return 0;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.